public void ShouldCreateReceiptForBasket1()
        {
            var book = new Book {
                Id = 1, Name = "book", Price = 12.49m
            };
            var musicCd = new Music {
                Id = 2, Name = "music CD", Price = 14.99m
            };
            var chocolateBar = new Food {
                Id = 3, Name = "chocolate bar", Price = 0.85m
            };

            var cart = new Cart {
                Id = 1
            };

            cart.Products.Add(book);
            cart.Products.Add(musicCd);
            cart.Products.Add(chocolateBar);

            var container = ConfigBuilder.Register();

            using (var scope = container.BeginLifetimeScope())
            {
                var receiptUtility = scope.Resolve <IReceiptUtility>();
                var receipt        = receiptUtility.Create(cart);
                Assert.AreEqual("1 book: 12.49\r\n1 music CD: 16.49\r\n1 chocolate bar: 0.85\r\nSales Taxes: 1.50\r\nTotal: 29.83",
                                receipt);
            }
        }
        public void ShouldCreateReceiptForBasket2()
        {
            var chocolates = new Food {
                Id = 4, Name = "chocolates", Price = 10.0m, ProductOrigin = EProductOrigin.Imported
            };
            var perfume = new Perfume {
                Id = 5, Name = "bottle of perfume", Price = 47.5m, ProductOrigin = EProductOrigin.Imported
            };

            var cart = new Cart {
                Id = 2
            };

            cart.Products.Add(chocolates);
            cart.Products.Add(perfume);
            var container = ConfigBuilder.Register();

            using (var scope = container.BeginLifetimeScope())
            {
                var receiptUtility = scope.Resolve <IReceiptUtility>();
                var receipt        = receiptUtility.Create(cart);
                Assert.AreEqual("1 imported chocolates: 10.5\r\n1 imported bottle of perfume: 54.65\r\nSales Taxes: 7.65\r\nTotal: 65.15",
                                receipt);
            }
        }
示例#3
0
        private static async Task Main(string[] args)
        {
            var configuration = ConfigBuilder.ValidateAndBuildConfiguration();

            var serviceProvider = new ServiceCollection()
                                  .AddSingleton(configuration)
                                  .AddSingleton <TrackingService>()
                                  .AddSingleton <IDataProvider, UserInputTimeDataProvider>()
                                  .AddSingleton <IActivityEvents, ActivityEvents>()
                                  .AddSingleton <IEventSender, EventSender>()
                                  .AddSingleton <ITrayIconService, TrayIconService>()
                                  .AddHttpClient <IEventSender, EventSender>(client =>
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", configuration["Token"]);
#if DEBUG
                client.BaseAddress = new Uri("http://localhost:7071/");
#else
                client.BaseAddress = new Uri("https://screentimetracker.azurewebsites.net");
#endif
            })
                                  .Services
                                  .BuildServiceProvider();

            serviceProvider.GetService <ITrayIconService>().InitTrayIcon();

            serviceProvider.GetService <IEventSender>();
            using var trackingService = serviceProvider.GetService <TrackingService>();

            trackingService.StartListening();

            await Task.Delay(-1);
        }
