private string GetColumnNameFromMember(MemberExpression node)
        {
            TableInfo  tableInfo  = DatabaseMapper.GetTableInfo(node.Member.DeclaringType);
            ColumnInfo columnInfo = tableInfo.GetColumnInfoByPropertyName(node.Member.Name);

            return(tableInfo.Delimiters.QuoteIdentifier(columnInfo.Name));
        }
Exemple #2
0
        public void MapTables_HasTables_ReturnsNonEmptyList()
        {
            // Arrange
            var table = new Table
            {
                TableId         = 1000,
                TableName       = "TableName",
                TableCreateDate = DateTime.Today - TimeSpan.FromDays(-30),
                TableModifyDate = DateTime.Today - TimeSpan.FromDays(-15),
                SchemaId        = 1
            };

            IDatabaseMappingDAO dbMappingDAOStub = Substitute.For <IDatabaseMappingDAO>();

            dbMappingDAOStub.GetDatabaseTables().Returns(new List <Table> {
                table
            });

            // Act
            IDatabaseMapper dbMapper = new DatabaseMapper(dbMappingDAOStub);

            dbMapper.MapTables();

            var dbMapping = dbMapper.DatabaseMapping;

            // Assert
            Assert.IsNotEmpty(dbMapping.Tables);
        }
Exemple #3
0
        private string GetColumnNameFromMember(MemberExpression node)
        {
            ColumnInfo columnInfo = DatabaseMapper.GetTableInfo(node.Member.DeclaringType)
                                    .GetColumnInfoByPropertyName(node.Member.Name);

            return(columnInfo.Name);
        }
Exemple #4
0
        public void GetTableExpressionIfWasNotSet()
        {
            var tableInfo        = new DatabaseMapper(new ConventionModelMapper()).GetTableInfo <Person>();
            var selectExpression = new SelectExpression(tableInfo);

            selectExpression.TableExpression.TablePart.Should().Be("TPerson");
        }
Exemple #5
0
        internal static async Task <SystemSettings> GetSystemSettings()
        {
            // TODO: Latest from DB not the cached in the server? If we are running on default, it will return null...
            var result = await Repository.GetLatestSystemSettingsAsync();

            return(DatabaseMapper.Map(result));
        }
Exemple #6
0
        public void GetColumnsExpressionIfWasNotSet()
        {
            var tableInfo        = new DatabaseMapper(new ConventionModelMapper()).GetTableInfo <Person>();
            var selectExpression = new SelectExpression(tableInfo);

            selectExpression.ColumnsExpression.ColumnsPart.Should().Be("Id, Name, LastName");
        }
Exemple #7
0
        public void MapSchemaTableRelationships_NoMappedTables_ThrowsInvalidOperationException()
        {
            // Arrange
            Schema[] schemas = new Schema[]
            {
                new Schema {
                    SchemaId = 1, SchemaName = "Schema 1"
                },
                new Schema {
                    SchemaId = 2, SchemaName = "Schema 2"
                },
                new Schema {
                    SchemaId = 3, SchemaName = "Schema 3"
                },
            };

            IDatabaseMappingDAO dbMappingDAO = Substitute.For <IDatabaseMappingDAO>();

            dbMappingDAO.GetDatabaseSchemas().Returns(schemas);
            dbMappingDAO.GetDatabaseTables().Returns(new List <Table>());

            // Act
            IDatabaseMapper dbMapper = new DatabaseMapper(dbMappingDAO);

            dbMapper.MapSchemas();
            dbMapper.MapTables();

            // Assert
            Assert.Throws <InvalidOperationException>(() => { dbMapper.MapSchemaTableRelationships(); });
        }
Exemple #8
0
        /// <summary>
        /// Static constructor for initializing default behaviours.
        /// </summary>
        static Database()
        {
            SqlServerQueryProviderFactory.Register();

            DefaultModelMapper  = new ConventionModelMapper();
            DatabaseMapper      = new DatabaseMapper(DefaultModelMapper);
            DefaultModelFactory = new DynamicMethodModelFactory(DatabaseMapper);
        }
        public void GetTableExpressionWithQuota()
        {
            TableInfo tableInfo = new DatabaseMapper(new ConventionModelMapper()).GetTableInfo <Person>();

            tableInfo.UseIdentifierDelimiters(Delimiters.SquareBrackets);
            var selectExpression = new SelectExpression(tableInfo);

            selectExpression.TableExpression.TablePart.Should().Be("[TPerson]");
        }
        public void GetColumnsExpressionWithQuotas()
        {
            TableInfo tableInfo = new DatabaseMapper(new ConventionModelMapper()).GetTableInfo <Person>();

            tableInfo.UseIdentifierDelimiters(Delimiters.SquareBrackets);
            var selectExpression = new SelectExpression(tableInfo);

            selectExpression.ColumnsExpression.ColumnsPart.Should().Be("[Id], [Name], [LastName]");
        }
        public void SetWhereConditionMoreTimes()
        {
            TableInfo tableInfo        = new DatabaseMapper(new ConventionModelMapper()).GetTableInfo <Person>();
            var       selectExpression = new SelectExpression(tableInfo);

            selectExpression.SetWhereExpression(new WhereExpression("PersonId > @1", 11));
            selectExpression.SetWhereExpression(new WhereExpression("IsDeleted = 0"));

            selectExpression.WhereExpression.Sql.Should().Be("(PersonId > @1) AND (IsDeleted = 0)");
        }
