public void ToOrderedChangeEvent_Should_ReturnChangeForEachItem()
        {
            var product = ProductFactory.GetProduct("0");

            product.Price.Should().BeApproximately(1.0, 0.000001);

            var changes = ProductFactory.GetProductPriceChanges(product.Id);

            var actual = ChangeFactory.ToOrderedChangeEvent <Product, ProductPriceChange, string, double, DateTime>(
                x => x.Price,
                0.8,
                changes,
                x => x.Id,
                x => x.Price,
                x => x.ChangeDate).ToList();

            Assert.Equal(changes.Count, actual.Count);
            var change1 = actual[0];
            var change2 = actual.Last();

            change1.Revert(product);
            product.Price.Should().BeApproximately(0.8, 0.000001);

            change2.Apply(product);
            product.Price.Should().BeApproximately(changes.Last().Price, 0.000001);
        }
Beispiel #2
0
        public void Run(string source,
                        string tableName,
                        string primaryKeyField)
        {
            var determine        = new char[] { ',' };
            var primaryKeyValues = source.Split(determine, StringSplitOptions.RemoveEmptyEntries);
            var dict             = new Dictionary <String, List <String> >();

            for (int index = 0; index < primaryKeyValues.Length; index++)
            {
                var selectQuery   = String.Format(@"SElECT * FROM {0} WHERE {1} = {2}", tableName, primaryKeyField, primaryKeyValues[index]);
                var dt            = _sourceAccess.ExcuteRawQuery(selectQuery) as DataTable;
                var changeCommand = ChangeFactory.CreateCommand(ChangeType.INSERTED, dt, tableName, primaryKeyField, string.Empty);
                var sqlList       = changeCommand.Excute();
                dict.Add(index.ToString(), sqlList);
            }
            foreach (var item in dict)
            {
                try
                {
                    foreach (var tmp in item.Value)
                    {
                        _destinationAccess.ExcuteRawNonQuery(tmp);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(String.Format("Error sync with logId {0}: {1}", item.Key, ex));
                }
            }
        }
        public void ToChangeEvent_Should_ReturnChangeForEachItem()
        {
            var product = ProductFactory.GetProduct("0");

            product.Available.Should().Be(10);

            var product1 = ProductFactory.GetProduct("1");
            var product2 = ProductFactory.GetProduct("2");

            var changes = new List <Product>
            {
                product1,
                product2
            };

            var actual = ChangeFactory.ToChangeEvent <Product, Product, Guid, int>(
                x => x.Available,
                15, changes,
                x => x.Id,
                x => x.InStock)
                         .ToList();

            Assert.Equal(changes.Count, actual.Count);
            var change1 = actual[0];
            var change2 = actual.Last();

            change1.Revert(product);
            product.Available.Should().Be(15);

            change2.Apply(product);
            product.Available.Should().Be(10);
        }
Beispiel #4
0
        internal static List <IEvent <Product, string> > GetChanges(Guid itemId)
        {
            var priceChanges         = ProductFactory.GetProductPriceChanges(itemId).ToList();
            var stockMutationChanges = ProductFactory.GetProductStockMutations(itemId).ToList();

            var changes = ChangeFactory.ToOrderedChangeEvent <Product, ProductPriceChange, string, double, DateTime>(
                x => x.Price,
                0,
                priceChanges,
                x => x.Id,
                x => x.Price,
                x => x.ChangeDate).Cast <IEvent <Product, string> >().ToList();

            changes.AddRange(MutationFactory.ToMutationEvent <Product, ProductStockMutation, string, int>(
                                 x => x.Available,
                                 stockMutationChanges,
                                 x => x.Id,
                                 x => x.ApplyableAmount).Cast <IEvent <Product, string> >());

            changes.AddRange(MutationFactory.ToOrderedMutationEvent <Product, ProductStockMutation, string, int, DateTime>(
                                 x => x.InStock,
                                 stockMutationChanges,
                                 x => x.Id,
                                 x => x.ApplyableAmount,
                                 x => x.DeliveryDate.Date).Cast <IEvent <Product, string> >());

            return(changes);
        }
Beispiel #5
0
        internal static DL.Models.Product SetProduct(ProductStock.DL.Models.Product product)
        {
            if (!ProductStocks.ContainsKey(product.Id))
            {
                ProductStocks.Add(product.Id, product);

                var result = new DL.Models.Product(product.Id, product.Number, product.Description);
                Products.Add(product.Id, result);

                var priceChanges = ChangeFactory.ToOrderedChangeEvent <
                    DL.Models.Product,
                    ProductStock.DL.Models.ProductPrice,
                    Guid,
                    double,
                    DateTimeOffset>(
                    x => x.Price,
                    0,
                    product.Prices,
                    x => x.Id,
                    x => x.Price,
                    x => x.RegisterDate).
                                   Cast <IEvent <DL.Models.Product, Guid> >().ToList();

                var stockAvailableMutations = MutationFactory.ToOrderedMutationEvent <
                    DL.Models.Product,
                    ProductStock.DL.Models.ProductStockMutation,
                    Guid,
                    int,
                    DateTimeOffset>(
                    x => x.Available,
                    product.StockMutations,
                    x => x.Id,
                    x => x.Amount * (x.Type == ProductStock.DL.Enums.MutationType.Purchase ? -1 : 1),
                    x => x.OrderDate).Cast <IEvent <DL.Models.Product, Guid> >().ToList();

                var stockInStockMutations = MutationFactory.ToOrderedMutationEvent <
                    DL.Models.Product,
                    ProductStock.DL.Models.ProductStockMutation,
                    Guid,
                    int,
                    DateTimeOffset>(
                    x => x.InStock,
                    product.StockMutations,
                    x => x.Id,
                    x => x.Amount * (x.Type == ProductStock.DL.Enums.MutationType.Purchase ? -1 : 1),
                    x => x.ShipmentDate).Cast <IEvent <DL.Models.Product, Guid> >().ToList();

                AddEvents(product.Id, new OrderedEventCollection <DL.Models.Product, Guid, DateTimeOffset>(priceChanges.ToList()));
                AddEvents(product.Id, new OrderedEventCollection <DL.Models.Product, Guid, DateTimeOffset>(stockAvailableMutations.ToList()));
                AddEvents(product.Id, new OrderedEventCollection <DL.Models.Product, Guid, DateTimeOffset>(stockInStockMutations.ToList()));

                return(result);
            }

            return(Products[product.Id]);
        }
Beispiel #6
0
        public void Run()
        {
            // Lấy thông tin cập nhật thay đổi trong DB Sql dựa theo trigger
            var selectCommand = String.Format("SELECT TOP ({0}) * FROM [LogTable] WHERE Status = {1} ORDER BY LogId", Utility.GetTopQuantity(), (int)Status.NEW);
            var logs          = _sourceAccess.ExcuteRawQuery(selectCommand) as DataTable;

            var dict             = new Dictionary <String, List <String> >();
            var updateLogCommand = "UPDATE [LogTable] SET Status = {0} WHERE LogId = {1}";
            var deleteLogCommand = "DELETE FROM [LogTable] WHERE LogId = {0}";

            foreach (DataRow item in logs.Rows)
            {
                //Đánh dấu là trạng thái đang tiến hành đồng bộ
                var logId = item["LogId"].ToString();
                _sourceAccess.ExcuteRawNonQuery(String.Format(updateLogCommand, (int)Status.SYNCED, item["LogId"]));

                var primaryKeyField = item["PrimaryKeyField"].ToString();
                var primaryKeyValue = item["PrimaryKeyValue"].ToString();
                var tableName       = item["TableName"].ToString().Replace(",", "");

                // Tạo câu truy vấn lấy dữ liệu từ CSDL Sql dựa theo khóa chính của từng bảng
                var selectQuery = item.ToDynamicSelect(primaryKeyField, primaryKeyValue);
                var dt          = _sourceAccess.ExcuteRawQuery(selectQuery) as DataTable;

                // Với từng trường hợp Insert, Update, Delete tạo câu lệnh tương ứng để excute trên DB Oracle
                var type          = item["Type"].ToString();
                var changeCommand = ChangeFactory.CreateCommand(type, dt, tableName, primaryKeyField, primaryKeyValue);
                var sqlList       = changeCommand.Excute();
                dict.Add(logId, sqlList);
            }

            //Tiến hành đồng bộ sang CSDL Oracle dựa vào câu lệnh sinh ra
            foreach (var item in dict)
            {
                try
                {
                    foreach (var tmp in item.Value)
                    {
                        _destinationAccess.ExcuteRawNonQuery(tmp);
                    }
                    _sourceAccess.ExcuteRawNonQuery(String.Format(deleteLogCommand, item.Key));
                }
                catch (Exception ex)
                {
                    Logger.Error(String.Format("Error sync with logId {0}: {1}", item.Key, ex));
                    _sourceAccess.ExcuteRawNonQuery(String.Format(updateLogCommand, (int)Status.ERROR, item.Key));
                }
            }
        }
Beispiel #7
0
        public void Run(string tableName,
                        string primaryKeyField,
                        bool isTruncated = true)
        {
            if (isTruncated)
            {
                var truncateCommand = String.Format("TRUNCATE TABLE {0}", tableName);
                _destinationAccess.ExcuteRawNonQuery(truncateCommand);
            }
            var selectCommand = String.Format("SELECT COUNT(1) Total FROM {0}", tableName);
            var total         = _sourceAccess.ExcuteRawQuery(selectCommand) as DataTable;
            var pageSize      = Utility.GetTopQuantity();
            var pageNumber    = Convert.ToInt32(total.Rows[0]["Total"]) / pageSize + 1;
            var dict          = new Dictionary <String, List <String> >();

            for (int index = 1; index <= pageNumber; index++)
            {
                var selectQuery = String.Format(@";WITH x AS (SELECT {1}, k = ROW_NUMBER() OVER (ORDER BY {1}) FROM {0})
                                                    SELECT e.*
                                                    FROM x INNER JOIN {0} AS e
                                                    ON x.{1} = e.{1}
                                                    WHERE x.k BETWEEN  {2} AND {3}",
                                                tableName,
                                                primaryKeyField,
                                                (index - 1) * pageSize + 1,
                                                index * pageSize);
                var dt            = _sourceAccess.ExcuteRawQuery(selectQuery) as DataTable;
                var changeCommand = ChangeFactory.CreateCommand(ChangeType.INSERTED, dt, tableName, primaryKeyField, string.Empty);
                var sqlList       = changeCommand.Excute();
                dict.Add(index.ToString(), sqlList);
            }
            foreach (var item in dict)
            {
                try
                {
                    foreach (var tmp in item.Value)
                    {
                        _destinationAccess.ExcuteRawNonQuery(tmp);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(String.Format("Error sync with logId: {0}", ex));
                }
            }
        }
        public void The_change_for_39_is_1_Quarter_1_Dime_4_Pennies()
        {
            //Arrange
            var changeFactory = new ChangeFactory();

            //Act
            var actualChangeItems = changeFactory.MakeChange(39);
            var expectedChangeItems = new List<int>()
            {
                25,
                10,
                1,
                1,
                1,
                1,
            };

            //Assert
            Assert.IsTrue(Enumerable.SequenceEqual(expectedChangeItems, actualChangeItems), "The change lists did not match.");
        }
        public void The_change_for_39_is_1_Quarter_1_Dime_4_Pennies()
        {
            //Arrange
            var changeFactory = new ChangeFactory();

            //Act
            var actualChangeItems   = changeFactory.MakeChange(39);
            var expectedChangeItems = new List <int>()
            {
                25,
                10,
                1,
                1,
                1,
                1,
            };

            //Assert
            Assert.IsTrue(Enumerable.SequenceEqual(expectedChangeItems, actualChangeItems), "The change lists did not match.");
        }
Beispiel #10
0
        public void Run(string childTableName,
                        string childPrimaryKeyField,
                        string parentTableName,
                        string parentPrimaryKeyField,
                        string createdDateColumn,
                        string startDate,
                        string endDate)
        {
            var command       = @"select {7} from {2}
                                                where exists (select top 1 1 from  {0}
                                                where  {4} > '{5}' AND {4} < '{6}'
                                                and  {0}.{1} = {2}.{1}
                                                )";
            var selectCommand = String.Format(command,
                                              parentTableName,
                                              parentPrimaryKeyField,
                                              childTableName,
                                              childPrimaryKeyField,
                                              createdDateColumn,
                                              startDate,
                                              endDate,
                                              "count(1) as Total");
            var total      = _sourceAccess.ExcuteRawQuery(selectCommand) as DataTable;
            var pageSize   = Utility.GetTopQuantity();
            var pageNumber = Convert.ToInt32(total.Rows[0]["Total"]) / pageSize + 1;
            var dict       = new Dictionary <String, List <String> >();

            for (int index = 1; index <= pageNumber; index++)
            {
                var pagingCommand = String.Format(command,
                                                  parentTableName,
                                                  parentPrimaryKeyField,
                                                  childTableName,
                                                  childPrimaryKeyField,
                                                  createdDateColumn,
                                                  startDate,
                                                  endDate,
                                                  "{1}, k = ROW_NUMBER() OVER (ORDER BY {1})");
                var selectQuery = String.Format(@";WITH x AS (" + pagingCommand + @")
                                                    SELECT e.*
                                                    FROM x INNER JOIN {0} AS e
                                                    ON x.{1} = e.{1}
                                                    WHERE x.k BETWEEN  {2} AND {3}",
                                                childTableName,
                                                childPrimaryKeyField,
                                                (index - 1) * pageSize + 1,
                                                index * pageSize);
                var dt            = _sourceAccess.ExcuteRawQuery(selectQuery) as DataTable;
                var changeCommand = ChangeFactory.CreateCommand(ChangeType.MERGED, dt, childTableName, childPrimaryKeyField, string.Empty);
                var sqlList       = changeCommand.Excute();
                dict.Add(index.ToString(), sqlList);
            }
            foreach (var item in dict)
            {
                try
                {
                    foreach (var tmp in item.Value)
                    {
                        _destinationAccess.ExcuteRawNonQuery(tmp);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(String.Format("Error sync with logId {0}: {1}", item.Key, ex));
                }
            }
        }
Beispiel #11
0
 public IncomingChangeProcessing(ChangeFactory changeFactory, AuthorizationStructure authorizationStructure)
 {
     _changeFactory          = changeFactory;
     _authorizationStructure = authorizationStructure;
 }