Beispiel #1
0
        public void Can_Map_Data()
        {
            // Arrange
            var data = new Dictionary<string, string>
            {
                {"Title", "Test Title"},
                {"Description", "Test Description"},
                {"Date", "2013-01-01"},
                {"Int", "21"},
                {"Bool", "True"},
                {"IntList", "1,2,3"},
                {"Misc", "Test Misc"}
            };
            var content = new TestContent();

            // Act
            content = new DataMapper().Map(content, data);

            // Assert
            Assert.AreEqual("Test Title", content.Title);
            Assert.AreEqual("Test Description", content.Description);
            Assert.AreEqual(new DateTime(2013, 1, 1), content.Date);
            Assert.AreEqual(21, content.Int);
            Assert.AreEqual(1, content.Data.Count);
            Assert.IsTrue(content.Bool);
            Assert.AreEqual(3, content.IntList.Count);
            Assert.IsTrue(content.Data.ContainsKey("Misc"));
            Assert.AreEqual("Test Misc", content.Data["Misc"]);
        }
Beispiel #2
0
        protected IDataMapper CreateSqliteDB()
        {
            var db = new DataMapper(System.Data.SQLite.SQLiteFactory.Instance, ConfigurationManager.ConnectionStrings["DB_Sqlite"].ConnectionString);
            db.SqlMode = SqlModes.Text;

            return db;
        }
Beispiel #3
0
        public void Map1()
        {
            mapper = new DataMapper(typeof(OrdersMap));

            mapper.AddMapping(1, "OrderId");
            mapper.AddMapping(2, "EmployeeId");
            mapper.AddMapping(0, "OrderDate");

            DataTable dt = new DataTable();
            dt.Columns.Add("Date", typeof(DateTime));
            dt.Columns.Add("Order", typeof(int));
            dt.Columns.Add("Employee", typeof(short));

            dt.Rows.Add(new object[] { new DateTime(2006,4,1), 3, (short)1 });
            dt.Rows.Add(new object[] { new DateTime(2006,6,1), 10, (short)11 });
            dt.Rows.Add(new object[] { new DateTime(2006,9,1), 20, (short)21 });

            OrdersMap[] res = (OrdersMap[]) mapper.MapDataTable2Records(dt);

            Assert.AreEqual(3, res[0].OrderID);
            Assert.AreEqual(1, res[0].EmployeeID);
            Assert.AreEqual(new DateTime(2006,4,1), res[0].OrderDate);

            Assert.AreEqual(10, res[1].OrderID);
            Assert.AreEqual(11, res[1].EmployeeID);
            Assert.AreEqual(new DateTime(2006,6,1), res[1].OrderDate);
        }
        public void RecurseGetFieldsNotFound()
        {
            DataMapper mapper = new DataMapper(typeof(FinalMapperClass));
            mapper.AddMapping(0, "InBaseClass");
            mapper.AddMapping(1, "InAdvancedClassNotFound");

            Assert.IsNotNull(mapper);
        }
        public void WhereIsNotNull()
        {
            var db = new DataMapper(System.Data.SqlClient.SqlClientFactory.Instance, @"Data Source=jordan-pc\sqlexpress;Initial Catalog=MyBigFishBowl;Persist Security Info=True;User ID=jmarr;Password=password");
            string sqlQuery = db.Query<Person>()
                .Where(p => p.Name != null)
                .BuildQuery();

            Assert.IsTrue(sqlQuery.Contains("WHERE ([t0].[Name] IS NOT NULL)"));
        }