Exemple #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Database" /> class.
        /// </summary>
        /// <param name="activeConnection">The active connection.</param>
        /// <param name="modelMapper">Model mapper, which will be used for mapping Object to Relation database.</param>
        public Database(DbConnection activeConnection, IModelMapper modelMapper)
        {
            Check.NotNull(activeConnection, nameof(activeConnection));
            Check.NotNull(modelMapper, nameof(modelMapper));

            var databaseMapper      = new DatabaseMapper(modelMapper);
            var defaultModelFactory = new DynamicMethodModelFactory(databaseMapper);

            Init(activeConnection, QueryProviderFactories.GetFactory(activeConnection),
                 databaseMapper, defaultModelFactory);
        }
Exemple #13
0
        public void SetGroupByExpression()
        {
            var tableInfo        = new DatabaseMapper(new ConventionModelMapper()).GetTableInfo <Person>();
            var selectExpression = new SelectExpression(tableInfo);

            var expression = new GroupByExpression("FirstName");

            selectExpression.SetGroupByExpression(expression);

            selectExpression.GroupByExpression.Should().Be(expression);
        }
        private IQuery <Person> CreateQuery()
        {
            var            mapper = new DatabaseMapper(new ConventionModelMapper());
            Query <Person> query  = new Query <Person>(mapper,
                                                       new SqlServerQueryProvider(new SqlConnection(),
                                                                                  new SqlServerSqlExpressionVisitorFactory(mapper),
                                                                                  Substitute.For <IModelBuilder>(),
                                                                                  new Logger()));

            return(query);
        }
Exemple #15
0
        public void SetColumnsExpression()
        {
            var tableInfo        = new DatabaseMapper(new ConventionModelMapper()).GetTableInfo <Person>();
            var selectExpression = new SelectExpression(tableInfo);

            var expression = new ColumnsExpression("Id");

            selectExpression.SetColumnsExpression(expression);

            selectExpression.ColumnsExpression.Should().Be(expression);
        }
Exemple #16
0
        private IQuery <Person> CreateQuery()
        {
            var            mapper = new DatabaseMapper(new ConventionModelMapper());
            Query <Person> query  = new Query <Person>(mapper,
                                                       new SqlServerQueryProvider(new SqlConnection(),
                                                                                  new DefaultQuerySqlGenerator(mapper),
                                                                                  Substitute.For <IModelBuilder>(),
                                                                                  new Logger()));

            return(query);
        }
Exemple #17
0
        public void ReturnInjectorForTypeWhichWasConfigured()
        {
            var modelMapper = NSubstitute.Substitute.For <IModelMapper>();
            var injector    = new Injector();

            modelMapper.GetInjector <Foo>().Returns(injector);

            var databaseModelMapper = new DatabaseMapper(modelMapper);

            databaseModelMapper.GetInjector <Foo>().Should().Be(injector);
        }