示例#4
0
        /// <summary> Builds instance responsible for composing object graph. </summary>
        private static CompositionRoot BuildCompositionRoot(Action <IContainer, IConfigSection> action, ITrace trace)
        {
            // create entry point for library functionallity using default configuration overriding some properties
            var root = new CompositionRoot(new Container(), ConfigBuilder.GetDefault().SetIndex("index").Build())
                       // override library's default services with demo specific implementations
                       .RegisterAction((container, config) =>
            {
                container
                .RegisterInstance <ITrace>(trace)
                .Register(Component.For <IPathResolver>().Use <UnityPathResolver>())
                .Register(Component.For <INetworkService>().Use <UnityNetworkService>())
                .Register(Component.For <IMapDataLibrary>().Use <MapDataLibrary>());
            })
                       // override with scene specific implementations
                       .RegisterAction(action)
                       // setup object graph
                       .Setup();

            // Register default data storages: one keeps data on disk, another one - in memory.
            // You are not limited with these two: you can add more disk and/or memory storages.
            // NOTE First registered storage will be used to save map data received from downloaded data
            var mapDataStore = root.GetService <IMapDataStore>();

            mapDataStore.Register(MapDataStorages.PersistentStorageKey, @"index/data");
            mapDataStore.Register(MapDataStorages.TransientStorageKey);

            // Enable mesh caching.
            root.GetService <IMapDataLibrary>().EnableCache();

            return(root);
        }
    public IEnumerable <FileResult> RealizeFileResults(ConfigBuilder builder)
    {
        foreach (var build in builder.Builders)
        {
            switch (build)
            {
            case WebApiBuilder webApiBuilder:
                yield return(Build(webApiBuilder));

                break;

            case ClassBuilder classBuilder:
                yield return(Build(classBuilder));

                break;

            case InterfaceBuilder interfaceBuilder:
                yield return(Build(interfaceBuilder));

                break;

            case ApiDefBuilder apiDefBuilder:
                yield return(Build(apiDefBuilder));

                break;

            default:
                break;
            }
        }
    }
        public void ShouldCreateReceiptForBasket3()
        {
            var importedPerfume = new Perfume {
                Id = 6, Name = "bottle of perfume", Price = 27.99m, ProductOrigin = EProductOrigin.Imported
            };
            var perfume = new Perfume {
                Id = 7, Name = "bottle of perfume", Price = 18.99m
            };
            var pills = new Medical {
                Id = 8, Name = "packet of headache pills", Price = 9.75m
            };
            var chocolates = new Food {
                Id = 9, Name = "box of chocolates", Price = 11.25m, ProductOrigin = EProductOrigin.Imported
            };

            var cart = new Cart {
                Id = 3
            };

            cart.Products.Add(importedPerfume);
            cart.Products.Add(perfume);
            cart.Products.Add(pills);
            cart.Products.Add(chocolates);
            var container = ConfigBuilder.Register();

            using (var scope = container.BeginLifetimeScope())
            {
                var receiptUtility = scope.Resolve <IReceiptUtility>();
                var receipt        = receiptUtility.Create(cart);
                Assert.AreEqual("1 imported bottle of perfume: 32.19\r\n1 bottle of perfume: 20.89\r\n1 packet of headache pills: 9.75\r\n1 imported box of chocolates: 11.85\r\nSales Taxes: 6.70\r\nTotal: 74.68",
                                receipt);
            }
        }
示例#7
0
    public void ApplyOverrides(List <ConfigEntry> overrideConfigEntries)
    {
                #if METRICS_ENABLED && INCLUDE_DEV_METRICS
        Metrics.Start(GetType().Name + ":SetOverrides");
        #endif

        // Overrides are only valid if there was initially a default config entry value.
        // This is mainly to make sure we always get back to the default configuration whenever the player changes accounts.
        HashSet <string> validConfigKeys = new HashSet <string>();
        foreach (ConfigEntry entry in _cachedConfigEntries)
        {
            validConfigKeys.Add(entry.Key);
        }
        List <ConfigEntry> validOverrideConfigs = new List <ConfigEntry>();
        foreach (ConfigEntry entry in overrideConfigEntries)
        {
            if (validConfigKeys.Contains(entry.Key))
            {
                validOverrideConfigs.Add(entry);
            }
        }

        ConfigBuilder <Config> configBuilder = new ConfigBuilder <Config>(this);
        if (_hasOverridesApplied)
        {
            configBuilder.Populate(_cachedConfigEntries);
        }
        _hasOverridesApplied = true;
        configBuilder.Populate(validOverrideConfigs);

                #if METRICS_ENABLED && INCLUDE_DEV_METRICS
        Metrics.End(GetType().Name + ":SetOverrides");
        #endif
    }
示例#8
0
        public async Task LoadRulesShouldOnlyReturnPackagesWhenOnlyGivenPackages()
        {
            // Arrange
            var config = new ConfigBuilder()
                         .WithPackage("package1", "1.2")
                         .WithPackage("package2", "0.3")
                         .ToString();

            using var file = new TempFile();
            await File.WriteAllTextAsync(file, config);

            var rulesFactory = Substitute.For <IRuleFactory>();

            rulesFactory.Construct(Arg.Any <PackageReferenceRuleData>()).Returns(Substitute.For <IRule>());
            var output = Substitute.For <IOutput>();
            var sut    = new RulesLoader(rulesFactory, output);

            // Act
            var actual = await sut.LoadRules(file).ToListAsync();

            // Assert
            Assert.Equal(2, actual.Count);
            rulesFactory.Received(2).Construct(Arg.Any <PackageReferenceRuleData>());
            rulesFactory.DidNotReceive().Construct(Arg.Any <PropertyRuleData>());
            rulesFactory.DidNotReceive().Construct(Arg.Any <ProjectReferenceRuleData>());
        }
    public async Task Handler()
    {
        resetEvent = new ManualResetEvent(false);
        var configuration = ConfigBuilder.BuildDefaultConfig("WithNoTracingTests");

        configuration.DisableRetries();

        configuration.Notifications.Errors.MessageSentToErrorQueue +=
            (sender, retry) =>
        {
            exception = retry.Exception;
            resetEvent.Set();
        };

        var endpoint = await Endpoint.Start(configuration);

        await endpoint.SendLocal(new StartHandler());

        if (!resetEvent.WaitOne(TimeSpan.FromSeconds(2)))
        {
            throw new Exception("No Set received.");
        }

        await endpoint.Stop();

        Approvals.Verify(exception.Message);
    }