Beispiel #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ContentStore"/> class.
        /// </summary>
        public ContentStore()
        {
            // Setup required components
            _fileStore = FileStoreManager.Default;
            _dataSerializer = DataSerializerManager.Default;
            _dataMapper = new DataMapper();

            // Setup file store event listener
            _fileStore.FileChanged += (sender, args) => _cacheDirty = true;
        }
        public void OrWhere_Lambda_Text()
        {
            var db = new DataMapper(System.Data.SqlClient.SqlClientFactory.Instance, @"Data Source=jordan-pc\sqlexpress;Initial Catalog=MyBigFishBowl;Persist Security Info=True;User ID=jmarr;Password=password");
            string sqlQuery = db.Query<Person>()
                .Where(p => p.Name == "Bob")
                .OrWhere("[Name] = 'Robert'")
                .OrderBy(p => p.Name).BuildQuery();

            Assert.IsTrue(sqlQuery.Contains("WHERE ([t0].[Name] = @P0) OR [Name] = 'Robert'"));
        }
        public void WhereIsNullWithOtherParameters()
        {
            var db = new DataMapper(System.Data.SqlClient.SqlClientFactory.Instance, @"Data Source=jordan-pc\sqlexpress;Initial Catalog=MyBigFishBowl;Persist Security Info=True;User ID=jmarr;Password=password");
            string sqlQuery = db.Query<Person>()
                .Where(p => p.ID == 1 || p.Name == null || p.ID == 2)
                .BuildQuery();

            Assert.IsTrue(sqlQuery.Contains("[t0].[ID] = @P0"));
            Assert.IsTrue(sqlQuery.Contains("[t0].[Name] IS NULL"));
            Assert.IsTrue(sqlQuery.Contains("[t0].[ID] = @P1"));
        }
 public void SetUp()
 {
     dataMapper = new DataMapper<TestPoco>();
     pocoInstance = new TestPoco
     {
         ComplexType = new PocoPoint { X = 1, Y = 2 },
         DifferentName = "Another",
         TestProperty = "Property",
         TestField = "Field"
     };
 }
            public void It_should_map_anything_using_our_conventions()
            {
                var dataMapper = new DataMapper();

                var dateTime = new DateTime(2016, 1, 2, 3, 4, 5);

                var result = dataMapper.CatchAll(new {FirstName = "Test1", LastName = "Test2", TheDate = dateTime});

                result["first_name"].ShouldEqual("Test1");
                result["last_name"].ShouldEqual("Test2");
                ((string)result["the_date"]).Substring(0, 16).ShouldEqual("2016-01-02T03:04");
            }
        public void Complex_Where_Query_No_Sort()
        {
            // Arrange
            var db = new DataMapper(System.Data.SqlClient.SqlClientFactory.Instance, "Data Source=a;Initial Catalog=a;User Id=a;Password=a;");
            QueryBuilder<Person> builder = new QueryBuilder<Person>(db, new SqlServerDialect());
            builder.Where(p => p.Age > 16 && p.Name.StartsWith("J"));

            // Act
            string generatedSql = builder.BuildQuery();

            // Assert
            Assert.IsTrue(generatedSql.Contains("SELECT [t0].[ID],[t0].[Name],[t0].[Age],[t0].[BirthDate],[t0].[IsHappy] "));
            Assert.IsTrue(generatedSql.Contains("FROM [PersonTable] [t0]"));
            Assert.IsTrue(generatedSql.Contains("WHERE (([t0].[Age] > @P0) AND ([t0].[Name] LIKE @P1 + '%'))"));
            Assert.IsFalse(generatedSql.Contains("ORDER BY"));
        }
        public void Sort_Only_Query_No_Where()
        {
            // Arrange
            var db = new DataMapper(System.Data.SqlClient.SqlClientFactory.Instance, "Data Source=a;Initial Catalog=a;User Id=a;Password=a;");
            QueryBuilder<Person> builder = new QueryBuilder<Person>(db, new SqlServerDialect());
            builder.OrderBy(p => p.ID).OrderBy(p => p.Name);

            // Act
            string generatedSql = builder.BuildQuery();

            // Assert
            Assert.IsTrue(generatedSql.Contains("SELECT [t0].[ID],[t0].[Name],[t0].[Age],[t0].[BirthDate],[t0].[IsHappy] "));
            Assert.IsTrue(generatedSql.Contains("FROM [PersonTable]"));
            Assert.IsFalse(generatedSql.Contains("WHERE"));
            Assert.IsTrue(generatedSql.Contains("ORDER BY [t0].[ID],[t0].[Name]"));
        }
        public void Complex_Where_Query_No_Sort()
        {
            // Arrange
            var db = new DataMapper(System.Data.SqlClient.SqlClientFactory.Instance, "Data Source=a;Initial Catalog=a;User Id=a;Password=a;");
            AutoQueryBuilder<Person> builder = new AutoQueryBuilder<Person>(db, false);

            // Act
            builder.Where(p => p.Age > 16 && p.Name.StartsWith("J"));
            
            // Assert
            builder.GenerateQueries();
            string generatedSql = builder.QueryQueue.First().QueryText;

            Assert.IsTrue(generatedSql.Contains("SELECT [ID],[Name],[Age],[BirthDate],[IsHappy] "));
            Assert.IsTrue(generatedSql.Contains("FROM PersonTable"));
            Assert.IsTrue(generatedSql.Contains("(([Age] > @P0 AND [Name] LIKE @P1 + '%'))"));
            Assert.IsFalse(generatedSql.Contains("ORDER BY"));
        }
        public void Sort_Only_Query_No_Where()
        {
            // Arrange
            var db = new DataMapper(System.Data.SqlClient.SqlClientFactory.Instance, "Data Source=a;Initial Catalog=a;User Id=a;Password=a;");
            AutoQueryBuilder<Person> builder = new AutoQueryBuilder<Person>(db, false);

            // Act
            builder.OrderBy(p => p.ID).OrderBy(p => p.Name);

            // Assert
            builder.GenerateQueries();
            string generatedSql = builder.QueryQueue.First().QueryText;

            Assert.IsTrue(generatedSql.Contains("SELECT [ID],[Name],[Age],[BirthDate],[IsHappy] "));
            Assert.IsTrue(generatedSql.Contains("FROM PersonTable"));
            Assert.IsFalse(generatedSql.Contains("WHERE"));
            Assert.IsTrue(generatedSql.Contains("ORDER BY [ID],[Name]"));
        }
        public void Where_Sort_Query_Should_Use_AltName()
        {
            // Arrange
            var db = new DataMapper(System.Data.SqlClient.SqlClientFactory.Instance, "Data Source=a;Initial Catalog=a;User Id=a;Password=a;");
            QueryBuilder<Order> builder = new QueryBuilder<Order>(db, new SqlServerDialect());
            builder
                .Join<Order, OrderItem>(JoinType.Left, o => o.OrderItems, (o, oi) => o.ID == oi.OrderID)
                .Where<OrderItem>(oi => oi.OrderID > 0)
                .OrderBy(o => o.OrderItems[0].ID);

            // Act
            string generatedSql = builder.BuildQuery();

            // Assert
            Assert.IsTrue(generatedSql.Contains("SELECT [t0].[ID],[t0].[OrderName],[t1].[ID] AS OrderItemID,[t1].[OrderID],[t1].[ItemDescription],[t1].[Price] "));
            Assert.IsTrue(generatedSql.Contains("FROM [Order] [t0] LEFT JOIN [OrderItem] [t1]"));
            Assert.IsTrue(generatedSql.Contains("WHERE ([t1].[OrderID] > @P0)"));
            Assert.IsTrue(generatedSql.Contains("ORDER BY [OrderItemID]"));
        }
        public void Where_Sort_Query_Should_Use_AltName()
        {
            // Arrange
            var db = new DataMapper(System.Data.SqlClient.SqlClientFactory.Instance, "Data Source=a;Initial Catalog=a;User Id=a;Password=a;");
            AutoQueryBuilder<Order> builder = new AutoQueryBuilder<Order>(db, true);
            
            // Act
            builder
                .Where(o => o.OrderItems[0].ID > 0)
                .OrderBy(o => o.OrderItems[0].ID);

            // Assert
            builder.GenerateQueries();
            string generatedSql = builder.QueryQueue.First().QueryText;

            Assert.IsTrue(generatedSql.Contains("SELECT [ID],[OrderName],[OrderItemID],[ItemDescription],[Price],[AmountPaid] "));
            Assert.IsTrue(generatedSql.Contains("FROM Order"));
            Assert.IsTrue(generatedSql.Contains("([OrderItemID] > @P0)"));
            Assert.IsTrue(generatedSql.Contains("ORDER BY [OrderItemID]"));
        }
