public AgenciesServiceTests()
 {
     _mapperMock      = new Mock <IMapper>();
     _agenciesService = new AgenciesService(
         _mapperMock.Object,
         DbContextProvider.GetSqlServerDbContext());
 }
Esempio n. 2
0
        public async Task ShouldFindSingleRouteMatch()
        {
            const string routeTag = "20";

            var agency = new Agency {
                Tag = "TTC",
            };
            var route = new AgencyRoute
            {
                Agency = agency,
                Tag    = routeTag,
            };
            var route2 = new AgencyRoute
            {
                Agency = agency,
                Tag    = routeTag + "a",
            };

            string[] results;

            using (BusVbotDbContext dbContext = DbContextProvider.CreateInMemoryDbContext(nameof(ShouldFindSingleRouteMatch)))
            {
                dbContext.AddRange(route, route2);
                dbContext.SaveChanges();

                IAgencyDataParser sut = new TtcDataParser(dbContext);
                results = await sut.FindMatchingRoutesAsync(routeTag);
            }

            Assert.Single(results);
            Assert.Equal(routeTag, results[0]);
        }
        public async Task AddAsync_Returns_None_If_Connection_To_Database_Is_Lost(Agency agency)
        {
            // Arrange
            var wrongConnectionString =
                "Server=x;Database=y;" +
                "Integrated Security=True;" +
                "Trusted_Connection=True;" +
                "MultipleActiveResultSets=true;";

            _agenciesService = new AgenciesService(
                _mapperMock.Object,
                DbContextProvider.GetSqlServerDbContext(wrongConnectionString));

            // Act
            var result = await _agenciesService.AddAsync(agency);

            // Assert
            result.HasValue.ShouldBe(false);
            result.MatchNone(error => error
                             .Messages
                             .ShouldAllBe(msg => msg == "An unhandled exception has occurred while creating the agency : " +
                                          "A network-related or instance-specific error occurred while " +
                                          "establishing a connection to SQL Server. " +
                                          "The server was not found or was not accessible. " +
                                          "Verify that the instance name is correct and that SQL Server " +
                                          "is configured to allow remote connections. " +
                                          "(provider: Named Pipes Provider, error: 40 - " +
                                          "Could not open a connection to SQL Server)!"));
        }
        private NewsService GetNewsServiceWithTestData()
        {
            var context = DbContextProvider.GetInMemoryDbContext();

            PopulateData(context);
            return(new NewsService(context));
        }