Exemple #18
0
 /// <summary>
 /// Visits the member.
 /// </summary>
 /// <param name="expression">The expression.</param>
 /// <exception cref="System.NotSupportedException">If the member type is not supported.</exception>
 protected override Expression VisitMember(MemberExpression expression)
 {
     if (expression.Expression != null &&
         (expression.Expression.NodeType == ExpressionType.Parameter ||
          expression.Expression.NodeType == ExpressionType.Convert))
     {
         var columnInfo = DatabaseMapper.GetTableInfo(expression.Member.DeclaringType).GetColumnInfoByPropertyName(expression.Member.Name);
         LinqStringBuilder.Append(columnInfo.Name);
         return(expression);
     }
     throw new NotSupportedException(string.Format("The member '{0}' is not supported.", expression.Member.Name));
 }
        private static bool ReadDatabaseConfig()
        {
            var dbMapper = new DatabaseMapper();

            _databaseEntity = dbMapper.GetListFromFile(_commandParams.DbConfig);

            if (_databaseEntity == null)
            {
                Console.WriteLine($"Cant read db config from file {_commandParams.DbConfig}. {dbMapper.Error}");
                return(false);
            }

            return(true);
        }
        private IQuery <T> CreateQuery <T>(Delimiters quota)
        {
            var modelMapper = new ConventionModelMapper();

            (modelMapper as IModelMapperInternal).UseIdentifierDelimiters(quota);
            _databaseMapper = new DatabaseMapper(modelMapper);

            return(Database
                   .Builder
                   .UseConnection(new SqlConnection())
                   .UseQueryProviderFactory(new FakeQueryProviderFactory())
                   .UseDatabaseConfiguration(new DatabaseConfiguration(quota))
                   .Build().Query <T>());
        }
Exemple #21
0
        public async Task Complete_Errors()
        {
            await GenericTester
            .Test()
            .AddSingletonService(AgentTester.BuildConfiguration <Startup>("Beef"))
            .RunAsync(async() =>
            {
                var config = ExecutionContext.GetService <IConfiguration>();
                var db     = new CdcDb(config.GetConnectionString("BeefDemo"));

                var script =
                    "DELETE FROM [DemoCdc].[CdcIdentifierMapping]" + Environment.NewLine +
                    "DELETE FROM [DemoCdc].[ContactOutbox]" + Environment.NewLine +
                    "DECLARE @Lsn BINARY(10)" + Environment.NewLine +
                    "SET @Lsn = sys.fn_cdc_get_max_lsn()" + Environment.NewLine +
                    "INSERT INTO [DemoCdc].[ContactOutbox] ([CreatedDate], [ContactMinLsn], [ContactMaxLsn], [AddressMinLsn], [AddressMaxLsn], [IsComplete], [CompletedDate], [HasDataLoss]) VALUES('2021-01-01T00:00:00', @Lsn, @Lsn, @Lsn, @Lsn, 1, '2021-01-01T00:00:00', 0)" + Environment.NewLine +
                    "SELECT TOP 1 * FROM [DemoCdc].[ContactOutbox]";

                var outbox = await db.SqlStatement(script).SelectSingleAsync(DatabaseMapper.CreateAuto <CdcOutbox>()).ConfigureAwait(false);
                var cdc    = new ContactCdcData(db, new NullEventPublisher(), ExecutionContext.GetService <ILogger <ContactCdcData> >(), new StringIdentifierGenerator());

                // Attempt to execute where already complete.
                var cdor = await cdc.CompleteAsync(outbox.Id, new List <CdcTracker>()).ConfigureAwait(false);
                WriteResult(cdor);
                Assert.NotNull(cdor);
                Assert.IsFalse(cdor.IsSuccessful);
                Assert.NotNull(cdor.Exception);
                Assert.IsInstanceOf <BusinessException>(cdor.Exception);

                // Attempt to execute the CdcData with an invalid identifier.
                cdor = await cdc.CompleteAsync(outbox.Id + 1, new List <CdcTracker>()).ConfigureAwait(false);
                WriteResult(cdor);
                Assert.NotNull(cdor);
                Assert.IsFalse(cdor.IsSuccessful);
                Assert.NotNull(cdor.Exception);
                Assert.IsInstanceOf <NotFoundException>(cdor.Exception);

                // Make it incomplete and complete it.
                script = $"UPDATE [DemoCdc].[ContactOutbox] SET [IsComplete] = 0 WHERE [OutboxId] = {outbox.Id}";
                await db.SqlStatement(script).NonQueryAsync().ConfigureAwait(false);

                cdor = await cdc.CompleteAsync(outbox.Id, new List <CdcTracker>()).ConfigureAwait(false);
                WriteResult(cdor);
                Assert.NotNull(cdor);
                Assert.IsTrue(cdor.IsSuccessful);
                Assert.IsNotNull(cdor.Outbox);
                Assert.AreEqual(true, cdor.Outbox.IsComplete);
            });
        }
        private async Task PostGpsLocation(GpsMeasurement gpsMeasurement)
        {
            try
            {
                // Send to CiaBatac
                await ciaBataController.PostGpsLocation(CiaBataMapper.ToGpsLocation(gpsMeasurement));

                // Save to database
                await Repository.InsertOrUpdateAsync(DatabaseMapper.Map(gpsMeasurement));
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Error posting gps");
            }
        }