Beispiel #17
0
        public void SingleRow()
        {
            var columns = DatabaseHelper.BuildColumnList<Customer>(_cache).ToList();

            const Int32 age = 35;
            var birthDate = new DateTime(1977, 10, 26);
            const Boolean enabled = true;
            const String lastName = "Baldi";
            var rows = new[]
                {
                    new Object[] { age, birthDate, enabled, lastName }
                };
            var reader = DatabaseHelper.CreateDataReader(columns, rows);
            var mapper = new DataMapper(_cache);
            var customer = mapper.MapRecord<Customer>(reader);

            Assert.Equal(age, customer.Age);
            Assert.Equal(birthDate, customer.BirthDate);
            Assert.Equal(enabled, customer.Enabled);
            Assert.Equal(lastName, customer.LastName);
        }
Beispiel #18
0
        public IDatabase Create(MigrationType migrationType = MigrationType.Main)
        {
            string connectionString;


            switch (migrationType)
            {
                case MigrationType.Main:
                    {
                        connectionString = _connectionStringFactory.MainDbConnectionString;
                        break;
                    }
                case MigrationType.Log:
                    {
                        connectionString = _connectionStringFactory.LogDbConnectionString;
                        break;
                    }
                default:
                    {
                        throw new ArgumentException("Invalid MigrationType");
                    }
            }

            _migrationController.MigrateToLatest(connectionString, migrationType);

            var db = new Database(() =>
                {
                    var dataMapper = new DataMapper(SQLiteFactory.Instance, connectionString)
                    {
                        SqlMode = SqlModes.Text,
                    };

                    return dataMapper;
                });

            db.Vacuum();


            return db;
        }
Beispiel #19
0
        public void SingleRowForTypeWithNonPublicStuff()
        {
            var columns = DatabaseHelper.BuildColumnList<CustomerWithPrivateStuff>(_cache).ToList();

            const Int32 age = 35;
            var birthDate = new DateTime(1977, 10, 26);
            const Boolean enabled = true;
            const String lastName = "Baldi";
            var rows = new[]
                {
                    new Object[] { enabled, age, birthDate, lastName }
                };
            var reader = DatabaseHelper.CreateDataReader(columns, rows);
            var mapper = new DataMapper(_cache);
            var customer = mapper.MapRecord<CustomerWithPrivateStuff>(reader);

            Assert.Equal(age, customer.Age);
            const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
            Assert.Equal(birthDate, customer.GetType().GetProperty("BirthDate", bindingFlags).GetValue(customer));
            Assert.Equal(enabled, customer.GetType().GetField("_enabled", bindingFlags).GetValue(customer));
            Assert.Equal(lastName, customer.LastName);
        }
Beispiel #20
0
        public void MultipleRows()
        {
            var columns = DatabaseHelper.BuildColumnList<Customer>(_cache).ToList();

            const Int32 firstAge = 35;
            var firstBirthDate = new DateTime(1977, 10, 26);
            const Boolean firstEnabled = true;
            const String firstLastName = "Baldi";

            const Int32 secondAge = 36;
            var secondBirthDate = new DateTime(1976, 2, 11);
            const Boolean secondEnabled = false;
            const String secondLastName = "Rossi";

            var rows = new[]
                {
                    new Object[] { firstAge, firstBirthDate, firstEnabled, firstLastName },
                    new Object[] { secondAge, secondBirthDate, secondEnabled, secondLastName }
                };
            var reader = DatabaseHelper.CreateDataReader(columns, rows);
            var mapper = new DataMapper(_cache);
            var customers = mapper.MapRecords<Customer>(reader);
            var result = customers.ToList();

            Assert.Equal(rows.Length, result.Count());
            
            Assert.Equal(firstAge, result[0].Age);
            Assert.Equal(firstBirthDate, result[0].BirthDate);
            Assert.Equal(firstEnabled, result[0].Enabled);
            Assert.Equal(firstLastName, result[0].LastName);

            Assert.Equal(secondAge, result[1].Age);
            Assert.Equal(secondBirthDate, result[1].BirthDate);
            Assert.Equal(secondEnabled, result[1].Enabled);
            Assert.Equal(secondLastName, result[1].LastName);
        }