Esempio n. 5
0
        public void Send_Taking_Several_Logs_Saves_Log_In_Db_Context()
        {
            var options = new DbContextOptionsBuilder <LogModelContext>()
                          .UseInMemoryDatabase(databaseName: "Test2")
                          .Options;
            var logDataContext = new LogModelContext(options);
            IDbContextProvider         dbContextProvider          = new DbContextProvider(logDataContext);
            IDbEntityBuilder           dbEntityBuilder            = new LogDbModelEntityBuilder();
            EntityFrameworkDestination entityFrameworkDestination = new EntityFrameworkDestination(dbContextProvider, dbEntityBuilder);
            LogModel logData1 = Samples.LogModels.WithTagsAndItems(LogType.Warning);

            logData1.LogId = "LogId1";
            LogModel logData2 = Samples.LogModels.WithTagsAndItems(LogType.Error);

            logData2.LogId = "LogId2";
            LogModel logData3 = Samples.LogModels.WithTagsAndItems(LogType.Info);

            logData3.LogId = "LogId3";

            // Act
            entityFrameworkDestination.Send(new LogModel[] { logData1, logData2, logData3 });

            // Assert
            List <LogDbModel> logs = logDataContext.Logs.ToList();

            Assert.AreEqual(3, logs.Count);
            LogDbModelAsserts.AssertLogModelModelIsEqualToLogModel(logs[0], logData1);
            LogDbModelAsserts.AssertLogModelModelIsEqualToLogModel(logs[1], logData2);
            LogDbModelAsserts.AssertLogModelModelIsEqualToLogModel(logs[2], logData3);
        }
        static void Main(string[] args)
        {
            try
            {
                var pAuthorise = Convert.ToInt32(args[0]);

                if (0 >= pAuthorise || pAuthorise > 100)
                {
                    throw new ArgumentException(nameof(pAuthorise));
                }

                var seed = Convert.ToInt32(args[1]);

                var config = AppSettingsFromJsonFiles.GetConfigurationRoot();
                using var dbContextProvider = new DbContextProvider <ExposureContentDbContext>(
                          () => new ExposureContentDbContext(new PostGresDbContextOptionsBuilder(new StandardEfDbConfig(config, "MSS")).Build())
                          );

                var authorise = new GenerateAuthorisations(dbContextProvider, new WorkflowDbAuthoriseCommand(dbContextProvider));
                authorise.Execute(pAuthorise, new Random(seed));
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            try
            {
                var config = AppSettingsFromJsonFiles.GetConfigurationRoot();
                using var dbContextProvider = new DbContextProvider <ExposureContentDbContext>(
                          () => new ExposureContentDbContext(new PostGresDbContextOptionsBuilder(new StandardEfDbConfig(config, "Content")).Build())
                          );


                var WorkflowCount = Convert.ToInt32(args[0]);
                if (WorkflowCount < 1)
                {
                    throw new ArgumentOutOfRangeException(nameof(WorkflowCount));
                }

                var randomSeed = Convert.ToInt32(args[1]);

                var r  = new Random(randomSeed); //Don't need the crypto version.
                var c1 = new GenerateAgWorkflows(dbContextProvider);
                c1.Execute(WorkflowCount, x => r.Next(x), x => r.NextBytes(x));
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
        }
Esempio n. 8
0
    public virtual async Task EnqueueAsync(IncomingEventInfo incomingEvent)
    {
        var dbContext = await DbContextProvider.GetDbContextAsync();

        dbContext.IncomingEvents.Add(
            new IncomingEventRecord(incomingEvent)
            );
    }
 public DatabaseAuditProvider(IServiceProvider serviceProvider, DbContextProvider dbContext, IHistoricalRepository historicalRepository, IDatabaseCommandGenerator databaseCommandGenerator, SchemmaNameProvider schemmaNameProvider, AuditTableNameProvider auditTableName)
 {
     this.dbContext                = dbContext(serviceProvider);
     this.historicalRepository     = historicalRepository;
     this.databaseCommandGenerator = databaseCommandGenerator;
     this.schemmaNameProvider      = schemmaNameProvider;
     this.auditTableName           = auditTableName;
 }
 public PreparationStepsService(
     DbContextProvider dbContextProvider,
     PreparationStepsDtoMapper preparationStepDtoMapper,
     PreparationStepsRepository preparationStepsRepository)
     : base(dbContextProvider, preparationStepsRepository)
 {
     _preparationStepsDtoMapper = preparationStepDtoMapper;
 }
Esempio n. 11
0
 public FileServiceTests()
 {
     _dbContext = DbContextProvider.GetInMemoryDbContext();
     _imageStorageServiceMock = new Mock <IImageStorageService>();
     _fileService             = new FileService(
         _dbContext,
         _imageStorageServiceMock.Object);
 }
Esempio n. 12
0
 public IngredientsService(
     DbContextProvider dbContextProvider,
     IngredientsDtoMapper ingredientsDtoMapper,
     IngredientsRepository ingredientsRepository)
     : base(dbContextProvider, ingredientsRepository)
 {
     _ingredientsDtoMapper = ingredientsDtoMapper;
 }
Esempio n. 13
0
 public TagsService(
     DbContextProvider dbContextProvider,
     TagsDtoMapper tagsDtoMapper,
     TagsRepository tagsRepository)
     : base(dbContextProvider, tagsRepository)
 {
     _tagsDtoMapper = tagsDtoMapper;
 }
    public override async Task MarkAsProcessedAsync(Guid id)
    {
        var dbContext = await DbContextProvider.GetDbContextAsync();

        var tableName = dbContext.IncomingEvents.EntityType.GetSchemaQualifiedTableName();

        var sql = $"UPDATE \"{tableName}\" SET \"Processed\" = '1', \"ProcessedTime\" = '{Clock.Now}' WHERE \"Id\" = '{id}'";
        await dbContext.Database.ExecuteSqlRawAsync(sql);
    }
Esempio n. 15
0
        /// <summary>
        /// 在数据库中检查指定的接口类型映射的数据表是否存在,如果不存在,将创建表
        /// </summary>
        /// <typeparam name="T">实体类接口类型</typeparam>
        public void CheckTableExistsOf <T>() where T : class
        {
            //DbContextProvider.CheckTableExists<T>();
            T   obj  = EntityBuilder.CreateEntity <T>();
            var mi   = DbContextProvider.GetType().GetMethod("CheckTableExists");
            var g_mi = mi.MakeGenericMethod(obj.GetType());

            g_mi.Invoke(DbContextProvider, null);
        }
Esempio n. 16
0
    public override async Task MarkAsProcessedAsync(Guid id)
    {
        var dbContext = await DbContextProvider.GetDbContextAsync();

        var tableName = dbContext.IncomingEvents.EntityType.GetSchemaQualifiedTableName();

        var sql = $"UPDATE {tableName} SET Processed = '1', ProcessedTime = '{Clock.Now}' WHERE Id = '{id.ToString().ToUpper()}'";
        await dbContext.Database.ExecuteSqlRawAsync(sql);
    }
Esempio n. 17
0
        private void WireDbContext <TDbContext>(IServiceCollection services) where TDbContext : DbContext
        {
            string connectionString = Configuration[AppSettingsKeys.ConnectionStringKey];

            // Some other providers could be chosen, according to Configuration[AppSettingsKeys.DbProviderKey]
            var provider = new DbContextProvider();

            provider.WireDbContext(services, Configuration, connectionString);
        }
    public override async Task DeleteAsync(Guid id)
    {
        var dbContext = (IHasEventOutbox)await DbContextProvider.GetDbContextAsync();

        var tableName = dbContext.OutgoingEvents.EntityType.GetSchemaQualifiedTableName();

        var sql = $"DELETE FROM \"{tableName}\" WHERE \"Id\" = '{id}'";
        await dbContext.Database.ExecuteSqlRawAsync(sql);
    }
Esempio n. 19
0
    public override async Task MarkAsProcessedAsync(Guid id)
    {
        var dbContext = await DbContextProvider.GetDbContextAsync();

        var tableName = dbContext.IncomingEvents.EntityType.GetSchemaQualifiedTableName();

        var sql = $"UPDATE \"{tableName}\" SET \"Processed\" = '1', \"ProcessedTime\" = TO_DATE('{Clock.Now}', 'yyyy-mm-dd hh24:mi:ss') WHERE \"Id\" = HEXTORAW('{GuidToOracleType(id)}')";
        await dbContext.Database.ExecuteSqlRawAsync(sql);
    }
        public void Adding_Entity_Framework_Destination_With_Minimal_Configuration()
        {
            IDbContextProvider         dbContextProvider          = new DbContextProvider(dbContext);
            IDbEntityBuilder           dbEntityBuilder            = new LogDbModelEntityBuilder();
            EntityFrameworkDestination entityFrameworkDestination = new EntityFrameworkDestination(dbContextProvider, dbEntityBuilder);

            Logger logger = new Logger();

            logger.AddLogDestinations(entityFrameworkDestination);
        }
Esempio n. 21
0
 public RecipesService(
     DbContextProvider dbContextProvider,
     RecipesDtoMapper recipesDtoMapper,
     RecipesRepository recipesRepository,
     IngredientsService ingredientsService)
     : base(dbContextProvider, recipesRepository)
 {
     _recipesDtoMapper   = recipesDtoMapper;
     _ingredientsService = ingredientsService;
 }
        public override async Task <int> Add(CreatePreparationStepDto createDto)
        {
            var preparationStep = DtoMapper.CreateEntity(createDto);
            var maxOder         = await Repository.GetMaxOrder(createDto.RecipeId);

            preparationStep.Order = (byte)(maxOder + 1);

            Repository.Add(preparationStep);
            return(await DbContextProvider.SaveChangesAsync());
        }
Esempio n. 23
0
        public void Ctor_Taking_DbContext_When_Called_With_Null_DbContext_Throws_ArgumentNullException()
        {
            var ex = Assert.Catch <ArgumentNullException>(() =>
            {
                // Act
                DbContextProvider dbContextProvider = new DbContextProvider(null as DbContext);
            });

            Assert.AreEqual("dbContext", ex.ParamName);
        }
 public static IEnumerable <DiscountCriteriaInfo> FetchByDiscountId(int discountId)
 {
     using (var db = DbContextProvider.GetDbContext())
     {
         foreach (var entity in db.DiscountCriteria.Where(x => x.DiscountId == discountId))
         {
             yield return(CreateInternal(entity));
         }
     }
 }
Esempio n. 25
0
    public override async Task DeleteOldEventsAsync()
    {
        var dbContext = await DbContextProvider.GetDbContextAsync();

        var tableName        = dbContext.IncomingEvents.EntityType.GetSchemaQualifiedTableName();
        var timeToKeepEvents = Clock.Now - EventBusBoxesOptions.WaitTimeToDeleteProcessedInboxEvents;

        var sql = $"DELETE FROM {tableName} WHERE Processed = '1' AND CreationTime < '{timeToKeepEvents}'";
        await dbContext.Database.ExecuteSqlRawAsync(sql);
    }
Esempio n. 26
0
    public override async Task DeleteOldEventsAsync()
    {
        var dbContext = await DbContextProvider.GetDbContextAsync();

        var tableName        = dbContext.IncomingEvents.EntityType.GetSchemaQualifiedTableName();
        var timeToKeepEvents = Clock.Now - EventBusBoxesOptions.WaitTimeToDeleteProcessedInboxEvents;

        var sql = $"DELETE FROM \"{tableName}\" WHERE \"Processed\" = '1' AND \"CreationTime\" < TO_DATE('{timeToKeepEvents}', 'yyyy-mm-dd hh24:mi:ss')";
        await dbContext.Database.ExecuteSqlRawAsync(sql);
    }
        public void Adding_Entity_Framework_Destination_With_Custom_DbEntity_Builder()
        {
            IDbContextProvider         dbContextProvider          = new DbContextProvider(dbContext);
            IDbEntityBuilder           customDbEntityBuilder      = new Mock <IDbEntityBuilder>().Object;
            EntityFrameworkDestination entityFrameworkDestination = new EntityFrameworkDestination(dbContextProvider, customDbEntityBuilder);

            Logger logger = new Logger();

            logger.AddLogDestinations(entityFrameworkDestination);
        }
Esempio n. 28
0
        public ArticlesServiceTests()
        {
            var profile             = new MappingProfile();
            var mapperConfiguration = new MapperConfiguration(expression => expression.AddProfile(profile));

            _mapper = new Mapper(mapperConfiguration);

            _repository = new ArticlesRepository(DbContextProvider.GetInMemory());

            _service = new ArticlesService.Services.ArticlesService(_mapper, _repository);
        }
Esempio n. 29
0
        public void Ctor_Taking_DbContext_When_Called_Sets_DbContext()
        {
            // Arrange
            DbContext dbContext = new Mock <DbContext>().Object;

            // Act
            DbContextProvider dbContextProvider = new DbContextProvider(dbContext);

            // Arrange
            Assert.AreEqual(dbContext, dbContextProvider.DbContext);
        }
Esempio n. 30
0
 public LogEventHandler(
     UserProvider userAcessor,
     IServiceProvider serviceProvider,
     DbContextProvider dbContext,
     IEnumerable <IgnoredEntity> listaNegras)
 {
     this.userAcessor = userAcessor(serviceProvider);
     this.dbContext   = dbContext(serviceProvider);
     this.listaNegras = listaNegras;
     this.LogType     = typeof(EventLog).Name;
 }