示例#10
0
    async Task <IEnumerable <LogEventEx> > Send(object message)
    {
        var logs      = new List <LogEvent>();
        var eventSink = new EventSink
        {
            Action = logs.Add
        };

        var loggerConfiguration = new LoggerConfiguration();

        loggerConfiguration.Enrich.WithExceptionDetails();
        loggerConfiguration.MinimumLevel.Verbose();
        loggerConfiguration.WriteTo.Sink(eventSink);
        Log.Logger = loggerConfiguration.CreateLogger();
        LogManager.Use <SerilogFactory>();

        var configuration  = ConfigBuilder.BuildDefaultConfig("SerilogTests");
        var serilogTracing = configuration.EnableSerilogTracing();

        serilogTracing.EnableSagaTracing();
        serilogTracing.EnableMessageTracing();

        var recoverability = configuration.Recoverability();

        recoverability.Delayed(settings =>
        {
            settings.TimeIncrease(TimeSpan.FromMilliseconds(1));
            settings.NumberOfRetries(1);
        });
        recoverability.Immediate(settings => { settings.NumberOfRetries(1); });

        configuration.Notifications.Errors.MessageSentToErrorQueue +=
            (sender, retry) => { resetEvent.Set(); };

        var endpoint = await Endpoint.Start(configuration);

        var sendOptions = new SendOptions();

        sendOptions.SetMessageId("00000000-0000-0000-0000-000000000001");
        sendOptions.RouteToThisEndpoint();
        await endpoint.Send(message, sendOptions);

        if (!resetEvent.WaitOne(TimeSpan.FromSeconds(5)))
        {
            throw new Exception("No Set received.");
        }

        await endpoint.Stop();

        Log.CloseAndFlush();

        return(logs.Select(x =>
                           new LogEventEx
        {
            MessageTemplate = x.MessageTemplate,
            Level = x.Level,
            Properties = x.Properties,
            Exception = x.Exception,
        }));
    }
示例#11
0
        public void ConfigureContainer(Container container)
        {
            var config     = new ConfigBuilder();
            var collection = new AssemblyCollection()
                             .AddPublicTypesAssemblies(GetType().GetTypeInfo().Assembly,
                                                       typeof(Ref).Assembly,
                                                       typeof(DomainRef).Assembly);

            config.Add(new ExistAll.SimpleConfig.Binders.ConfigurationBinder(Configuration));

            var settings = config.Build(collection.Assemblies, new ConfigOptions()
            {
                ConfigSuffix = "Settings"
            });

            foreach (var setting in settings)
            {
                container.RegisterSingleton(setting.Key, setting.Value);
            }

            container.RegisterSingleton <ISystemClock, SystemClock>();
            container.RegisterSingleton <ISiteCrawler, HttpSiteCrawler>();
            container.RegisterDecorator <ISiteCrawler, CacheHttpSiteCrawler>();
            container.RegisterSingleton <ISiteRepository, SiteRepository>();
            container.RegisterSingleton <ICrawlerSiteRequestValidator, SiteInfoRequestValidator>();
        }