Beispiel #21
0
        public IDatabase Create(MigrationContext migrationContext)
        {
            string connectionString;

            switch (migrationContext.MigrationType)
            {
                case MigrationType.Main:
                    {
                        connectionString = _connectionStringFactory.MainDbConnectionString;
                        break;
                    }
                case MigrationType.Log:
                    {
                        connectionString = _connectionStringFactory.LogDbConnectionString;
                        break;
                    }
                default:
                    {
                        throw new ArgumentException("Invalid MigrationType");
                    }
            }

            try
            {
                _migrationController.Migrate(connectionString, migrationContext);
            }
            catch (SQLiteException ex)
            {
                var fileName = _connectionStringFactory.GetDatabasePath(connectionString);

                if (migrationContext.MigrationType == MigrationType.Log)
                {
                    Logger.Error(ex, "Logging database is corrupt, attempting to recreate it automatically");

                    try
                    {
                        _diskProvider.DeleteFile(fileName + "-shm");
                        _diskProvider.DeleteFile(fileName + "-wal");
                        _diskProvider.DeleteFile(fileName + "-journal");
                        _diskProvider.DeleteFile(fileName);
                    }
                    catch (Exception)
                    {
                        Logger.Error("Unable to recreate logging database automatically. It will need to be removed manually.");
                    }

                    _migrationController.Migrate(connectionString, migrationContext);
                }

                else
                {
                    if (OsInfo.IsOsx)
                    {
                        throw new CorruptDatabaseException("Database file: {0} is corrupt, restore from backup if available. See: https://github.com/Sonarr/Sonarr/wiki/FAQ#i-use-sonarr-on-a-mac-and-it-suddenly-stopped-working-what-happened", ex, fileName);
                    }

                    throw new CorruptDatabaseException("Database file: {0} is corrupt, restore from backup if available. See: https://github.com/Sonarr/Sonarr/wiki/FAQ#i-am-getting-an-error-database-disk-image-is-malformed", ex, fileName);
                }
            }

            var db = new Database(migrationContext.MigrationType.ToString(), () =>
                {
                    var dataMapper = new DataMapper(SQLiteFactory.Instance, connectionString)
                    {
                        SqlMode = SqlModes.Text,
                    };

                    return dataMapper;
                });

            return db;
        }
        public void WhenQueryingAView_WhereClauseShouldUseAltNameForColumns()
        {
            // Arrange
            var db = new DataMapper(System.Data.SqlClient.SqlClientFactory.Instance, "Data Source=a;Initial Catalog=a;User Id=a;Password=a;");
            QueryBuilder<Person> builder = new QueryBuilder<Person>(db, new SqlServerDialect());
            builder
                .Graph()
                .Where<Pet>(p => p.Name == "Spot"); // Pet Name has an alt name of 'Pet_Name' specified

            // Act
            string generatedSql = builder.BuildQuery();

            // Assert
            Assert.IsTrue(generatedSql.Contains("SELECT [t0].[ID],[t0].[Name],[t0].[Age],[t0].[BirthDate],[t0].[IsHappy],[t0].[Pet_ID],[t0].[Pet_Name] "));
            Assert.IsTrue(generatedSql.Contains("FROM [PersonTable] [t0]"));
            Assert.IsTrue(generatedSql.Contains("WHERE ([t0].[Pet_Name] = @P0)"));
        }
        public void ManualWhereClause()
        {
            // Arrange
            var db = new DataMapper(System.Data.SqlClient.SqlClientFactory.Instance, "Data Source=a;Initial Catalog=a;User Id=a;Password=a;");
            QueryBuilder<Person> builder = new QueryBuilder<Person>(db, new SqlServerDialect());
            builder
                .Where("[t0].[ID] = 1");

            // Act
            string generatedSql = builder.BuildQuery();

            // Assert
            Assert.IsTrue(generatedSql.Contains("SELECT [t0].[ID],[t0].[Name],[t0].[Age],[t0].[BirthDate],[t0].[IsHappy] "));
            Assert.IsTrue(generatedSql.Contains("FROM [PersonTable] [t0]"));
            Assert.IsTrue(generatedSql.Contains("WHERE [t0].[ID] = 1"));
        }
Beispiel #24
0
 public static Models.CharacterState Map(DataModels.CharacterState data)
 {
     return(DataMapper.Map <Models.CharacterState, DataModels.CharacterState>(data));
 }
Beispiel #25
0
 public static Models.Skills Map(Skills data)
 {
     return(DataMapper.Map <Models.Skills, Skills>(data));
 }
 public void Setup()
 {
     address = new Address();
     mapper  = new DataMapper("v1");
 }
Beispiel #27
0
 protected IDataMapper CreateSqlServerDB()
 {
     var db = new DataMapper(System.Data.SqlClient.SqlClientFactory.Instance, ConfigurationManager.ConnectionStrings["DB_SqlServer"].ConnectionString);
     return db;
 }
Beispiel #28
0
        public virtual IList <TDto> FetchAll(TQuery query)
        {
            string fetchQuery = GetFetchQueryId();

            return(DataMapper.QueryForList <TDto>(fetchQuery, query));
        }
Beispiel #29
0
        public virtual TDto FetchOne(string id)
        {
            string fetchId = GetFetchId();

            return(DataMapper.QueryForObject <TDto>(fetchId, id));
        }
 public void Setup()
 {
     transmission = new Transmission();
     mapper       = new DataMapper("v1");
 }
 public void Setup()
 {
     options = new Options();
     mapper  = new DataMapper("v1");
 }
        public void should_use_sortDirection_supplied_in_overload()
        {
            // Arrange
            var db = new DataMapper(System.Data.SqlClient.SqlClientFactory.Instance, "Data Source=a;Initial Catalog=a;User Id=a;Password=a;");
            QueryBuilder<Person> builder = new QueryBuilder<Person>(db, new SqlServerDialect());
            builder.OrderBy(p => p.ID, SortDirection.Asc).OrderBy(p => p.Name, SortDirection.Desc);

            // Act
            string generatedSql = builder.BuildQuery();

            // Assert
            Assert.IsTrue(generatedSql.Contains("SELECT [t0].[ID],[t0].[Name],[t0].[Age],[t0].[BirthDate],[t0].[IsHappy] "));
            Assert.IsTrue(generatedSql.Contains("FROM [PersonTable]"));
            Assert.IsFalse(generatedSql.Contains("WHERE"));
            Assert.IsTrue(generatedSql.Contains("ORDER BY [t0].[ID],[t0].[Name] DESC"));
        }
        public void Where_And_Or_Mix()
        {
            var db = new DataMapper(System.Data.SqlClient.SqlClientFactory.Instance, @"Data Source=jordan-pc\sqlexpress;Initial Catalog=MyBigFishBowl;Persist Security Info=True;User ID=jmarr;Password=password");
            string sqlQuery = db.Query<Person>()
                .Where(p => p.Name == "Bob" || p.Name == "Robert")
                .AndWhere(p => p.Age > 30 && p.Age < 40).BuildQuery();

            Assert.IsTrue(sqlQuery.Contains("WHERE (([t0].[Name] = @P0) OR ([t0].[Name] = @P1)) AND (([t0].[Age] > @P2) AND ([t0].[Age] < @P3))"));
        }
Beispiel #34
0
        public void SpecialValues()
        {
            var columns = DatabaseHelper.BuildColumnList<CustomerWithUri>(_cache).ToList();

            const String lastName = "Baldi";
            var homePage = new Uri("http://naighes.com/");

            var rows = new[]
                {
                    new Object[] { homePage, lastName }
                };
            var reader = DatabaseHelper.CreateDataReader(columns, rows);
            var mapper = new DataMapper(_cache);
            var customer = mapper.MapRecord<CustomerWithUri>(reader);

            Assert.Equal(lastName, customer.LastName);
            Assert.Equal(homePage, customer.HomePage);
        }
Beispiel #35
0
 public void Setup()
 {
     _query  = new MetricsResourceQuery();
     _mapper = new DataMapper("v1");
 }