Exemple #23
0
        public void ReturnTableInfoForType()
        {
            var modelMapper = NSubstitute.Substitute.For <IModelMapper>();
            var tableInfo   = new TableInfo(new List <ColumnInfo>(), new List <PropertyInfo>(), null);

            modelMapper.GetTableInfo <Foo>().Returns(tableInfo);
            modelMapper.GetTableInfo(Arg.Any <Type>()).Returns(tableInfo);

            var databaseModelMapper = new DatabaseMapper(modelMapper);
            var expected            = tableInfo;

            var actual = databaseModelMapper.GetTableInfo <Foo>();

            actual.Should().Be(expected);
        }
Exemple #24
0
        public void MapTables_HasNoTables_ReturnsEmptyList()
        {
            // Arrange
            IDatabaseMappingDAO dbMappingDAOStub = Substitute.For <IDatabaseMappingDAO>();

            dbMappingDAOStub.GetDatabaseTables().Returns(new List <Table>());

            // Act
            IDatabaseMapper dbMapper = new DatabaseMapper(dbMappingDAOStub);

            dbMapper.MapTables();

            var dbMapping = dbMapper.DatabaseMapping;

            // Assert
            Assert.IsEmpty(dbMapping.Tables);
        }
Exemple #25
0
        public void MapSchemas_HasNoSchemas_ReturnEmptyList()
        {
            // Arrange
            IDatabaseMappingDAO dbMappingDAOStub = Substitute.For <IDatabaseMappingDAO>();

            dbMappingDAOStub.GetDatabaseSchemas().Returns(new List <Schema>());

            // Act
            IDatabaseMapper dbMapper = new DatabaseMapper(dbMappingDAOStub);

            dbMapper.MapSchemas();

            var dbMapping = dbMapper.DatabaseMapping;

            // Assert
            Assert.IsEmpty(dbMapping.Schemas);
        }