示例#12
0
        public async Task LoadRulesShouldNotLoadUnconstructableRules()
        {
            // Arrange
            var config = new ConfigBuilder()
                         .WithProperty(new PropertyRuleData())
                         .WithPackage(new PackageReferenceRuleData())
                         .WithProjectReference(new ProjectReferenceRuleData())
                         .ToString();

            using var file = new TempFile();
            await File.WriteAllTextAsync(file, config);

            var rulesFactory = Substitute.For <IRuleFactory>();

            rulesFactory.Construct(Arg.Any <PackageReferenceRuleData>()).Returns((IRule?)null);
            rulesFactory.Construct(Arg.Any <PropertyRuleData>()).Returns((IRule?)null);
            rulesFactory.Construct(Arg.Any <ProjectReferenceRuleData>()).Returns((IRule?)null);
            var output = Substitute.For <IOutput>();
            var sut    = new RulesLoader(rulesFactory, output);

            // Act
            var actual = await sut.LoadRules(file).ToListAsync();

            // Assert
            Assert.Empty(actual);
            rulesFactory.Received(1).Construct(Arg.Any <PropertyRuleData>());
            rulesFactory.Received(1).Construct(Arg.Any <PackageReferenceRuleData>());
            rulesFactory.Received(1).Construct(Arg.Any <ProjectReferenceRuleData>());
        }
示例#13
0
        public override string Get()
        {
            StringBuilder header = new StringBuilder();

            TagBuilder.Begin(header, "thead", true);
            TagBuilder.Begin(header, "tr", true);
            TagBuilder.Begin(header, "th", true);
            TagBuilder.EndTag(header, "th");

            foreach (Column column in this.Columns)
            {
                string cssClass = string.Empty;

                if ((new[] { "System.Single", "System.Double", "System.Decimal" }).Contains(column.Type.FullName))
                {
                    cssClass = " class='text right'";
                }

                TagBuilder.Begin(header, "th");
                header.Append(cssClass);
                TagBuilder.Close(header);


                header.Append(ScrudLocalizationHelper.GetResourceString(this.Config.ResourceAssembly,
                                                                        ConfigBuilder.GetResourceClassName(this.Config), column.ColumnName));
                TagBuilder.EndTag(header, "th");
            }


            TagBuilder.EndTag(header, "tr");
            TagBuilder.EndTag(header, "thead");

            return(header.ToString());
        }
示例#14
0
        /// <summary> Builds instance responsible for composing object graph. </summary>
        private static CompositionRoot BuildCompositionRoot(IContainer container, ITrace trace)
        {
            // create configuration from default overriding some properties
            var config = ConfigBuilder.GetDefault()
                         .SetIndex("Index/")
                         .Build();

            // create entry point for utymap functionallity
            var compositionRoot = new CompositionRoot(container, config)
                                  // override default services with unity specific implementation
                                  .RegisterAction((c, _) => c.RegisterInstance <ITrace>(trace))
                                  .RegisterAction((c, _) => c.Register(Component.For <IPathResolver>().Use <UnityPathResolver>()))
                                  .RegisterAction((c, _) => c.Register(Component.For <INetworkService>().Use <UnityNetworkService>()))
                                  .RegisterAction((c, _) => c.Register(Component.For <IMapDataLibrary>().Use <MapDataLibrary>()))
                                  // register scene specific services (plugins)
                                  .RegisterAction((c, _) => c.Register(Component.For <UnityModelBuilder>().Use <UnityModelBuilder>()))
                                  .RegisterAction((c, _) => c.Register(Component.For <MaterialProvider>().Use <MaterialProvider>()))
                                  // register default mapcss
                                  .RegisterAction((c, _) => c.Register(Component.For <Stylesheet>().Use <Stylesheet>(@"MapCss/default/default.mapcss")));

            // setup object graph
            compositionRoot.Setup();

            return(compositionRoot);
        }