Beispiel #36
0
 public static Models.Resources Map(Resources data)
 {
     return(DataMapper.Map <Models.Resources, Resources>(data));
 }
Beispiel #37
0
 private void HandleSelected(ISelectableItem pItem)
 {
     DataMapper.renderTotalPopulation(DataMapper.loadPopulation());
 }
Beispiel #38
0
 public static Models.SyntyAppearance Map(DataModels.SyntyAppearance appearance)
 {
     return(DataMapper.Map <Models.SyntyAppearance, DataModels.SyntyAppearance>(appearance));
 }
 public void Setup()
 {
     recipient = new Recipient();
     mapper    = new DataMapper("v1");
 }
Beispiel #40
0
 protected IDataMapper CreateAccessDB()
 {
     var db = new DataMapper(System.Data.OleDb.OleDbFactory.Instance, ConfigurationManager.ConnectionStrings["DB_Access"].ConnectionString);
     return db;
 }
 public void Setup()
 {
     content = new Content();
     mapper  = new DataMapper("v1");
 }
        /// <summary>
        /// [Private]根据应付款单据类型和应付款单据编号加载应付款和付款单数据
        /// </summary>
        /// <param name="orderSysNo">应付款单据编号</param>
        /// <param name="orderType">应付款单据类型</param>
        /// <param name="companyCode">CompanyCode</param>
        /// <returns></returns>
        private PayDetailInfoResp LoadForEditByOrderSysNoAndOrderType(int orderSysNo, PayableOrderType orderType, string companyCode)
        {
            PayDetailInfoResp resp = new PayDetailInfoResp();

            int                totalCount;
            DataTable          st;
            PayableQueryFilter filter = new PayableQueryFilter();

            filter.OrderID     = orderSysNo.ToString();
            filter.OrderType   = orderType;
            filter.CompanyCode = companyCode;

            DataTable payDT = ObjectFactory <IPayableQueryDA> .Instance.QueryPayable(filter, out totalCount, out st);

            bool    isVendorHoldedControl = false;
            DataRow pay = null;

            if (payDT != null && payDT.Rows.Count > 0)
            {
                pay = payDT.Rows[0];
                if ((int)pay["OrderType"] == (int)PayableOrderType.PO || (int)pay["OrderType"] == (int)PayableOrderType.VendorSettleOrder ||
                    (int)pay["OrderType"] == (int)PayableOrderType.CollectionSettlement)
                {
                    isVendorHoldedControl = ObjectFactory <PayableAppService> .Instance.IsHolderVendorByVendorSysNo((int)pay["VendorSysNo"]);
                }

                int       paySysNo  = Convert.ToInt32(pay["PaySysNo"]);
                DataTable payItemDT = ObjectFactory <IPayItemQueryDA> .Instance.SimpleQuery(paySysNo);

                resp.PayItemList = DataMapper.GetEntityList <PayItemInfo, List <PayItemInfo> >(payItemDT.Rows);
            }

            CanBePayOrderQueryFilter queryFilter = new CanBePayOrderQueryFilter();

            queryFilter.OrderID     = orderSysNo.ToString();
            queryFilter.OrderType   = orderType;
            queryFilter.CompanyCode = companyCode;

            DataTable orderDT = ObjectFactory <ICanBePayOrderQueryDA> .Instance.Query(queryFilter, out totalCount);

            if (orderDT == null || orderDT.Rows.Count <= 0)
            {
                throw new ECCentral.BizEntity.BizException(string.Format(
                                                               ResouceManager.GetMessageString(InvoiceConst.ResourceTitle.Payable, "Payable_LoadForEditBySysNo_OrderNotExist"), orderSysNo));
            }

            var order    = orderDT.Rows[0];
            var payStyle = PayItemStyle.Normal;

            if (orderType == PayableOrderType.PO)
            {
                if ((int)order["OrderStatus"] == (int)PurchaseOrderStatus.WaitingInStock)
                {
                    payStyle = PayItemStyle.Advanced;
                }
            }

            resp.OrderInfo = new OrderInfo()
            {
                PayStyle              = payStyle,
                OrderAmt              = (decimal)order["OrderAmt"],
                OrderSysNo            = orderSysNo,
                OrderID               = (string)order["OrderID"],
                OrderType             = orderType,
                PaySysNo              = pay != null ? (int)pay["PaySysNo"] : 0,
                OrderStatus           = (int)order["OrderStatus"],
                BatchNumber           = (int)order["BatchNumber"],
                IsVendorHoldedControl = isVendorHoldedControl
            };

            var totalAmt = 0.00M;
            var paidAmt  = 0.00M;

            if (resp.PayItemList != null && resp.PayItemList.Count > 0)
            {
                resp.PayItemList.ForEach(p =>
                {
                    totalAmt += p.PayAmt.Value;
                    paidAmt  += p.Status == PayItemStatus.Paid ? p.PayAmt.Value : 0;
                });
            }
            resp.TotalInfo = new TotalInfo()
            {
                TotalAmt   = totalAmt,
                PaidAmt    = paidAmt,
                OrderAmt   = (decimal)order["OrderAmt"],
                OrderSysNo = (int)order["OrderSysNo"]
            };

            return(resp);
        }
 public void Setup()
 {
     file   = new Attachment();
     mapper = new DataMapper("v1");
 }
Beispiel #44
0
 public BaseManager()
 {
     DataMapper.Initialize();
 }
Beispiel #45
0
        public virtual void Delete(string id)
        {
            string deleteId = GetDeleteId();

            DataMapper.Delete(deleteId, id);
        }