Exemple #26
0
        public async Task LoadRadioSettingsFromDatabaseAsync()
        {
            try
            {
                var dbSettings = await DbContext.RadioSettings.ToListAsync(); // Execute query

                var radiosFromSettings = dbSettings
                                         .Select(rs => DatabaseMapper.Map(rs))
                                         .ToDictionary(r => r.RadioId, r => r);

                foreach (var radio in radiosFromSettings)
                {
                    radios.AddOrUpdate(radio.Key, radio.Value, (rid, oldvalue) => { return(radio.Value); });
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Could not load the radio settings from the database");
            }
        }
Exemple #27
0
        public void MapSchemas_HasSchemas_ReturnsNonEmptyList()
        {
            // Arrange
            var schema = new Schema {
                SchemaId = 1, SchemaName = "dbo"
            };

            IDatabaseMappingDAO dbMappingDAOStub = Substitute.For <IDatabaseMappingDAO>();

            dbMappingDAOStub.GetDatabaseSchemas().Returns(new List <Schema> {
                schema
            });

            // Act
            IDatabaseMapper dbMapper = new DatabaseMapper(dbMappingDAOStub);

            dbMapper.MapSchemas();

            var dbMapping = dbMapper.DatabaseMapping;

            // Assert
            Assert.IsNotEmpty(dbMapping.Schemas);
        }
Exemple #28
0
        public void MapSchemaTableRelationships_NoMappedSchemas_ThrowsInvalidOperationException()
        {
            // Arrange
            Table[] tables = new Table[]
            {
                new Table {
                    TableId = 1, TableName = "Table 1", TableCreateDate = DateTime.Now, TableModifyDate = DateTime.Now, SchemaId = 1
                },
                new Table {
                    TableId = 2, TableName = "Table 2", TableCreateDate = DateTime.Now, TableModifyDate = DateTime.Now, SchemaId = 1
                },
                new Table {
                    TableId = 3, TableName = "Table 3", TableCreateDate = DateTime.Now, TableModifyDate = DateTime.Now, SchemaId = 1
                },
                new Table {
                    TableId = 4, TableName = "Table 4", TableCreateDate = DateTime.Now, TableModifyDate = DateTime.Now, SchemaId = 1
                },
                new Table {
                    TableId = 5, TableName = "Table 5", TableCreateDate = DateTime.Now, TableModifyDate = DateTime.Now, SchemaId = 1
                },
            };

            IDatabaseMappingDAO dbMappingDAO = Substitute.For <IDatabaseMappingDAO>();

            dbMappingDAO.GetDatabaseSchemas().Returns(new List <Schema>());
            dbMappingDAO.GetDatabaseTables().Returns(tables);

            // Act
            IDatabaseMapper dbMapper = new DatabaseMapper(dbMappingDAO);

            dbMapper.MapSchemas();
            dbMapper.MapTables();

            // Assert
            Assert.Throws <InvalidOperationException>(() => { dbMapper.MapSchemaTableRelationships(); });
        }
Exemple #29
0
        public void MapSchemaTableRelationships_HasMatchingRelationships_MapRelationshipsCorrecly()
        {
            // Arrange
            Schema[] schemas = new Schema[]
            {
                new Schema {
                    SchemaId = 1, SchemaName = "Schema 1"
                },
                new Schema {
                    SchemaId = 2, SchemaName = "Schema 2"
                },
                new Schema {
                    SchemaId = 3, SchemaName = "Schema 3"
                },
            };

            var tableCreateDate = DateTime.Now - TimeSpan.FromDays(-30);
            var tableModifyDate = DateTime.Now - TimeSpan.FromDays(-15);

            Table[] tables = new Table[]
            {
                new Table {
                    TableId = 1, TableName = "Table 1", TableCreateDate = tableCreateDate, TableModifyDate = tableModifyDate, SchemaId = 1
                },
                new Table {
                    TableId = 2, TableName = "Table 2", TableCreateDate = tableCreateDate, TableModifyDate = tableModifyDate, SchemaId = 1
                },
                new Table {
                    TableId = 3, TableName = "Table 3", TableCreateDate = tableCreateDate, TableModifyDate = tableModifyDate, SchemaId = 2
                },
                new Table {
                    TableId = 4, TableName = "Table 4", TableCreateDate = tableCreateDate, TableModifyDate = tableModifyDate, SchemaId = 2
                },
                new Table {
                    TableId = 5, TableName = "Table 5", TableCreateDate = tableCreateDate, TableModifyDate = tableModifyDate, SchemaId = 3
                },
                new Table {
                    TableId = 6, TableName = "Table 6", TableCreateDate = tableCreateDate, TableModifyDate = tableModifyDate, SchemaId = 3
                }
            };

            IDatabaseMappingDAO dbMappingDAO = Substitute.For <IDatabaseMappingDAO>();

            dbMappingDAO.GetDatabaseSchemas().Returns(schemas);
            dbMappingDAO.GetDatabaseTables().Returns(tables);

            // Act
            IDatabaseMapper dbMapper = new DatabaseMapper(dbMappingDAO);

            dbMapper.MapSchemas();
            dbMapper.MapTables();

            dbMapper.MapSchemaTableRelationships();

            // Asserts

            #region .: Asserts for schema 1 :.

            var schema1 = schemas.Single(s => s.SchemaId == 1);
            var table1  = tables.Single(t => t.TableId == 1);
            var table2  = tables.Single(t => t.TableId == 2);

            // Asserts that tables 1 and 2 points to schema1
            Assert.AreSame(schema1, table1.Schema);
            Assert.AreSame(schema1, table2.Schema);

            // Asserts that schema1 contains tables 1 and 2

            Assert.Contains(table1, schema1.Tables as ICollection);
            Assert.Contains(table2, schema1.Tables as ICollection);

            #endregion .: Asserts for schema 1 :.

            #region .: Asserts for schema 2 :.

            var schema2 = schemas.Single(s => s.SchemaId == 2);
            var table3  = tables.Single(t => t.TableId == 3);
            var table4  = tables.Single(t => t.TableId == 4);

            // Asserts that tables 3 and 4 points to schema2
            Assert.AreSame(schema2, table3.Schema);
            Assert.AreSame(schema2, table4.Schema);

            // Asserts that schema2 contains tables 3 and 4
            Assert.Contains(table3, schema2.Tables as ICollection);
            Assert.Contains(table4, schema2.Tables as ICollection);

            #endregion .: Asserts for schema 2 :.

            #region .: Asserts for schema 3 :.

            var schema3 = schemas.Single(s => s.SchemaId == 3);
            var table5  = tables.Single(t => t.TableId == 5);
            var table6  = tables.Single(t => t.TableId == 6);

            // Asserts that tables 5 and 6 points to schema3
            Assert.AreSame(schema3, table5.Schema);
            Assert.AreSame(schema3, table6.Schema);

            // Asserts that schema3 contains tables 5 and 6
            Assert.Contains(table5, schema3.Tables as ICollection);
            Assert.Contains(table6, schema3.Tables as ICollection);

            #endregion .: Asserts for schema 3 :.
        }
        private TableInfo GetTableInfo()
        {
            var tableInfo = new DatabaseMapper(new ConventionModelMapper()).GetTableInfo <Person>();

            return(tableInfo);
        }