示例#15
0
        private static async Task Main()
        {
            var config           = new ConfigBuilder(".").Build();
            var parser           = new ReadSharpParser();
            var emailSender      = new MailgunSender(config.MailGunSenderOptions.ApiKey, config.MailGunSenderOptions.HostEmail);
            var pocketClientMock = new Mock <IPocketClient>();

            pocketClientMock.Setup(x =>
                                   x.Get(
                                       It.IsAny <State>(),
                                       It.IsAny <bool>(),
                                       It.IsAny <string>(),
                                       It.IsAny <ContentType>(),
                                       It.IsAny <Sort>(),
                                       It.IsAny <string>(),
                                       It.IsAny <string>(),
                                       It.IsAny <DateTime>(),
                                       It.IsAny <int>(),
                                       It.IsAny <int>(),
                                       It.IsAny <CancellationToken>())).Returns(
                Task.FromResult(
                    (IEnumerable <PocketItem>) new PocketItem[] {
                new PocketItem {
                    Uri = new Uri("https://blog.wikimedia.org/2018/04/20/why-it-took-a-long-time-to-build-that-tiny-link-preview-on-wikipedia/")
                }
            }
                    )
                );

            var sender = new ArticleSender(pocketClientMock.Object, parser, emailSender, config.ServiceDomain);
            await sender.SendArticlesAsync(new User { KindleEmail = "*****@*****.**", Token = "testtoken" });
        }
    public async Task Handler()
    {
        Exception?exception     = null;
        var       resetEvent    = new ManualResetEvent(false);
        var       configuration = ConfigBuilder.BuildDefaultConfig("WithNoTracingTests");

        configuration.DisableRetries();
        configuration.RegisterComponents(_ => _.AddSingleton(resetEvent));

        var recoverability = configuration.Recoverability();

        recoverability.Failed(_ => _
                              .OnMessageSentToErrorQueue((message, _) =>
        {
            exception = message.Exception;
            resetEvent.Set();
            return(Task.CompletedTask);
        }));

        var endpoint = await Endpoint.Start(configuration);

        await endpoint.SendLocal(new StartHandler());

        if (!resetEvent.WaitOne(TimeSpan.FromSeconds(2)))
        {
            throw new("No Set received.");
        }

        await endpoint.Stop();

        await Verify(exception !.Message);
    }
        private static Serilog.Core.Logger CreateSeriLogger()
        {
            SerilogOptions options = ConfigBuilder <SerilogOptions> .GetConfig("serilog");

            string currentPath = Path.GetDirectoryName(typeof(LoggerFactory).Assembly.Location) ?? "";
            var    folderPath  = Path.Combine(currentPath, "..\\..\\..\\..\\..\\");
            string env         = Environment.GetEnvironmentVariable("NET_ENVIRONMENT") ?? "development";

            var builer = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.RollingFile(pathFormat: $"{folderPath}/logs/roll/log-{{Date}}.txt",
                                              flushToDiskInterval: new TimeSpan(0, 0, 0, 500))
                         .WriteTo.File(path: $"{folderPath}/logs/log.txt",
                                       flushToDiskInterval: new TimeSpan(0, 0, 0, 500));

            if (!string.IsNullOrEmpty(options.SeqReader))
            {
                builer.WriteTo.Seq(serverUrl: options.SeqReader, period: TimeSpan.Zero);
            }

            var serilog = builer
                          .WriteTo.ColoredConsole()
                          .Enrich.FromLogContext()
                          .Enrich.WithThreadId()
                          .Enrich.WithMachineName()
                          .Enrich.WithProperty("Application", options.AppName)
                          .Enrich.WithProperty("SessionId", Guid.NewGuid())
                          .Enrich.WithProperty("Environment", env)
                          .CreateLogger();

            return(serilog);
        }
示例#18
0
        public void ExtractWebApiAddress_Length_Success()
        {
            IConfigBuilder configBuilder = new ConfigBuilder();
            var            webApiAddr    = configBuilder.GetWebApiAddress();

            Assert.IsTrue(webApiAddr.Length > 0);
        }