Beispiel #46
0
        public IDatabase Create(MigrationContext migrationContext)
        {
            string connectionString;


            switch (migrationContext.MigrationType)
            {
            case MigrationType.Main:
            {
                connectionString = _connectionStringFactory.MainDbConnectionString;
                break;
            }

            case MigrationType.Log:
            {
                connectionString = _connectionStringFactory.LogDbConnectionString;
                break;
            }

            default:
            {
                throw new ArgumentException("Invalid MigrationType");
            }
            }

            try
            {
                _migrationController.Migrate(connectionString, migrationContext);
            }
            catch (SQLiteException ex)
            {
                var fileName = _connectionStringFactory.GetDatabasePath(connectionString);

                if (migrationContext.MigrationType == MigrationType.Log)
                {
                    Logger.Error(ex, "Logging database is corrupt, attempting to recreate it automatically");

                    try
                    {
                        _diskProvider.DeleteFile(fileName + "-shm");
                        _diskProvider.DeleteFile(fileName + "-wal");
                        _diskProvider.DeleteFile(fileName + "-journal");
                        _diskProvider.DeleteFile(fileName);
                    }
                    catch (Exception)
                    {
                        Logger.Error("Unable to recreate logging database automatically. It will need to be removed manually.");
                    }

                    _migrationController.Migrate(connectionString, migrationContext);
                }

                else
                {
                    if (OsInfo.IsOsx)
                    {
                        throw new CorruptDatabaseException("Database file: {0} is corrupt, restore from backup if available. See: https://github.com/Sonarr/Sonarr/wiki/FAQ#i-use-sonarr-on-a-mac-and-it-suddenly-stopped-working-what-happened", ex, fileName);
                    }

                    throw new CorruptDatabaseException("Database file: {0} is corrupt, restore from backup if available. See: https://github.com/Sonarr/Sonarr/wiki/FAQ#i-am-getting-an-error-database-disk-image-is-malformed", ex, fileName);
                }
            }

            var db = new Database(migrationContext.MigrationType.ToString(), () =>
            {
                var dataMapper = new DataMapper(SQLiteFactory.Instance, connectionString)
                {
                    SqlMode = SqlModes.Text,
                };

                return(dataMapper);
            });

            return(db);
        }
Beispiel #47
0
        public virtual IList <TDto> FetchMany(string ids)
        {
            string fetchIds = GetFetchIds();

            return(DataMapper.QueryForList <TDto>(fetchIds, ids));
        }
Beispiel #48
0
        private DataMapperViewModel GetEntityFields(DataMapperViewModel vm)
        {
            var entitySelected = dataFlowDbContext.Entities.FirstOrDefault(x => x.Id == vm.MapToEntity);

            if (!string.IsNullOrWhiteSpace(entitySelected?.Url))
            {
                string apiUrl = base.ConfigurationService.GetConfigurationByKey(Constants.API_SERVER_URL).Value;
                apiUrl = DataFlow.Common.Helpers.UrlUtility.GetUntilOrEmpty(apiUrl.Trim(), "/api/"); //get just the base URL

                var entityJson = edFiMetadataProcessor.GetJsonFromUrl(apiUrl, entitySelected.Url);
                var apiFields  = edFiMetadataProcessor.GetFieldListFromJson(entityJson, entitySelected.Name)
                                 .Where(x => x.Required || GetAdditionalFields(entitySelected.Name).Contains(x.Name))
                                 .ToList();

                apiFields.ForEach(x =>
                {
                    if (x.Name == "id")
                    {
                        return;
                    }

                    var dataMapperField = new DataMapper(
                        name: x.Name,
                        dataMapperProperty: new DataMapperProperty(
                            dataType: x.Type,
                            childType: !string.IsNullOrWhiteSpace(x.SubType) ? x.Name : string.Empty
                            ));
                    if (!string.IsNullOrWhiteSpace(x.SubType) && x.SubFields.Any())
                    {
                        x.SubFields.ForEach(subField =>
                        {
                            if (subField.Name == "id")
                            {
                                return;
                            }
                            ;
                            var subDataMapper = new DataMapper();

                            if (subField.Required || GetAdditionalFields(x.Name).Contains(subField.Name))
                            {
                                subDataMapper = new DataMapper(
                                    name: subField.Name,
                                    dataMapperProperty: new DataMapperProperty(
                                        dataType: subField.Type,
                                        childType: !string.IsNullOrWhiteSpace(subField.SubType) ? subField.Name : string.Empty
                                        ));
                                dataMapperField.SubDataMappers.Add(subDataMapper);
                            }

                            if (!string.IsNullOrWhiteSpace(subField.SubType) && subField.SubFields.Any())
                            {
                                subField.SubFields.ForEach(triField =>
                                {
                                    if (triField.Name == "id")
                                    {
                                        return;
                                    }

                                    if (triField.Required)
                                    {
                                        var triDataMapper = new DataMapper(
                                            name: triField.Name,
                                            dataMapperProperty: new DataMapperProperty(
                                                dataType: triField.Type,
                                                childType: !string.IsNullOrWhiteSpace(triField.SubType) ? triField.Name : string.Empty
                                                ));

                                        subDataMapper.SubDataMappers.Add(triDataMapper);
                                    }
                                });
                            }
                        });
                    }

                    var dataMappers = new List <DataMapper> {
                        dataMapperField
                    };
                    var builder = DataMapperBuilder.BuildPropertyUniqueKey(dataMappers);

                    vm.Fields.AddRange(builder);
                });
            }
            return(vm);
        }
Beispiel #49
0
 public static Item Map(Models.Item itemsItem)
 {
     return(DataMapper.Map <Item, Models.Item>(itemsItem));
 }
Beispiel #50
0
 private void HandleSelected(ISelectableItem pItem)
 {
     DataMapper.renderCrimesTotal(DataMapper.loadCrimes());
 }
Beispiel #51
0
 public static Models.Appearance Map(Appearance data)
 {
     return(DataMapper.Map <Models.Appearance, Appearance>(data));
 }
Beispiel #52
0
 private void FetchObject(SalesOrderTypeDto dto)
 {
     DataMapper.Map(dto, this);
 }
Beispiel #53
0
 public static Models.Statistics Map(DataModels.Statistics data)
 {
     return(DataMapper.Map <Models.Statistics, DataModels.Statistics>(data));
 }
Beispiel #54
0
 public void Setup()
 {
     dataMapper = new DataMapper();
 }
Beispiel #55
0
 public static SkillsExtended MapExtended(Skills data)
 {
     return(DataMapper.Map <SkillsExtended, Skills>(data));
 }