示例#19
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log,
            ExecutionContext context)
        {
            var reportedUrlRow = new ReportedUrl
            {
                PartitionKey = "reportedUrl",
                RowKey       = Guid.NewGuid().ToString(),
                Url          = req.Query["url"]
            };

            Config config = new ConfigBuilder(context.FunctionAppDirectory).Build();

            await SaveReportedUrl(reportedUrlRow, config.StorageConnectionString);

            log.LogInformation($"Reported url: {reportedUrlRow.Url}");

            return(new HtmlResponseMessage(
                       HttpStatusCode.OK,
                       $@"<html>
                <head>
                    <meta charset=""UTF-8"">
                    <title>Article reported</title>
                </head>
                <body>
                    <h1>Thank you for submiting that article!</h1>
                    <p>We'll investigate {reportedUrlRow.Url} soon.</p>
                </body>
                </html>"));
        }
示例#20
0
        public void ExtractWebApiAddress_Success()
        {
            IConfigBuilder configBuilder = new ConfigBuilder();
            var            webApiAddr    = configBuilder.GetWebApiAddress();

            Assert.IsNotNull(webApiAddr);
        }
        private void DriverConfig(ConfigBuilder configBuilder)
        {
            if (!string.IsNullOrEmpty(data.userAgent))
            {
                configBuilder.WithUserAgent(data.userAgent);
            }

            if (data.resolverRegistered)
            {
                configBuilder.WithResolver(new ListAddressResolver(Control, data.uri));
            }

            if (data.connectionTimeoutMs > 0)
            {
                configBuilder.WithConnectionTimeout(TimeSpan.FromMilliseconds(data.connectionTimeoutMs));
            }

            if (data.maxConnectionPoolSize.HasValue)
            {
                configBuilder.WithMaxConnectionPoolSize(data.maxConnectionPoolSize.Value);
            }

            if (data.connectionAcquisitionTimeoutMs.HasValue)
            {
                configBuilder.WithConnectionAcquisitionTimeout(TimeSpan.FromMilliseconds(data.connectionAcquisitionTimeoutMs.Value));
            }

            SimpleLogger logger = new SimpleLogger();

            configBuilder.WithLogger(logger);
        }
示例#22
0
        public void TestMergingDictionaryToConfig()
        {
            var configRoot =
                new ConfigBuilder()
                .MergeDictionary(
                    new Dictionary <object, object>
            {
                {
                    "aaa", new Dictionary <object, object>
                    {
                        { "bbb", 999 },
                    }
                }
            }
                    )
                .MergeDictionary(
                    new Dictionary <object, object>
            {
                {
                    "aaa", new Dictionary <object, object>
                    {
                        { "ccc", 111 },
                    }
                },
                {
                    "xxx", 555
                }
            }
                    ).Build();

            Assert.AreEqual(2, configRoot.GetKeys().Count());
            Assert.AreEqual(999, configRoot.Query("aaa", "bbb").AsInt());
            Assert.AreEqual(111, configRoot.Query("aaa", "ccc").AsInt());
            Assert.AreEqual(555, configRoot.Query("xxx").AsInt());
        }
示例#23
0
        private void BeforeBuildInitService()
        {
            SmartSqlConfig                  = ConfigBuilder.Build(_importProperties);
            SmartSqlConfig.Alias            = Alias;
            SmartSqlConfig.LoggerFactory    = LoggerFactory;
            SmartSqlConfig.DataSourceFilter = DataSourceFilter ?? new DataSourceFilter(SmartSqlConfig.LoggerFactory);
            if (_isCacheEnabled.HasValue)
            {
                SmartSqlConfig.Settings.IsCacheEnabled = _isCacheEnabled.Value;
            }

            if (InvokeSucceeded != null)
            {
                SmartSqlConfig.InvokeSucceedListener.InvokeSucceeded += (sender, args) =>
                {
                    InvokeSucceeded(args.ExecutionContext);
                };
            }

            SmartSqlConfig.SqlParamAnalyzer = new SqlParamAnalyzer(SmartSqlConfig.Settings.IgnoreParameterCase,
                                                                   SmartSqlConfig.Database.DbProvider.ParameterPrefix);

            InitDeserializerFactory();
            InitFilters();
            BuildPipeline();
        }
示例#24
0
        public static CompositionRoot GetCompositionRoot(GeoCoordinate worldZeroPoint,
                                                         Action <IContainer, IConfigSection> action)
        {
            // create default container which should not be exposed outside
            // to avoid Service Locator pattern.
            IContainer container = new Container();

            // create default application configuration
            var config = ConfigBuilder.GetDefault()
                         .SetIndex(IndexPath)
                         .Build();

            // initialize services
            var root = new CompositionRoot(container, config)
                       .RegisterAction((c, _) => c.Register(Component.For <ITrace>().Use <ConsoleTrace>()))
                       .RegisterAction((c, _) => c.Register(Component.For <IPathResolver>().Use <TestPathResolver>()))
                       .RegisterAction((c, _) => c.Register(Component.For <Stylesheet>().Use <Stylesheet>(DefaultMapCss)))
                       .RegisterAction((c, _) => c.Register(Component.For <IProjection>().Use <CartesianProjection>(worldZeroPoint)))
                       .RegisterAction(action)
                       .Setup();

            // Register default data stores to simplify test setup. The order is important
            var mapDataStore = root.GetService <IMapDataStore>();

            mapDataStore.Register(TransientStorageKey);
            mapDataStore.Register(PersistentStorageKey, IndexPath + "/data");

            return(root);
        }
示例#25
0
        public void ApplyParameters_Minimal()
        {
            const string connectionString = "some connection string";
            const string querySql         = "select top 1 * from nothing";

            var config = new ConfigBuilder().Build().ToConfiguration();

            config.ApplyParameters(new Parameters
            {
                ConnectionString = connectionString,
                QuerySql         = querySql
            });

            Assert.Equal(connectionString, config.ConnectionString);
            Assert.Equal(querySql, config.Query);
            Assert.Equal(_defaults.MaxExecutionSeconds, config.ExecutionTime.TotalSeconds);
            Assert.Equal(_defaults.QueryIntervalMs, config.QueryIntervalMs);
            Assert.Equal(_defaults.OutputToConsole, config.OutputToConsole);
            Assert.Equal(_defaults.OutputToFile, config.OutputToFile);
            Assert.Equal(_defaults.FileName, config.FileName);
            Assert.Equal(_defaults.IfFileExists, config.IfFileExists);
            Assert.Equal(_defaults.MaxFileSizeKb, config.MaxFileSizeKb);
            Assert.Equal(_sqlSettings.QueryTimeoutSeconds, config.QueryTimeoutSeconds);
            Assert.Equal(_sqlSettings.TransactionIsolationLevel, config.TransactionIsolationLevel);
        }
示例#26
0
        public override string Get()
        {
            StringBuilder grid = new StringBuilder();

            using (DataTable table = this.GetTable())
            {
                if (table.Rows.Count.Equals(0))
                {
                    return("<div class='ui message'>No record found</div>");
                }

                TagBuilder.Begin(grid, "table");
                TagBuilder.AddId(grid, "FormGridView");
                TagBuilder.AddClass(grid, ConfigBuilder.GetGridViewCssClass(this.Config));
                TagBuilder.AddStyle(grid, ConfigBuilder.GetGridViewWidth(this.Config) + ";white-space: nowrap;");
                TagBuilder.Close(grid);

                List <Column> columns = GetColumns(table).ToList();

                HeaderRow header = new HeaderRow(this.Config, columns);
                grid.Append(header.Get());

                using (Body body = new Body(this.Config, table, columns))
                {
                    grid.Append(body.Get());
                }


                TagBuilder.EndTag(grid, "table");
            }


            return(grid.ToString());
        }
示例#27
0
        public void Initialize()
        {
            _configBuilder = new ConfigBuilder("Balances");
            Consumer       = new ApiConsumer(_configBuilder, null);

            prepareTestData().Wait();
        }
示例#28
0
        public IntegrationTestDbFixture()
        {
            var loggerFactory = new LoggerFactory();
            var configuration = ConfigBuilder.GetConfiguration(Constants.CurrentEnvironment)
                                .AddJsonFile("appsettings.json")
                                .AddEnvironmentVariables()
                                .Build();

            ConnectionStrings.SetOneTime(configuration);
            ApplicationSettings.SetOneTime(configuration);

            var instanceRegistrations = new List <Func <ContainerConfiguration, ExportDescriptorProvider> >
            {
                r => r.WithInstance(loggerFactory),
                r => r.WithInstance(configuration)
            };

            ClassFactory = Bootstrapper.Init(APP_PREFIX, instanceRegistrations);

            var migrator = GetTestDbMigration();

            if (migrator == null)
            {
                throw new NoNullAllowedException("dbMigration not found..");
            }

            migrator.Execute();
        }
示例#29
0
        public void RunGame()
        {
            _logger.Start();

            var config = ConfigBuilder.GetDefault()
                         .Build();

            var componentRoot = TestHelper.GetGameRunner(_container, config);

            _messageBus   = _container.Resolve <IMessageBus>();
            _trace        = _container.Resolve <ITrace>();
            _tileListener = new DemoTileListener(_messageBus, _logger);

            // start game on default position
            componentRoot.RunGame(StartGeoCoordinate);

            _geoPositionObserver = _container.Resolve <ITileController>();
            _mapPositionObserver = _container.Resolve <ITileController>();

            _messageBus.AsObservable <GeoPosition>().Do(position =>
            {
                _trace.Debug(LogTag, "GeoPosition: {0}", position.ToString());
                _geoPositionObserver.OnNext(position.Coordinate);
            }).Subscribe();

            _messageBus.AsObservable <Vector2d>().Do(position =>
            {
                _trace.Debug(LogTag, "MapPosition: {0}", position.ToString());
                _mapPositionObserver.OnNext(position);
            }).Subscribe();
        }
示例#30
0
        /// <summary>
        /// Builds configuration, i.e. load values from config file and merge them with hard coded values.
        /// Have to be called before accessing static configuration properties.
        /// <para />
        /// Why not call this via static constructor?
        /// Because if an error occurs, not even logger is available yet.
        /// </summary>
        public static void Build()
        {
            int start = Environment.TickCount;

            ConfigBuilder builder = new ConfigBuilder();

            ConfigException ce = null;

            try { builder.BuildConfig(); }
            catch (ConfigException e)  // log exceptions thrown in Player.Conf.Build only here
            {
                logger.Error(ExceptionUtil.Format(e));
                ce = e;
            }

            Global  = builder.GlobalConfig;
            Scanner = builder.ScannerConfig;
            Style   = builder.StyleConfig;

            logger.Trace("Build() needed {0}ms", (Environment.TickCount - start));

            if (ce != null)  // signal error
            {
                throw ce;
            }
        }
示例#31
0
 public static void Register()
 {
     var options = new ConfigOptions();
     var configBuilder = new ConfigBuilder(options,
         (configuration, builder) =>
         {
             builder.RegisterType<DebugLogger>().As<ILogger>();
             builder.RegisterType<Mapper>().As<IMapper>();
             builder.RegisterType<BankContext>().As<IContext>();
             builder.RegisterType<EntityStubFactory>().As<IEntityStubFactory>();
             builder.RegisterType<RepositoryFactory>().As<IRepositoryFactory>();
             builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
             builder.RegisterType<ExpressionBuilder>().As<IExpressionBuilder>();
             builder.RegisterType<CurrencyService>().As<ICurrencyService>();
             builder.RegisterType<CurrencyRateFactory>().As<ICurrencyRateFactory>();
             builder.RegisterType<CurrencyRateService>().As<ICurrencyRateService>();
             builder.RegisterType<ExchangeService>().As<IExchangeService>();
         });
     HttpConfiguration config = ServiceConfig.Initialize(configBuilder);
     AutoMapper.Mapper.Initialize(InitializeConfiguration);
 }
示例#32
0
        public static void Register()
        {
            var options = new ConfigOptions();
            var configBuilder = new ConfigBuilder(options,
                (configuration, builder) =>
                {
                    // todo: initialize container here
                    builder.RegisterInstance(new AuthOwinAppBuilder(configuration)).As<IOwinAppBuilder>();
                    builder.RegisterType<ClientIdentityStore>().As<IClientIdentityStore>();
                    builder.RegisterType<ClientIdentityManager>();
                    builder.RegisterType<BankContext>().As<IContext>();
                    builder.RegisterType<EntityStubFactory>().As<IEntityStubFactory>();
                    builder.RegisterType<RepositoryFactory>().As<IRepositoryFactory>();
                    builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
                    builder.RegisterType<MobileServiceLogger>().As<ILogger>();
                    builder.RegisterType<Mapper>().As<IMapper>();
                    builder.RegisterType<ExpressionBuilder>().As<IExpressionBuilder>();
                    builder.RegisterType<TransactionService>().As<ITransactionService>();
                    builder.RegisterType<AccountService>().As<IAccountService>();
                    builder.RegisterType<CurrencyService>().As<ICurrencyService>();
                    builder.RegisterType<AccountTypeService>().As<IAccountTypeService>();
                    builder.RegisterType<ClientService>().As<IClientService>();
                    builder.RegisterType<CurrencyRateFactory>().As<ICurrencyRateFactory>();
                    builder.RegisterType<CurrencyRateService>().As<ICurrencyRateService>();
                    builder.RegisterType<ExchangeService>().As<IExchangeService>();
                    builder.RegisterType<ClientAuthorizationService>().As<IClientAuthorizationService>();
                    builder.RegisterType<AuthorizationAttemptService>().As<IAuthorizationAttemptService>();
                    builder.RegisterType<AuthorizationCardService>().As<IAuthorizationCardService>();
                    builder.RegisterType<ClientAuthenticationCodeValidator>().As<IClientAuthenticationCodeValidator>();
                    builder.RegisterType<ClientCreditCardService>().As<IClientCreditCardService>();
                });

            HttpConfiguration config = ServiceConfig.Initialize(configBuilder);
            config.EnableCors();
            AutoMapper.Mapper.Initialize(InitializeConfiguration);
        }