Beispiel #56
0
 public void Setup()
 {
     relayWebhook = new RelayWebhook();
     mapper       = new DataMapper("v1");
 }
Beispiel #57
0
        public void WhenSkipTakeIsCalledAfterOrderBy_ShouldTranslateToQuery()
        {
            var db = new DataMapper(System.Data.SqlClient.SqlClientFactory.Instance, @"Data Source=jordan-pc\sqlexpress;Initial Catalog=MyBigFishBowl;Persist Security Info=True;User ID=jmarr;Password=password");
            string sqlPage1 = db.Query<Person>()
                .OrderBy(p => p.Name)
                .Skip(0)
                .Take(20).BuildQuery();

            Assert.IsTrue(sqlPage1.Contains("WHERE RowNumber BETWEEN 1 AND 20"));

            string sqlPage2 = db.Query<Person>()
                .OrderBy(p => p.Name)
                .Skip(20)
                .Take(20)
                .BuildQuery();

            Assert.IsTrue(sqlPage2.Contains("WHERE RowNumber BETWEEN 21 AND 40"));
        }
Beispiel #58
0
 public void Setup()
 {
     sendingDomain = new SendingDomain();
     mapper        = new DataMapper("v1");
 }
Beispiel #59
0
        public JsonResult UpdateJsonMap(FormCollection formCollection, string triggeredBy)
        {
            var fields             = formCollection["FieldNames"].Split(';').ToList();
            var nonObjectsOrArrays = new[] { "string", "date-time", "boolean", "integer" };

            var dataMapperModels = new List <DataMapper>();

            fields.ForEach(f =>
            {
                var fieldCount = formCollection[$"hf{f}_ChildType"]?.Split(',').Length ?? 0;

                for (var i = 0; i < fieldCount; i++)
                {
                    var source       = formCollection[$"ddl{f}_SourceType"].SplitGetElementAt(',', i);
                    var sourceColumn = formCollection[$"ddl{f}_SourceColumn"].SplitGetElementAt(',', i);
                    var dataType     = formCollection[$"hf{f}_DataType"].SplitGetElementAt(',', i);
                    var defaultValue = formCollection[$"txt{f}_DefaultValue"].SplitGetElementAt(',', i);
                    var sourceTable  = formCollection[$"ddl{f}_SourceTable"].SplitGetElementAt(',', i);
                    var staticValue  = formCollection[$"txt{f}_StaticValue"].SplitGetElementAt(',', i);
                    var childType    = formCollection[$"hf{f}_ChildType"].SplitGetElementAt(',', i);
                    var parentType   = formCollection[$"hf{f}_ParentType"].SplitGetElementAt(',', i);
                    var parentTypes  = parentType?.Split(':').ToList() ?? new List <string>();
                    var firstParent  = parentTypes.ElementAtOrDefault(0).NullIfWhiteSpace();
                    var secondParent = parentTypes.ElementAtOrDefault(1).NullIfWhiteSpace();

                    if ((nonObjectsOrArrays.Contains(dataType) || dataType.EndsWith("Reference")) && firstParent == null)
                    {
                        var modelProperty = dataMapperModels.FirstOrDefault(x => x.Name == GetJsonFieldName(f));
                        if (modelProperty == null)
                        {
                            var model = new DataMapper
                            {
                                Name = GetJsonFieldName(f),
                                DataMapperProperty = new DataMapperProperty
                                {
                                    Source       = source,
                                    SourceColumn = sourceColumn,
                                    DataType     = dataType,
                                    Default      = defaultValue,
                                    SourceTable  = sourceTable,
                                    Value        = staticValue,
                                    ChildType    = childType,
                                    ParentType   = parentType
                                }
                            };
                            dataMapperModels.Add(model);
                        }
                    }
                    else if ((nonObjectsOrArrays.Contains(dataType) || dataType.EndsWith("Reference")) && secondParent != null)
                    {
                        var parentName = firstParent.EndsWith("Reference") ? firstParent : $"{firstParent}_Item{i}";

                        var parentModel = dataMapperModels
                                          .Where(x => x.Name == firstParent)
                                          .SelectMany(x => x.SubDataMappers)
                                          .Where(x => x.Name == parentName)
                                          .SelectMany(x => x.SubDataMappers)
                                          .FirstOrDefault(x => x.Name == secondParent);

                        /*
                         * some scenarios occur where the parent model wasn't created but should have been
                         * For example: studentAssessments > studentObjectiveAssessments:performanceLevels
                         */
                        if (parentModel == null)
                        {
                            var model = new DataMapper()
                            {
                                Name = secondParent
                            };
                            dataMapperModels
                            .Where(x => x.Name == firstParent)
                            .SelectMany(x => x.SubDataMappers)
                            .FirstOrDefault(x => x.Name == parentName)?.SubDataMappers.Add(model);

                            parentModel = dataMapperModels
                                          .Where(x => x.Name == firstParent)
                                          .SelectMany(x => x.SubDataMappers)
                                          .Where(x => x.Name == parentName)
                                          .SelectMany(x => x.SubDataMappers)
                                          .FirstOrDefault(x => x.Name == secondParent);
                        }

                        parentModel?.SubDataMappers.Add(
                            new DataMapper()
                        {
                            Name = $"{GetJsonFieldName(f)}",
                            DataMapperProperty = new DataMapperProperty()
                            {
                                Source       = source,
                                SourceColumn = sourceColumn,
                                DataType     = dataType,
                                Default      = defaultValue,
                                SourceTable  = sourceTable,
                                Value        = staticValue,
                                ChildType    = childType,
                                ParentType   = parentType
                            }
                        });
                    }
                    else
                    {
                        var addModel = false;

                        var model = dataMapperModels.FirstOrDefault(x => x.Name == GetJsonFieldName(f));

                        if (model == null)
                        {
                            addModel = true;
                            model    = new DataMapper
                            {
                                Name = GetJsonFieldName(f)
                            };
                        }
                        if (model.SubDataMappers.All(x => x.Name != $"{GetJsonFieldName(f)}_Item{i}"))
                        {
                            if (dataType == "array" && parentType == null)
                            {
                                model.SubDataMappers.Add(new DataMapper()
                                {
                                    Name = $"{GetJsonFieldName(f)}_Item{i}",
                                    DataMapperProperty = new DataMapperProperty()
                                    {
                                        Source       = source,
                                        SourceColumn = sourceColumn,
                                        DataType     = dataType,
                                        Default      = defaultValue,
                                        SourceTable  = sourceTable,
                                        Value        = staticValue,
                                        ChildType    = childType,
                                        ParentType   = parentType
                                    }
                                });
                            }
                        }

                        if (firstParent != null && secondParent == null)
                        {
                            var parentName  = firstParent.EndsWith("Reference") ? firstParent : $"{firstParent}_Item{i}";
                            var parentModel = dataMapperModels.SelectMany(x => x.SubDataMappers).FirstOrDefault(x => x.Name == parentName)
                                              ?? dataMapperModels.FirstOrDefault(x => x.Name == parentName);

                            parentModel?.SubDataMappers.Add(
                                new DataMapper()
                            {
                                Name = $"{GetJsonFieldName(f)}",
                                DataMapperProperty = new DataMapperProperty()
                                {
                                    Source       = source,
                                    SourceColumn = sourceColumn,
                                    DataType     = dataType,
                                    Default      = defaultValue,
                                    SourceTable  = sourceTable,
                                    Value        = staticValue,
                                    ChildType    = childType,
                                    ParentType   = parentType
                                }
                            });
                        }
                        else
                        {
                            if (addModel)
                            {
                                dataMapperModels.Add(model);
                            }
                        }
                    }
                }
            });

            dataMapperModels.ForEach(dm =>
            {
                if (dm.SubDataMappers.Any())
                {
                    //dm.Name = CleanJsonArrayObjectName(dm.Name);
                    dm.DataMapperProperty = null;
                }

                dm.SubDataMappers.ForEach(subdm =>
                {
                    if (subdm.SubDataMappers.Any())
                    {
                        //subdm.Name = CleanJsonArrayObjectName(subdm.Name);
                        subdm.DataMapperProperty = null;
                    }

                    subdm.SubDataMappers.ForEach(tridm =>
                    {
                        if (tridm.SubDataMappers.Any())
                        {
                            //tridm.Name = CleanJsonArrayObjectName(tridm.Name);
                            tridm.DataMapperProperty = null;
                        }
                    });
                });
            });

            var serializeOne = JsonConvert.SerializeObject(dataMapperModels, DataMapper.JsonSerializerSettings);
            var deserialize  = JsonConvert.DeserializeObject <List <DataMapper> >(serializeOne, DataMapper.JsonSerializerSettings);
            var serializeTwo = JsonConvert.SerializeObject(deserialize, DataMapper.JsonSerializerSettings);


            var jsonMap = serializeTwo;

            return(Json(jsonMap));
        }
        /// <summary>
        /// Builds the mapper factory.
        /// </summary>
        /// <returns>the mapper factory</returns>
        public IMapperFactory BuildMapperFactory()
        {
            // Registers file Xml, ... configuration element
            if (interpreter!=null)
            {
                interpreter.ProcessResource(configurationStore);

                // ensure that the default configuration settings get updated after the interpreter runs
                configurationSetting.PreserveWhitespace = TryGetSettingBoolean(ConfigConstants.ATTRIBUTE_PRESERVEWHITSPACE, configurationSetting.PreserveWhitespace);
                configurationSetting.UseReflectionOptimizer = TryGetSettingBoolean(ConfigConstants.ATTRIBUTE_USE_REFLECTION_OPTIMIZER, configurationSetting.UseReflectionOptimizer);
                configurationSetting.IsCacheModelsEnabled = TryGetSettingBoolean(ConfigConstants.ATTRIBUTE_CACHE_MODELS_ENABLED, configurationSetting.IsCacheModelsEnabled);
                configurationSetting.UseStatementNamespaces = TryGetSettingBoolean(ConfigConstants.ATTRIBUTE_USE_STATEMENT_NAMESPACES, configurationSetting.UseStatementNamespaces);
                configurationSetting.ValidateMapperConfigFile = TryGetSettingBoolean(ConfigConstants.ATTRIBUTE_VALIDATE_SQLMAP, configurationSetting.ValidateMapperConfigFile);
            }

            // Registers code configuration element
            //此处还未有案例分析????
            for(int i=0;i<modules.Count;i++)
            {
                modules[i].Configure(this);
            }

            // Process Extends ResultMap
            //将父节点的子节点信息添加到含有extends节点的下面
            List<IConfiguration> resolved = new List<IConfiguration>();
            for (int i = 0; i < configurationStore.ResultMaps.Length; i++)
            {
                ResolveExtendResultMap(resolved, configurationStore.ResultMaps[i]);
            }

            // Process Extends ParameterMap
            resolved = new List<IConfiguration>();
            for (int i = 0; i < configurationStore.ParameterMaps.Length; i++)
            {
                ResolveExtendParameterMap(resolved, configurationStore.ParameterMaps[i]);
            }

            // Process Include Sql statement
            //处理statements节点下的include属性
            for (int i = 0; i < configurationStore.Statements.Length; i++)
            {
                //获取节点statement update insert delete select节点的子节点include集合
                ConfigurationCollection includes = configurationStore.Statements[i].Children.RecursiveFind(ConfigConstants.ELEMENT_INCLUDE);

                if (includes.Count > 0)
                {
                    ResolveIncludeStatement(includes);
                }
            }

            // Process Extends statement
            resolved = new List<IConfiguration>();
            for (int i = 0; i < configurationStore.Statements.Length; i++)
            {
                ResolveExtendStatement(resolved, configurationStore.Statements[i]);
            }

            modelStore = new DefaultModelStore();

            IModelBuilder builder = new DefaultModelBuilder(modelStore);
            //核心处理结果都存储在了modelStore类中了
            builder.BuildModel(configurationSetting, configurationStore);
            //将核心处理结果对象存到DataMapper类中
            IDataMapper dataMapper = new DataMapper(modelStore);

            return new DefaultMapperFactory(dataMapper);
        }