public void MergeChanges_Should_Set_ChangeTracker_For_Added_Order_With_Null_Customer()
        {
            // Arrange
            var database  = new MockNorthwind();
            var origOrder = new Order
            {
                OrderDate  = DateTime.Parse("1996-07-04"),
                CustomerId = "ALFKI"
            };
            var changeTracker = new ChangeTrackingCollection <Order>(true)
            {
                origOrder
            };
            var addedOrder = AddOrders(database, origOrder)[0];

            // Act
            changeTracker.MergeChanges(addedOrder);
            TrackingState origTrackingState = origOrder.Customer.TrackingState;

            origOrder.Customer.CustomerName = "xxx";

            // Assert
            Assert.Equal(TrackingState.Unchanged, origTrackingState);
            Assert.Equal(TrackingState.Modified, origOrder.Customer.TrackingState);
            Assert.Contains("CustomerName", origOrder.Customer.ModifiedProperties);
        }
        public void MergeChanges_Should_Set_Modified_Customer_With_Unchanged_Setting()
        {
            // Arrange
            var database = new MockNorthwind();
            var order    = database.Orders[0];
            var customer = order.Customer;

            customer.CustomerSetting = new CustomerSetting
            {
                CustomerId = customer.CustomerId,
                Customer   = customer,
                Setting    = "Setting1"
            };
            var changeTracker   = new ChangeTrackingCollection <Order>(order);
            var name            = customer.CustomerName = "xxx";
            var origState       = customer.TrackingState;
            var changes         = changeTracker.GetChanges();
            var changedCustomer = changes[0].Customer;
            var updatedOrder    = changes[0].Clone <Order>();

            updatedOrder.AcceptChanges();

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.Equal(name, customer.CustomerName);                     // Changed customer name is preserved
            Assert.Null(changedCustomer.CustomerSetting);                  // GetChanges sets unchanges ref props to null
            Assert.NotNull(order.Customer.CustomerSetting);                // Unchanged ref props not overwritten
            Assert.Equal(TrackingState.Modified, origState);               // Changed state is modified
            Assert.Equal(TrackingState.Unchanged, customer.TrackingState); // State set to unchanged
        }
        public void MergeChanges_Should_Set_Unchanged_Customer_With_Modified_Setting()
        {
            // Arrange
            var database = new MockNorthwind();
            var order    = database.Orders[0];
            var customer = order.Customer;

            customer.CustomerSetting = new CustomerSetting
            {
                CustomerId = customer.CustomerId,
                Customer   = customer,
                Setting    = "Setting1"
            };
            var changeTracker   = new ChangeTrackingCollection <Order>(order);
            var setting         = customer.CustomerSetting.Setting = "xxx";
            var origState       = customer.CustomerSetting.TrackingState;
            var changes         = changeTracker.GetChanges();
            var changedCustomer = changes[0].Customer;
            var updatedOrder    = changes[0].Clone <Order>();

            updatedOrder.AcceptChanges();

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.Equal(setting, customer.CustomerSetting.Setting);       // Changed customer setting is preserved
            Assert.Equal(TrackingState.Modified, origState);               // Changed state is modified
            Assert.Equal(TrackingState.Unchanged, customer.TrackingState); // State set to unchanged
        }
        public void MergeChanges_Should_Set_Modified_Employee_With_Unchanged_Territories()
        {
            // Arrange
            var database               = new MockNorthwind();
            var employee               = database.Employees[0];
            var unchangedterritory     = employee.Territories[0];
            var modifiedterritory      = employee.Territories[1];
            var deletedterritory       = employee.Territories[2];
            var addedExistingTerritory = database.Territories[3];
            var addedNewTerritory      = new Territory
            {
                TerritoryId          = "91360",
                TerritoryDescription = "SouthernCalifornia",
                Employees            = new ChangeTrackingCollection <Employee> {
                    employee
                }
            };
            var changeTracker      = new ChangeTrackingCollection <Employee>(employee);
            var name               = employee.LastName = "xxx";
            var origState          = employee.TrackingState;
            var changes            = changeTracker.GetChanges();
            var changedTerritories = changes[0].Territories;
            var updatedEmployee    = changes[0].Clone <Employee>();

            updatedEmployee.AcceptChanges();

            // Act
            changeTracker.MergeChanges(updatedEmployee);

            // Assert
            Assert.Equal(name, employee.LastName);       // Changed prop is preserved
            Assert.Empty(changedTerritories);            // GetChanges sets unchanges ref props to null
            Assert.Equal(3, employee.Territories.Count); // Unchanged items preserved
        }
        public void WhenISubmitPostToCreateAnEntity()
        {
            ScenarioContext.Current.Pending();

            var customer = ScenarioContext.Current.Get<Customer>("Customer");
            var changeTracker = new ChangeTrackingCollection<Customer>(true) { customer };
            Customer result = _client.CreateEntity(customer);
            changeTracker.MergeChanges(result);
        }
예제 #6
0
        static void Main(string[] args)
        {
            // Main method

            Console.WriteLine("Press Enter to start");
            Console.ReadLine();

            // Create http client
            const string serviceBaseAddress = "http://localhost:" + "49640" + "/";
            var          client             = new HttpClient {
                BaseAddress = new Uri(serviceBaseAddress)
            };

            List <Product> products = GetProducts(client).ToList();

            foreach (var p in products)
            {
                PrintProduct(p);
            }

            // Select individual product
            Console.WriteLine("\nProduct to update {ProductId}:");
            int productId = int.Parse(Console.ReadLine());
            var product   = products.Single(p => p.ProductId == productId);

            // Track changes
            var changeTracker = new ChangeTrackingCollection <Product>(product);

            // Update product
            product.UnitPrice++;

            // Get changes
            var changedProduct = changeTracker.GetChanges().SingleOrDefault();

            // Submit changes
            Product updatedProduct;

            if (product is DiscontinuedProduct)
            {
                updatedProduct = UpdateEntity(client, (DiscontinuedProduct)product);
            }
            else
            {
                updatedProduct = UpdateEntity(client, product);
            }

            // Merge changes
            changeTracker.MergeChanges(updatedProduct);

            Console.WriteLine("Updated product:");
            PrintProduct(product);

            // Keep console open
            Console.WriteLine("\nPress any key to exit");
            Console.ReadKey(true);
        }
        public void WhenISubmitPostToCreateAnEntity()
        {
            ScenarioContext.Current.Pending();

            var customer      = ScenarioContext.Current.Get <Customer>("Customer");
            var changeTracker = new ChangeTrackingCollection <Customer>(true)
            {
                customer
            };
            Customer result = _client.CreateEntity(customer);

            changeTracker.MergeChanges(result);
        }
        public void MergeChanges_On_Equatable_PromotionalProduct_Should_Not_Throw_ArgumentException()
        {
            // Arrange
            var product       = new MockNorthwind().Products.OfType <PromotionalProduct>().First();
            var changeTracker = new ChangeTrackingCollection <PromotionalProduct>(product);
            var clonedProduct = product.Clone();

            // Act
            changeTracker.MergeChanges(clonedProduct);

            // Assert
            Assert.True(true);
        }
        public void MergeChanges_On_Equatable_Customer_Should_Not_Throw_ArgumentException()
        {
            // Arrange
            var customer = new Customer {
                CustomerId = "ALFKI"
            };
            var changeTracker = new ChangeTrackingCollection <Customer>(customer);

            // Act
            changeTracker.MergeChanges();

            // Assert
            Assert.True(true);
        }
        public void MergeChanges_Should_Merge_Updates_For_Unchanged_Order_With_Changed_OrderDetails()
        {
            // Arrange
            var database  = new MockNorthwind();
            var origOrder = database.Orders[0];
            var product   = database.Products.Single(p => p.ProductId == 14);

            origOrder.OrderDetails.Add(new OrderDetail {
                ProductId = 14, OrderId = 10249, Quantity = 9, UnitPrice = 18.6000M, Product = product
            });
            var unchangedDetail = origOrder.OrderDetails[0];
            var modifiedDetail  = origOrder.OrderDetails[1];
            var deletedDetail   = origOrder.OrderDetails[3];
            var changeTracker   = new ChangeTrackingCollection <Order>(origOrder);

            origOrder.OrderDetails[1].Product.ProductName = "xxx";
            origOrder.OrderDetails[2].Quantity++;
            origOrder.OrderDetails[2].ProductId = 1;
            var newUnitPrice = origOrder.OrderDetails[2].UnitPrice + 1;

            origOrder.OrderDetails.RemoveAt(3);
            var addedDetail = new OrderDetail {
                ProductId = 51, OrderId = 10249, Quantity = 40, UnitPrice = 42.4000M
            };

            origOrder.OrderDetails.Add(addedDetail);

            var changes      = changeTracker.GetChanges();
            var updatedOrder = UpdateOrdersWithDetails(database, changes)[0];

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.Contains(unchangedDetail, origOrder.OrderDetails);                                                  // Unchanged present
            Assert.Equal("xxx", origOrder.OrderDetails[1].Product.ProductName);                                        // Prod name updated
            Assert.Equal(updatedOrder.OrderDetails[1].ProductId, origOrder.OrderDetails[2].Product.ProductId);         // Changed Product set
            Assert.Equal(newUnitPrice, origOrder.OrderDetails[2].UnitPrice);                                           // Db-generated value set
            Assert.Equal(updatedOrder.OrderDetails[2].Product.ProductId, origOrder.OrderDetails[3].Product.ProductId); // Added detail Product set
            Assert.True(origOrder.OrderDetails.All(d => d.TrackingState == TrackingState.Unchanged));                  // Details unchanged
            Assert.Same(addedDetail, origOrder.OrderDetails.Single(d => d.ProductId == 51));                           // Ref equality
            Assert.Same(modifiedDetail, origOrder.OrderDetails.Single(d => d.ProductId == 42));                        // Ref equality
            Assert.DoesNotContain(deletedDetail, origOrder.OrderDetails);                                              // Detail deleted
            ICollection cachedDeletes = ((ITrackingCollection)origOrder.OrderDetails).CachedDeletes;

            Assert.Empty(cachedDeletes); // Cached deletes have been removed
        }
        public void MergeChanges_Should_Set_Properties_For_Modified_Order_With_Updated_Customer()
        {
            // Arrange
            var database = new MockNorthwind();
            var origOrder = database.Orders[0];
            var changeTracker = new ChangeTrackingCollection<Order>(origOrder);
            origOrder.CustomerId = "ALFKI";
            var updatedOrder = UpdateOrders(database, origOrder)[0];

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.AreEqual(updatedOrder.CustomerId, origOrder.CustomerId);
            Assert.AreEqual(updatedOrder.Customer.CustomerId, origOrder.Customer.CustomerId);
            Assert.AreEqual(updatedOrder.OrderDate, origOrder.OrderDate);
        }
        public void MergeChanges_Should_Set_ModifiedProperties_To_Null_For_Modified_Order_With_Updated_Customer()
        {
            // Arrange
            var database = new MockNorthwind();
            var origOrder = database.Orders[0];
            var changeTracker = new ChangeTrackingCollection<Order>(origOrder);
            origOrder.CustomerId = "ALFKI";
            var origModifiedProps = origOrder.ModifiedProperties;
            var updatedOrder = UpdateOrders(database, origOrder)[0];

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.Contains("CustomerId", origModifiedProps);
            Assert.Null(origOrder.ModifiedProperties);
        }
        public void MergeChanges_Should_Set_TrackingState_To_Unchanged_For_Modified_Order_With_Updated_Customer()
        {
            // Arrange
            var database = new MockNorthwind();
            var origOrder = database.Orders[0];
            var changeTracker = new ChangeTrackingCollection<Order>(origOrder);
            origOrder.CustomerId = "ALFKI";
            TrackingState origTrackingState = origOrder.TrackingState;
            var updatedOrder = UpdateOrders(database, origOrder)[0];

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.Equal(TrackingState.Modified, origTrackingState);
            Assert.Equal(TrackingState.Unchanged, origOrder.TrackingState);
        }
        public void MergeChanges_Should_Set_ModifiedProperties_To_Null_For_Modified_Order_With_Updated_Customer()
        {
            // Arrange
            var database      = new MockNorthwind();
            var origOrder     = database.Orders[0];
            var changeTracker = new ChangeTrackingCollection <Order>(origOrder);

            origOrder.CustomerId = "ALFKI";
            var origModifiedProps = origOrder.ModifiedProperties;
            var updatedOrder      = UpdateOrders(database, origOrder)[0];

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.Contains("CustomerId", origModifiedProps);
            Assert.Null(origOrder.ModifiedProperties);
        }
        public void MergeChanges_Should_Set_TrackingState_To_Unchanged_For_Modified_Order_With_Updated_Customer()
        {
            // Arrange
            var database      = new MockNorthwind();
            var origOrder     = database.Orders[0];
            var changeTracker = new ChangeTrackingCollection <Order>(origOrder);

            origOrder.CustomerId = "ALFKI";
            TrackingState origTrackingState = origOrder.TrackingState;
            var           updatedOrder      = UpdateOrders(database, origOrder)[0];

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.Equal(TrackingState.Modified, origTrackingState);
            Assert.Equal(TrackingState.Unchanged, origOrder.TrackingState);
        }
예제 #16
0
        public void MergeChanges_Should_Set_Properties_For_Modified_Order_With_Updated_Customer()
        {
            // Arrange
            var database      = new MockNorthwind();
            var origOrder     = database.Orders[0];
            var changeTracker = new ChangeTrackingCollection <Order>(origOrder);

            origOrder.CustomerId = "ALFKI";
            var updatedOrder = UpdateOrders(database, origOrder)[0];

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.AreEqual(updatedOrder.CustomerId, origOrder.CustomerId);
            Assert.AreEqual(updatedOrder.Customer.CustomerId, origOrder.Customer.CustomerId);
            Assert.AreEqual(updatedOrder.OrderDate, origOrder.OrderDate);
        }
        public void MergeChanges_Should_Set_Order_With_Modified_Customer_With_Db_Generated_Values()
        {
            // Arrange
            var database      = new MockNorthwind();
            var order         = database.Orders[0];
            var changeTracker = new ChangeTrackingCollection <Order>(order);
            var customer      = order.Customer;
            var name          = customer.CustomerName = "xxx";
            var changes       = changeTracker.GetChanges();
            var updatedOrder  = changes[0].Clone <Order>();
            var data          = updatedOrder.Customer.Data = "yyy"; // simulate db-generated values

            updatedOrder.AcceptChanges();

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.Equal(name, order.Customer.CustomerName);
            Assert.Equal(data, order.Customer.Data);
        }
예제 #18
0
        public void MergeChanges_Should_Set_ChangeTracker_For_Modified_Order_With_Updated_Customer()
        {
            // Arrange
            var database      = new MockNorthwind();
            var origOrder     = database.Orders[0];
            var changeTracker = new ChangeTrackingCollection <Order>(origOrder);

            origOrder.CustomerId = "ALFKI";
            var updatedOrder = UpdateOrders(database, origOrder)[0];

            // Act
            changeTracker.MergeChanges(updatedOrder);
            TrackingState origTrackingState = origOrder.Customer.TrackingState;

            origOrder.Customer.CustomerName = "xxx";

            // Assert
            Assert.AreEqual(TrackingState.Unchanged, origTrackingState);
            Assert.AreEqual(TrackingState.Modified, origOrder.Customer.TrackingState);
            Assert.Contains("CustomerName", (ICollection)origOrder.Customer.ModifiedProperties);
        }
        public void MergeChanges_Should_Set_Properties_For_Multiple_Modified_Orders_With_Updated_Customer()
        {
            // Arrange
            var database      = new MockNorthwind();
            var origOrder1    = database.Orders[0];
            var origOrder2    = database.Orders[1];
            var changeTracker = new ChangeTrackingCollection <Order>(origOrder1, origOrder2);

            origOrder1.CustomerId = "ALFKI";
            origOrder2.CustomerId = "ANATR";
            var updatedOrders = UpdateOrders(database, origOrder1, origOrder2);

            // Act
            changeTracker.MergeChanges(updatedOrders.ToArray());

            // Assert
            Assert.Equal(updatedOrders[0].CustomerId, origOrder1.CustomerId);
            Assert.Equal(updatedOrders[0].Customer.CustomerId, origOrder1.Customer.CustomerId);
            Assert.Equal(updatedOrders[0].OrderDate, origOrder1.OrderDate);
            Assert.Equal(updatedOrders[1].CustomerId, origOrder2.CustomerId);
            Assert.Equal(updatedOrders[1].Customer.CustomerId, origOrder2.Customer.CustomerId);
            Assert.Equal(updatedOrders[1].OrderDate, origOrder2.OrderDate);
        }
        public void MergeChanges_Should_Set_Modified_Order_With_Unchanged_Customer()
        {
            // Arrange
            var database      = new MockNorthwind();
            var order         = database.Orders[0];
            var changeTracker = new ChangeTrackingCollection <Order>(order);
            var date          = order.OrderDate = order.OrderDate.AddDays(1);
            var origState     = order.TrackingState;
            var changes       = changeTracker.GetChanges();
            var changedOrder  = changes[0];
            var updatedOrder  = changes[0].Clone <Order>();

            updatedOrder.AcceptChanges();

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.Equal(date, order.OrderDate);                        // Changed order date is preserved
            Assert.Null(changedOrder.Customer);                         // GetChanges sets unchanges ref props to null
            Assert.NotNull(order.Customer);                             // Unchanged order.Customer is not overwritten
            Assert.Equal(TrackingState.Modified, origState);            // Changed state is modified
            Assert.Equal(TrackingState.Unchanged, order.TrackingState); // State set to unchanged
        }
        public void MergeChanges_Should_Set_TrackingState_To_Unchanged_For_Added_Order_With_Null_Customer()
        {
            // Arrange
            var database  = new MockNorthwind();
            var origOrder = new PriorityOrder
            {
                PriorityPlan = "Silver",
                OrderDate    = DateTime.Parse("1996-07-04"),
                CustomerId   = "ALFKI"
            };
            var changeTracker = new ChangeTrackingCollection <Order>(true)
            {
                origOrder
            };
            var addedOrder = AddOrders(database, origOrder)[0];

            // Act
            changeTracker.MergeChanges(addedOrder);

            // Assert
            Assert.Equal(addedOrder.CustomerId, origOrder.CustomerId);
            Assert.Equal(addedOrder.Customer.CustomerId, origOrder.Customer.CustomerId);
            Assert.Equal(addedOrder.OrderDate, origOrder.OrderDate);
        }
        public void MergeChanges_Should_Set_ChangeTracker_For_Modified_Order_With_Updated_Customer()
        {
            // Arrange
            var database = new MockNorthwind();
            var origOrder = database.Orders[0];
            var changeTracker = new ChangeTrackingCollection<Order>(origOrder);
            origOrder.CustomerId = "ALFKI";
            var updatedOrder = UpdateOrders(database, origOrder)[0];

            // Act
            changeTracker.MergeChanges(updatedOrder);
            TrackingState origTrackingState = origOrder.Customer.TrackingState;
            origOrder.Customer.CustomerName = "xxx";

            // Assert
            Assert.AreEqual(TrackingState.Unchanged, origTrackingState);
            Assert.AreEqual(TrackingState.Modified, origOrder.Customer.TrackingState);
            Assert.Contains("CustomerName", (ICollection)origOrder.Customer.ModifiedProperties);
        }
        public void MergeChanges_Should_Set_Order_With_Modified_Customer_With_Db_Generated_Values()
        {
            // Arrange
            var database = new MockNorthwind();
            var order = database.Orders[0];
            var changeTracker = new ChangeTrackingCollection<Order>(order);
            var customer = order.Customer;
            var name = customer.CustomerName = "xxx";
            var changes = changeTracker.GetChanges();
            var updatedOrder = changes[0].Clone<Order>();
            var data = updatedOrder.Customer.Data = "yyy"; // simulate db-generated values
            updatedOrder.AcceptChanges();

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.Equal(name, order.Customer.CustomerName);
            Assert.Equal(data, order.Customer.Data);
        }
        public void MergeChanges_Should_Merge_Updates_For_Unchanged_Employee_With_Changed_Territories()
        {
            // Arrange
            var database = new MockNorthwind();
            var employee = database.Employees[0];
            var unchangedTerritory = employee.Territories[0];
            var modifiedTerritory = employee.Territories[1];
            var deletedTerritory = employee.Territories[2];
            var addedExistingTerritory = database.Territories[3];
            var area1 = new Area { AreaId = 1, AreaName = "Northern", Territories = new ChangeTrackingCollection<Territory> { unchangedTerritory } };
            var area2 = new Area { AreaId = 2, AreaName = "Southern", Territories = new ChangeTrackingCollection<Territory> { modifiedTerritory } };
            var area3 = new Area { AreaId = 3, AreaName = "Eastern", Territories = new ChangeTrackingCollection<Territory> { deletedTerritory } };
            var area4 = new Area { AreaId = 4, AreaName = "Western", Territories = new ChangeTrackingCollection<Territory> { addedExistingTerritory } };
            var addedNewTerritory = new Territory
            {
                TerritoryId = "91360",
                TerritoryDescription = "SouthernCalifornia",
                Employees = new ChangeTrackingCollection<Employee> { employee },
                AreaId = 5,
                TrackingState = TrackingState.Added // Must explicitly mark as added
            };
            unchangedTerritory.Area = area1;
            unchangedTerritory.AreaId = area1.AreaId;
            modifiedTerritory.Area = area2;
            modifiedTerritory.AreaId = area2.AreaId;
            deletedTerritory.Area = area3;
            deletedTerritory.AreaId = area3.AreaId;
            addedExistingTerritory.Area = area4;
            addedExistingTerritory.AreaId = area4.AreaId;

            var changeTracker = new ChangeTrackingCollection<Employee>(employee);
            modifiedTerritory.TerritoryDescription = "xxx"; // mod prop
            modifiedTerritory.AreaId = 6; // mod FK prop
            employee.Territories.Remove(deletedTerritory); // should mark area deleted
            employee.Territories.Add(addedExistingTerritory); // should keep area unchanged
            employee.Territories.Add(addedNewTerritory); // should keep territory added
            addedExistingTerritory.Area.AreaName = "zzz"; // should mark area modified

            var changes = changeTracker.GetChanges(); // should exclude unchanged territory
            var updatedEmployee = UpdateEmployeesWithTerritories(changes)[0]; // rel entities, db-gen vals

            // Act
            changeTracker.MergeChanges(updatedEmployee);

            // Assert
            Assert.Contains(unchangedTerritory, employee.Territories); // Unchanged present
            Assert.Equal("zzz", addedExistingTerritory.Area.AreaName); // Area name updated
            Assert.Equal("yyy", addedNewTerritory.Data); // Db-generated value set
            Assert.Equal(addedNewTerritory.AreaId, addedNewTerritory.Area.AreaId); // Added territory Area set
            Assert.Equal(modifiedTerritory.AreaId, modifiedTerritory.Area.AreaId); // Modified territory Area set
            Assert.Same(addedExistingTerritory, employee.Territories.Single(t => t.TerritoryId == "02116")); // Ref equality
            Assert.Same(addedNewTerritory, employee.Territories.Single(t => t.TerritoryId == "91360")); // Ref equality
            Assert.Same(modifiedTerritory, employee.Territories.Single(t => t.TerritoryId == "01730")); // Ref equality
            Assert.DoesNotContain(deletedTerritory, employee.Territories); // Detail deleted
            ICollection cachedDeletes = ((ITrackingCollection)employee.Territories).GetChanges(true);
            Assert.Empty(cachedDeletes); // Cached deletes have been removed
        }
        public void MergeChanges_Should_Set_TrackingState_To_Unchanged_For_Added_Order_With_Null_Customer()
        {
            // Arrange
            var database = new MockNorthwind();
            var origOrder = new PriorityOrder
            {
                PriorityPlan = "Silver",
                OrderDate = DateTime.Parse("1996-07-04"),
                CustomerId = "ALFKI"
            };
            var changeTracker = new ChangeTrackingCollection<Order>(true) { origOrder };
            var addedOrder = AddOrders(database, origOrder)[0];

            // Act
            changeTracker.MergeChanges(addedOrder);

            // Assert
            Assert.Equal(addedOrder.CustomerId, origOrder.CustomerId);
            Assert.Equal(addedOrder.Customer.CustomerId, origOrder.Customer.CustomerId);
            Assert.Equal(addedOrder.OrderDate, origOrder.OrderDate);
        }
        public void MergeChanges_On_Equatable_PromotionalProduct_Should_Not_Throw_ArgumentException()
        {
            // Arrange
            var product = new MockNorthwind().Products.OfType<PromotionalProduct>().First();
            var changeTracker = new ChangeTrackingCollection<PromotionalProduct>(product);
            var clonedProduct = product.Clone();

            // Act
            changeTracker.MergeChanges(clonedProduct);

            // Assert
            Assert.True(true);
        }
        public void MergeChanges_Should_Set_Properties_For_Multiple_Modified_Orders_With_Updated_Customer()
        {
            // Arrange
            var database = new MockNorthwind();
            var origOrder1 = database.Orders[0];
            var origOrder2 = database.Orders[1];
            var changeTracker = new ChangeTrackingCollection<Order>(origOrder1, origOrder2);
            origOrder1.CustomerId = "ALFKI";
            origOrder2.CustomerId = "ANATR";
            var updatedOrders = UpdateOrders(database, origOrder1, origOrder2);

            // Act
            changeTracker.MergeChanges(updatedOrders.ToArray());

            // Assert
            Assert.Equal(updatedOrders[0].CustomerId, origOrder1.CustomerId);
            Assert.Equal(updatedOrders[0].Customer.CustomerId, origOrder1.Customer.CustomerId);
            Assert.Equal(updatedOrders[0].OrderDate, origOrder1.OrderDate);
            Assert.Equal(updatedOrders[1].CustomerId, origOrder2.CustomerId);
            Assert.Equal(updatedOrders[1].Customer.CustomerId, origOrder2.Customer.CustomerId);
            Assert.Equal(updatedOrders[1].OrderDate, origOrder2.OrderDate);
        }
        public void MergeChanges_Should_Set_Properties_For_Added_Order_With_Null_Customer()
        {
            // Arrange
            var database = new MockNorthwind();
            var origOrder = new Order
            {
                OrderDate = DateTime.Parse("1996-07-04"),
                CustomerId = "ALFKI"
            };
            var changeTracker = new ChangeTrackingCollection<Order>(true) {origOrder};
            TrackingState origTrackingState = origOrder.TrackingState;
            var addedOrder = AddOrders(database, origOrder)[0];

            // Act
            changeTracker.MergeChanges(addedOrder);

            // Assert
            Assert.Equal(TrackingState.Added, origTrackingState);
            Assert.Equal(TrackingState.Unchanged, origOrder.TrackingState);
        }
예제 #29
0
        static void Main(string[] args)
        {
            Console.WriteLine("Press Enter to start");
            Console.ReadLine();

            ICustomerService customerService = new ChannelFactory<ICustomerService>("customerService").CreateChannel();
            IOrderService orderService = new ChannelFactory<IOrderService>("orderService").CreateChannel();

            using ((IDisposable)customerService)
            using ((IDisposable)orderService)
            {
                try
                {
                    // Get customers
                    Console.WriteLine("Customers:");
                    IEnumerable<Customer> customers = customerService.GetCustomersAsync().Result;
                    if (customers == null) return;
                    foreach (var c in customers)
                        PrintCustomer(c);

                    // Get orders for a customer
                    Console.WriteLine("\nGet customer orders {CustomerId}:");
                    string customerId = Console.ReadLine();
                    if (!customers.Any(c => string.Equals(c.CustomerId, customerId, StringComparison.OrdinalIgnoreCase)))
                    {
                        Console.WriteLine("Invalid customer id: {0}", customerId.ToUpper());
                        return;
                    }
                    IEnumerable<Order> orders = orderService.GetCustomerOrdersAsync(customerId).Result;
                    foreach (var o in orders)
                        PrintOrder(o);

                    // Get an order
                    Console.WriteLine("\nGet an order {OrderId}:");
                    int orderId = int.Parse(Console.ReadLine());
                    if (!orders.Any(o => o.OrderId == orderId))
                    {
                        Console.WriteLine("Invalid order id: {0}", orderId);
                        return;
                    }
                    Order order = orderService.GetOrderAsync(orderId).Result;
                    PrintOrderWithDetails(order);

                    // Create a new order
                    Console.WriteLine("\nPress Enter to create a new order for {0}",
                        customerId.ToUpper());
                    Console.ReadLine();

                    var newOrder = new Order
                    {
                        CustomerId = customerId,
                        OrderDate = DateTime.Today,
                        ShippedDate = DateTime.Today.AddDays(1),
                        OrderDetails = new ChangeTrackingCollection<OrderDetail>
                            {
                                new OrderDetail { ProductId = 1, Quantity = 5, UnitPrice = 10 },
                                new OrderDetail { ProductId = 2, Quantity = 10, UnitPrice = 20 },
                                new OrderDetail { ProductId = 4, Quantity = 40, UnitPrice = 40 }
                            }
                    };
                    var createdOrder = orderService.CreateOrderAsync(newOrder).Result;
                    PrintOrderWithDetails(createdOrder);

                    // Update the order
                    Console.WriteLine("\nPress Enter to update order details");
                    Console.ReadLine();

                    // Start change-tracking the order
                    var changeTracker = new ChangeTrackingCollection<Order>(createdOrder);

                    // Modify order details
                    createdOrder.OrderDetails[0].UnitPrice++;
                    createdOrder.OrderDetails.RemoveAt(1);
                    createdOrder.OrderDetails.Add(new OrderDetail
                    {
                        OrderId = createdOrder.OrderId,
                        ProductId = 3,
                        Quantity = 15,
                        UnitPrice = 30
                    });

                    // Submit changes
                    Order changedOrder = changeTracker.GetChanges().SingleOrDefault();
                    Order updatedOrder = orderService.UpdateOrderAsync(changedOrder).Result;

                    // Merge changes
                    changeTracker.MergeChanges(updatedOrder);
                    Console.WriteLine("Updated order:");
                    PrintOrderWithDetails(createdOrder);

                    // Delete the order
                    Console.WriteLine("\nPress Enter to delete the order");
                    Console.ReadLine();
                    bool deleted = orderService.DeleteOrderAsync(createdOrder.OrderId).Result;

                    // Verify order was deleted
                    Order deletedOrder = orderService.GetOrderAsync(createdOrder.OrderId).Result;
                    Console.WriteLine(deleted && deletedOrder == null
                        ? "Order was successfully deleted"
                        : "Order was not deleted");
                }
                catch (AggregateException aggEx)
                {
                    var baseEx = aggEx.Flatten().GetBaseException();
                    var innerExMsg = baseEx.InnerException != null ? "\r\n" + baseEx.InnerException.Message : "";
                    Console.WriteLine(baseEx.Message + innerExMsg);
                }
                finally
                {
                    var channel = customerService as IClientChannel;
                    if (channel != null && channel.State == CommunicationState.Faulted)
                    {
                        channel.Abort();
                    }
                }

                // Keep console open
                Console.WriteLine("Press any key to exit");
                Console.ReadKey(true);
            }
        }
        public void MergeChanges_Should_Set_Modified_Customer_With_Unchanged_Setting()
        {
            // Arrange
            var database = new MockNorthwind();
            var order = database.Orders[0];
            var customer = order.Customer;
            customer.CustomerSetting = new CustomerSetting
            {
                CustomerId = customer.CustomerId,
                Customer = customer,
                Setting = "Setting1"
            };
            var changeTracker = new ChangeTrackingCollection<Order>(order);
            var name = customer.CustomerName = "xxx";
            var origState = customer.TrackingState;
            var changes = changeTracker.GetChanges();
            var changedCustomer = changes[0].Customer;
            var updatedOrder = changes[0].Clone<Order>();
            updatedOrder.AcceptChanges();

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.Equal(name, customer.CustomerName); // Changed customer name is preserved
            Assert.Null(changedCustomer.CustomerSetting); // GetChanges sets unchanges ref props to null
            Assert.NotNull(order.Customer.CustomerSetting); // Unchanged ref props not overwritten
            Assert.Equal(TrackingState.Modified, origState); // Changed state is modified
            Assert.Equal(TrackingState.Unchanged, customer.TrackingState); // State set to unchanged
        }
예제 #31
0
        static void Main()
        {
            // Get media type formatter
            MediaTypeFormatter formatter;
            string acceptHeader;
            GetFormatter(out formatter, out acceptHeader);

            // TODO: Address for Web API service (replace port number)
            const string serviceBaseAddress = "http://localhost:" + "58527" + "/";
            var client = new HttpClient { BaseAddress = new Uri(serviceBaseAddress) };
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader));

            // Get customers
            Console.WriteLine("Customers:");
            IEnumerable<Customer> customers = GetCustomers(client, formatter);
            if (customers == null) return;
            foreach (var c in customers)
                PrintCustomer(c);

            // Get orders for a customer
            Console.WriteLine("\nGet customer orders {CustomerId}:");
            string customerId = Console.ReadLine();
            if (!customers.Any(c => string.Equals(c.CustomerId, customerId, StringComparison.OrdinalIgnoreCase)))
            {
                Console.WriteLine("Invalid customer id: {0}", customerId.ToUpper());
                return;
            }
            IEnumerable<Order> orders = GetCustomerOrders(client, customerId, formatter);
            foreach (var o in orders)
                PrintOrder(o);

            // Get an order
            Console.WriteLine("\nGet an order {OrderId}:");
            int orderId = int.Parse(Console.ReadLine());
            if (!orders.Any(o => o.OrderId == orderId))
            {
                Console.WriteLine("Invalid order id: {0}", orderId);
                return;
            }
            Order order = GetOrder(client, orderId, formatter);
            PrintOrderWithDetails(order);

            // Create a new order
            Console.WriteLine("\nPress Enter to create a new order for {0}",
                customerId.ToUpper());
            Console.ReadLine();

            var newOrder = new Order
            {
                CustomerId = customerId,
                OrderDate = DateTime.Today,
                ShippedDate = DateTime.Today.AddDays(1),
                OrderDetails = new ChangeTrackingCollection<OrderDetail>
                    {
                        new OrderDetail { ProductId = 1, Quantity = 5, UnitPrice = 10 },
                        new OrderDetail { ProductId = 2, Quantity = 10, UnitPrice = 20 },
                        new OrderDetail { ProductId = 4, Quantity = 40, UnitPrice = 40 }
                    }
            };
            var createdOrder = CreateOrder(client, newOrder, formatter);
            PrintOrderWithDetails(createdOrder);

            // Update the order
            Console.WriteLine("\nPress Enter to update order details");
            Console.ReadLine();

            // Start change-tracking the order
            var changeTracker = new ChangeTrackingCollection<Order>(createdOrder);

            // Modify order details
            createdOrder.OrderDetails[0].UnitPrice++;
            createdOrder.OrderDetails.RemoveAt(1);
            createdOrder.OrderDetails.Add(new OrderDetail
            {
                OrderId = createdOrder.OrderId,
                ProductId = 3,
                Quantity = 15,
                UnitPrice = 30
            });

            // Submit changes
            var changedOrder = changeTracker.GetChanges().SingleOrDefault();
            var updatedOrder = UpdateOrder(client, changedOrder, formatter);

            // Merge changes
            changeTracker.MergeChanges(updatedOrder);
            Console.WriteLine("Updated order:");
            PrintOrderWithDetails(createdOrder);

            // Delete the order
            Console.WriteLine("\nPress Enter to delete the order");
            Console.ReadLine();
            DeleteOrder(client, createdOrder);

            // Verify order was deleted
            var deleted = VerifyOrderDeleted(client, createdOrder.OrderId);
            Console.WriteLine(deleted ?
                "Order was successfully deleted" :
                "Order was not deleted");

            // Keep console open
            Console.WriteLine("Press any key to exit");
            Console.ReadKey(true);
        }
        static void Main()
        {
            // To debug with Fiddler, append .fiddler to localhost
            const string baseAddress = "http://localhost:" + "5000" + "/";

            // Start
            Console.WriteLine("Press Enter to start");
            Console.ReadLine();
            INorthwindServiceAgent serviceAgent = new NorthwindServiceAgent(baseAddress, new JsonMediaTypeFormatter());

            // Get customers
            Console.WriteLine("Customers:");
            IEnumerable <Customer> customers = serviceAgent.GetCustomers().Result;

            if (customers == null)
            {
                return;
            }
            foreach (var c in customers)
            {
                PrintCustomer(c);
            }

            // Get orders for a customer
            Console.WriteLine("\nGet customer orders {CustomerId}:");
            string customerId = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(customerId))
            {
                return;
            }
            if (!customers.Any(c => string.Equals(c.CustomerId, customerId, StringComparison.OrdinalIgnoreCase)))
            {
                Console.WriteLine("Invalid customer id: {0}", customerId.ToUpper());
                return;
            }
            IEnumerable <Order> orders = serviceAgent.GetCustomerOrders(customerId).Result;

            foreach (var o in orders)
            {
                PrintOrder(o);
            }

            // Get an order
            Console.WriteLine("\nGet an order {OrderId}:");
            int orderId = int.Parse(Console.ReadLine());

            if (!orders.Any(o => o.OrderId == orderId))
            {
                Console.WriteLine("Invalid order id: {0}", orderId);
                return;
            }
            Order order = serviceAgent.GetOrder(orderId).Result;

            PrintOrderWithDetails(order);

            // Create a new order
            Console.WriteLine("\nPress Enter to create a new order for {0}",
                              customerId.ToUpper());
            Console.ReadLine();

            var newOrder = new Order
            {
                CustomerId   = customerId,
                OrderDate    = DateTime.Today,
                ShippedDate  = DateTime.Today.AddDays(1),
                OrderDetails = new ChangeTrackingCollection <OrderDetail>
                {
                    new OrderDetail {
                        ProductId = 1, Quantity = 5, UnitPrice = 10
                    },
                    new OrderDetail {
                        ProductId = 2, Quantity = 10, UnitPrice = 20
                    },
                    new OrderDetail {
                        ProductId = 4, Quantity = 40, UnitPrice = 40
                    }
                }
            };
            Order createdOrder = serviceAgent.CreateOrder(newOrder).Result;

            PrintOrderWithDetails(createdOrder);

            // Update the order
            Console.WriteLine("\nPress Enter to update order details");
            Console.ReadLine();

            // Start change-tracking the order
            var changeTracker = new ChangeTrackingCollection <Order>(createdOrder);

            // Modify order details
            createdOrder.OrderDetails[0].UnitPrice++;
            createdOrder.OrderDetails.RemoveAt(1);
            createdOrder.OrderDetails.Add(new OrderDetail
            {
                OrderId   = createdOrder.OrderId,
                ProductId = 3,
                Quantity  = 15,
                UnitPrice = 30
            });

            // Submit changes
            Order changedOrder = changeTracker.GetChanges().SingleOrDefault();
            Order updatedOrder = serviceAgent.UpdateOrder(changedOrder).Result;

            // Merge changes
            changeTracker.MergeChanges(updatedOrder);
            Console.WriteLine("Updated order:");
            PrintOrderWithDetails(createdOrder);

            // Delete the order
            Console.WriteLine("\nPress Enter to delete the order");
            Console.ReadLine();
            serviceAgent.DeleteOrder(createdOrder).Wait();

            // Verify order was deleted
            bool deleted = serviceAgent.VerifyOrderDeleted(createdOrder.OrderId).Result;

            Console.WriteLine(deleted ?
                              "Order was successfully deleted" :
                              "Order was not deleted");

            // Keep console open
            Console.WriteLine("Press any key to exit");
            Console.ReadKey(true);
        }
        public void MergeChanges_Should_Set_Modified_Employee_With_Unchanged_Territories()
        {
            // Arrange
            var database = new MockNorthwind();
            var employee = database.Employees[0];
            var unchangedterritory = employee.Territories[0];
            var modifiedterritory = employee.Territories[1];
            var deletedterritory = employee.Territories[2];
            var addedExistingTerritory = database.Territories[3];
            var addedNewTerritory = new Territory
            {
                TerritoryId = "91360",
                TerritoryDescription = "SouthernCalifornia",
                Employees = new ChangeTrackingCollection<Employee> {employee}
            };
            var changeTracker = new ChangeTrackingCollection<Employee>(employee);
            var name = employee.LastName = "xxx";
            var origState = employee.TrackingState;
            var changes = changeTracker.GetChanges();
            var changedTerritories = changes[0].Territories;
            var updatedEmployee = changes[0].Clone<Employee>();
            updatedEmployee.AcceptChanges();

            // Act
            changeTracker.MergeChanges(updatedEmployee);

            // Assert
            Assert.Equal(name, employee.LastName); // Changed prop is preserved
            Assert.Empty(changedTerritories); // GetChanges sets unchanges ref props to null
            Assert.Equal(3, employee.Territories.Count); // Unchanged items preserved
        }
예제 #34
0
        static void Main(string[] args)
        {
            Console.WriteLine("Press Enter get customers");
            Console.ReadLine();

            // Get media type formatter
            MediaTypeFormatter formatter;
            string             acceptHeader;

            GetFormatter(out formatter, out acceptHeader);

            // TODO: Address for Web API service (replace port number)
            const string serviceBaseAddress = "http://localhost:" + "64139" + "/";
            var          client             = new HttpClient {
                BaseAddress = new Uri(serviceBaseAddress)
            };

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader));

            // Get customers
            Console.WriteLine("Customers:");
            IEnumerable <Customer> customers = GetCustomers(client, formatter);

            if (customers == null)
            {
                return;
            }
            foreach (var c in customers)
            {
                PrintCustomer(c);
            }

            // Get orders for a customer
            Console.WriteLine("\nGet customer orders {CustomerId}:");
            string customerId = Console.ReadLine();

            if (!customers.Any(c => string.Equals(c.CustomerId, customerId, StringComparison.OrdinalIgnoreCase)))
            {
                Console.WriteLine("Invalid customer id: {0}", customerId.ToUpper());
                return;
            }
            IEnumerable <Order> orders = GetCustomerOrders(client, customerId, formatter);

            foreach (var o in orders)
            {
                PrintOrder(o);
            }

            // Get an order
            Console.WriteLine("\nGet an order {OrderId}:");
            int orderId = int.Parse(Console.ReadLine());

            if (!orders.Any(o => o.OrderId == orderId))
            {
                Console.WriteLine("Invalid order id: {0}", orderId);
                return;
            }
            Order order = GetOrder(client, orderId, formatter);

            PrintOrderWithDetails(order);

            // Create a new order
            Console.WriteLine("\nPress Enter to create a new order for {0}",
                              customerId.ToUpper());
            Console.ReadLine();

            var newOrder = new Order
            {
                CustomerId   = customerId,
                OrderDate    = DateTime.Today,
                ShippedDate  = DateTime.Today.AddDays(1),
                OrderDetails = new ChangeTrackingCollection <OrderDetail>
                {
                    new OrderDetail {
                        ProductId = 1, Quantity = 5, UnitPrice = 10
                    },
                    new OrderDetail {
                        ProductId = 2, Quantity = 10, UnitPrice = 20
                    },
                    new OrderDetail {
                        ProductId = 4, Quantity = 40, UnitPrice = 40
                    }
                }
            };
            var createdOrder = CreateOrder(client, newOrder, formatter);

            PrintOrderWithDetails(createdOrder);

            // Update the order
            Console.WriteLine("\nPress Enter to update order and details");
            Console.ReadLine();

            // Start change-tracking the order
            var changeTracker = new ChangeTrackingCollection <Order>(createdOrder);

            // Modify order
            createdOrder.OrderDate = createdOrder.OrderDate.GetValueOrDefault().AddDays(1);

            // Modify order details
            createdOrder.OrderDetails[0].UnitPrice++;
            createdOrder.OrderDetails.RemoveAt(1);
            createdOrder.OrderDetails.Add(new OrderDetail
            {
                OrderId   = createdOrder.OrderId,
                ProductId = 3,
                Quantity  = 15,
                UnitPrice = 30
            });

            // Submit changes
            var changedOrder = changeTracker.GetChanges().SingleOrDefault();
            var updatedOrder = UpdateOrder(client, changedOrder, formatter);

            // Merge changes
            changeTracker.MergeChanges(updatedOrder);
            Console.WriteLine("Updated order:");
            PrintOrderWithDetails(createdOrder);

            // Delete the order
            Console.WriteLine("\nPress Enter to delete the order");
            Console.ReadLine();
            DeleteOrder(client, createdOrder);

            // Verify order was deleted
            var deleted = VerifyOrderDeleted(client, createdOrder.OrderId);

            Console.WriteLine(deleted ?
                              "Order was successfully deleted" :
                              "Order was not deleted");

            // Keep console open
            Console.WriteLine("Press any key to exit");
            Console.ReadKey(true);
        }
        public void MergeChanges_Should_Set_Modified_Order_With_Unchanged_Customer()
        {
            // Arrange
            var database = new MockNorthwind();
            var order = database.Orders[0];
            var changeTracker = new ChangeTrackingCollection<Order>(order);
            var date = order.OrderDate = order.OrderDate.AddDays(1);
            var origState = order.TrackingState;
            var changes = changeTracker.GetChanges();
            var changedOrder = changes[0];
            var updatedOrder = changes[0].Clone<Order>();
            updatedOrder.AcceptChanges();

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.Equal(date, order.OrderDate); // Changed order date is preserved
            Assert.Null(changedOrder.Customer); // GetChanges sets unchanges ref props to null
            Assert.NotNull(order.Customer); // Unchanged order.Customer is not overwritten
            Assert.Equal(TrackingState.Modified, origState); // Changed state is modified
            Assert.Equal(TrackingState.Unchanged, order.TrackingState); // State set to unchanged
        }
        public void MergeChanges_On_Equatable_Customer_Should_Not_Throw_ArgumentException()
        {
            // Arrange
            var customer = new Customer { CustomerId = "ALFKI" };
            var changeTracker = new ChangeTrackingCollection<Customer>(customer);

            // Act
            changeTracker.MergeChanges();

            // Assert
            Assert.True(true);
        }
        public void MergeChanges_Should_Merge_Updates_For_Unchanged_Employee_With_Changed_Territories()
        {
            // Arrange
            var database               = new MockNorthwind();
            var employee               = database.Employees[0];
            var unchangedTerritory     = employee.Territories[0];
            var modifiedTerritory      = employee.Territories[1];
            var deletedTerritory       = employee.Territories[2];
            var addedExistingTerritory = database.Territories[3];
            var area1 = new Area {
                AreaId = 1, AreaName = "Northern", Territories = new ChangeTrackingCollection <Territory> {
                    unchangedTerritory
                }
            };
            var area2 = new Area {
                AreaId = 2, AreaName = "Southern", Territories = new ChangeTrackingCollection <Territory> {
                    modifiedTerritory
                }
            };
            var area3 = new Area {
                AreaId = 3, AreaName = "Eastern", Territories = new ChangeTrackingCollection <Territory> {
                    deletedTerritory
                }
            };
            var area4 = new Area {
                AreaId = 4, AreaName = "Western", Territories = new ChangeTrackingCollection <Territory> {
                    addedExistingTerritory
                }
            };
            var addedNewTerritory = new Territory
            {
                TerritoryId          = "91360",
                TerritoryDescription = "SouthernCalifornia",
                Employees            = new ChangeTrackingCollection <Employee> {
                    employee
                },
                AreaId        = 5,
                TrackingState = TrackingState.Added // Must explicitly mark as added
            };

            unchangedTerritory.Area       = area1;
            unchangedTerritory.AreaId     = area1.AreaId;
            modifiedTerritory.Area        = area2;
            modifiedTerritory.AreaId      = area2.AreaId;
            deletedTerritory.Area         = area3;
            deletedTerritory.AreaId       = area3.AreaId;
            addedExistingTerritory.Area   = area4;
            addedExistingTerritory.AreaId = area4.AreaId;

            var changeTracker = new ChangeTrackingCollection <Employee>(employee);

            modifiedTerritory.TerritoryDescription = "xxx";                   // mod prop
            modifiedTerritory.AreaId = 6;                                     // mod FK prop
            employee.Territories.Remove(deletedTerritory);                    // should mark area deleted
            employee.Territories.Add(addedExistingTerritory);                 // should keep area unchanged
            employee.Territories.Add(addedNewTerritory);                      // should keep territory added
            addedExistingTerritory.Area.AreaName = "zzz";                     // should mark area modified

            var changes         = changeTracker.GetChanges();                 // should exclude unchanged territory
            var updatedEmployee = UpdateEmployeesWithTerritories(changes)[0]; // rel entities, db-gen vals

            // Act
            changeTracker.MergeChanges(updatedEmployee);

            // Assert
            Assert.Contains(unchangedTerritory, employee.Territories);                                       // Unchanged present
            Assert.Equal("zzz", addedExistingTerritory.Area.AreaName);                                       // Area name updated
            Assert.Equal("yyy", addedNewTerritory.Data);                                                     // Db-generated value set
            Assert.Equal(addedNewTerritory.AreaId, addedNewTerritory.Area.AreaId);                           // Added territory Area set
            Assert.Equal(modifiedTerritory.AreaId, modifiedTerritory.Area.AreaId);                           // Modified territory Area set
            Assert.Same(addedExistingTerritory, employee.Territories.Single(t => t.TerritoryId == "02116")); // Ref equality
            Assert.Same(addedNewTerritory, employee.Territories.Single(t => t.TerritoryId == "91360"));      // Ref equality
            Assert.Same(modifiedTerritory, employee.Territories.Single(t => t.TerritoryId == "01730"));      // Ref equality
            Assert.DoesNotContain(deletedTerritory, employee.Territories);                                   // Detail deleted
            ICollection cachedDeletes = ((ITrackingCollection)employee.Territories).CachedDeletes;

            Assert.Empty(cachedDeletes); // Cached deletes have been removed
        }
        public void MergeChanges_Should_Set_Unchanged_Customer_With_Modified_Setting()
        {
            // Arrange
            var database = new MockNorthwind();
            var order = database.Orders[0];
            var customer = order.Customer;
            customer.CustomerSetting = new CustomerSetting
            {
                CustomerId = customer.CustomerId,
                Customer = customer,
                Setting = "Setting1"
            };
            var changeTracker = new ChangeTrackingCollection<Order>(order);
            var setting = customer.CustomerSetting.Setting = "xxx";
            var origState = customer.CustomerSetting.TrackingState;
            var changes = changeTracker.GetChanges();
            var changedCustomer = changes[0].Customer;
            var updatedOrder = changes[0].Clone<Order>();
            updatedOrder.AcceptChanges();

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.Equal(setting, customer.CustomerSetting.Setting); // Changed customer setting is preserved
            Assert.Equal(TrackingState.Modified, origState); // Changed state is modified
            Assert.Equal(TrackingState.Unchanged, customer.TrackingState); // State set to unchanged
        }
예제 #39
0
        private static void ManyToManyRelation(HttpClient client)
        {
            Console.WriteLine("\nPress Enter to create a new employee existing territory");
            Console.ReadLine();

            // Get existing territories
            var territory1 = GetEntity <Territory, string>(client, "01581");
            var territory2 = GetEntity <Territory, string>(client, "01730");
            var territory3 = GetEntity <Territory, string>(client, "01833");

            // Create a new employee
            var employee = new Employee
            {
                LastName    = "Smith",
                FirstName   = "John",
                BirthDate   = DateTime.Parse("1979-12-09"),
                HireDate    = DateTime.Parse("2001-05-01"),
                City        = "Dallas",
                Country     = "USA",
                Territories = new ChangeTrackingCollection <Territory>
                {
                    territory1, territory2, territory3
                }
            };

            // Add to change tracker to mark as Added
            var employeeChangeTracker = new ChangeTrackingCollection <Employee>(true)
            {
                employee
            };

            // Insert employee and merge
            Employee updatedEmployee = CreateEntity(client, employee);

            employeeChangeTracker.MergeChanges(updatedEmployee);
            PrintEmployee(employee);

            Console.WriteLine("\nPress Enter to modify, add and remove territories");
            Console.ReadLine();

            // Modify territory, remove territory, add existing territory
            var territory4 = GetEntity <Territory, string>(client, "02116");

            employee.Territories[1].TerritoryDescription += " - Changed";
            employee.Territories.RemoveAt(2);
            employee.Territories.Add(territory4);

            // Update employee, then merge changes
            var changedEmployee = employeeChangeTracker.GetChanges().SingleOrDefault();

            updatedEmployee = UpdateEntity(client, changedEmployee);
            employeeChangeTracker.MergeChanges(updatedEmployee);
            PrintEmployee(employee);

            // Delete the order and customer
            Console.WriteLine("\nPress Enter to delete the employee without deleting territories");
            Console.ReadLine();

            // Delete order and verify
            DeleteEntity <Employee, int>(client, employee.EmployeeId);
            var employeeDeleted = VerifyEntityDeleted <Employee, int>(client, employee.EmployeeId);

            Console.WriteLine(employeeDeleted ?
                              "Employee was successfully deleted" :
                              "Employee was NOT deleted");
            var removedTerritory = GetEntity <Territory, string>(client, "01833");

            Console.WriteLine("Removed territory '01833' still exists: {0}",
                              removedTerritory != null);
        }
예제 #40
0
        private static void OneToOneRelation(HttpClient client)
        {
            Console.WriteLine("\nPress Enter to create a new customer");
            Console.ReadLine();

            // Create a new customer
            var customer = new Customer
            {
                CustomerId  = "ABCDE",
                CompanyName = "Acme Company",
                ContactName = "John Doe",
                City        = "Dallas",
                Country     = "USA"
            };

            // Add to change tracker to mark as Added
            var customerChangeTracker = new ChangeTrackingCollection <Customer>(true)
            {
                customer
            };

            // Insert customer and merge
            Customer updatedCustomer = CreateEntity(client, customer);

            customerChangeTracker.MergeChanges(updatedCustomer);
            PrintCustomer(customer);

            Console.WriteLine("\nPress Enter to add a new setting");
            Console.ReadLine();

            // Add a new customer setting
            // NOTE: To add a 1-1 property, you must manually mark it as Added.
            customer.CustomerSetting = new CustomerSetting
            {
                CustomerId    = customer.CustomerId,
                Setting       = " Test Setting",
                TrackingState = TrackingState.Added // Mark as added
            };

            // Update customer, then accept changes
            updatedCustomer = UpdateEntity(client, customer);
            Console.WriteLine("\tCustomer setting added: {0}",
                              updatedCustomer.CustomerSetting != null);
            customer.AcceptChanges();
            PrintCustomer(customer);

            // Add new customer setting
            Console.WriteLine("\nPress Enter to modify the setting");
            Console.ReadLine();

            // Modify customer setting
            var newSetting = customer.CustomerSetting.Setting += " - Changed";

            // Update customer, then accept changes
            updatedCustomer = UpdateEntity(client, customer);
            Console.WriteLine("\tCustomer setting modified: {0}",
                              updatedCustomer.CustomerSetting.Setting == newSetting);
            customer.AcceptChanges();
            PrintCustomer(customer);

            // Remove existing customer setting
            Console.WriteLine("\nPress Enter to remove the existing setting");
            Console.ReadLine();

            // Delete existing customer setting
            // NOTE: To remove a 1-1 property, you must manually mark it as Deleted.
            customer.CustomerSetting.TrackingState = TrackingState.Deleted;

            // Update customer, then set 1-1 property to null
            updatedCustomer = UpdateEntity(client, customer);
            Console.WriteLine("\tCustomer setting removed: {0}",
                              updatedCustomer.CustomerSetting == null);
            customer.CustomerSetting = null;
            PrintCustomer(customer);

            // Delete the customer
            Console.WriteLine("\nPress Enter to delete the customer");
            Console.ReadLine();
            DeleteEntity <Customer, string>(client, customer.CustomerId);

            // Verify order was deleted
            var deleted = VerifyEntityDeleted <Customer, string>(client, customer.CustomerId);

            Console.WriteLine(deleted ?
                              "Customer was successfully deleted" :
                              "Customer was NOT deleted");
        }
예제 #41
0
        static void Main(string[] args)
        {
            Console.WriteLine("Press Enter to start");
            Console.ReadLine();

            ICustomerService customerService = new ChannelFactory <ICustomerService>("customerService").CreateChannel();
            IOrderService    orderService    = new ChannelFactory <IOrderService>("orderService").CreateChannel();

            using ((IDisposable)customerService)
                using ((IDisposable)orderService)
                {
                    try
                    {
                        // Get customers
                        Console.WriteLine("Customers:");
                        IEnumerable <Customer> customers = customerService.GetCustomersAsync().Result;
                        if (customers == null)
                        {
                            return;
                        }
                        foreach (var c in customers)
                        {
                            PrintCustomer(c);
                        }

                        // Get orders for a customer
                        Console.WriteLine("\nGet customer orders {CustomerId}:");
                        string customerId = Console.ReadLine();
                        if (!customers.Any(c => string.Equals(c.CustomerId, customerId, StringComparison.OrdinalIgnoreCase)))
                        {
                            Console.WriteLine("Invalid customer id: {0}", customerId.ToUpper());
                            return;
                        }
                        IEnumerable <Order> orders = orderService.GetCustomerOrdersAsync(customerId).Result;
                        foreach (var o in orders)
                        {
                            PrintOrder(o);
                        }

                        // Get an order
                        Console.WriteLine("\nGet an order {OrderId}:");
                        int orderId = int.Parse(Console.ReadLine());
                        if (!orders.Any(o => o.OrderId == orderId))
                        {
                            Console.WriteLine("Invalid order id: {0}", orderId);
                            return;
                        }
                        Order order = orderService.GetOrderAsync(orderId).Result;
                        PrintOrderWithDetails(order);

                        // Create a new order
                        Console.WriteLine("\nPress Enter to create a new order for {0}",
                                          customerId.ToUpper());
                        Console.ReadLine();

                        var newOrder = new Order
                        {
                            CustomerId   = customerId,
                            OrderDate    = DateTime.Today,
                            ShippedDate  = DateTime.Today.AddDays(1),
                            OrderDetails = new ChangeTrackingCollection <OrderDetail>
                            {
                                new OrderDetail {
                                    ProductId = 1, Quantity = 5, UnitPrice = 10
                                },
                                new OrderDetail {
                                    ProductId = 2, Quantity = 10, UnitPrice = 20
                                },
                                new OrderDetail {
                                    ProductId = 4, Quantity = 40, UnitPrice = 40
                                }
                            }
                        };
                        var createdOrder = orderService.CreateOrderAsync(newOrder).Result;
                        PrintOrderWithDetails(createdOrder);

                        // Update the order
                        Console.WriteLine("\nPress Enter to update order details");
                        Console.ReadLine();

                        // Start change-tracking the order
                        var changeTracker = new ChangeTrackingCollection <Order>(createdOrder);

                        // Modify order details
                        createdOrder.OrderDetails[0].UnitPrice++;
                        createdOrder.OrderDetails.RemoveAt(1);
                        createdOrder.OrderDetails.Add(new OrderDetail
                        {
                            OrderId   = createdOrder.OrderId,
                            ProductId = 3,
                            Quantity  = 15,
                            UnitPrice = 30
                        });

                        // Submit changes
                        Order changedOrder = changeTracker.GetChanges().SingleOrDefault();
                        Order updatedOrder = orderService.UpdateOrderAsync(changedOrder).Result;

                        // Merge changes
                        changeTracker.MergeChanges(updatedOrder);
                        Console.WriteLine("Updated order:");
                        PrintOrderWithDetails(createdOrder);

                        // Delete the order
                        Console.WriteLine("\nPress Enter to delete the order");
                        Console.ReadLine();
                        bool deleted = orderService.DeleteOrderAsync(createdOrder.OrderId).Result;

                        // Verify order was deleted
                        Order deletedOrder = orderService.GetOrderAsync(createdOrder.OrderId).Result;
                        Console.WriteLine(deleted && deletedOrder == null
                        ? "Order was successfully deleted"
                        : "Order was not deleted");
                    }
                    catch (AggregateException aggEx)
                    {
                        var baseEx     = aggEx.Flatten().GetBaseException();
                        var innerExMsg = baseEx.InnerException != null ? "\r\n" + baseEx.InnerException.Message : "";
                        Console.WriteLine(baseEx.Message + innerExMsg);
                    }
                    finally
                    {
                        var channel = customerService as IClientChannel;
                        if (channel != null && channel.State == CommunicationState.Faulted)
                        {
                            channel.Abort();
                        }
                    }

                    // Keep console open
                    Console.WriteLine("Press any key to exit");
                    Console.ReadKey(true);
                }
        }
        public void MergeChanges_Should_Merge_Updates_For_Unchanged_Order_With_Changed_OrderDetails()
        {
            // Arrange
            var database = new MockNorthwind();
            var origOrder = database.Orders[0];
            var product = database.Products.Single(p => p.ProductId == 14);
            origOrder.OrderDetails.Add(new OrderDetail { ProductId = 14, OrderId = 10249, Quantity = 9, UnitPrice = 18.6000M, Product = product });
            var unchangedDetail = origOrder.OrderDetails[0];
            var modifiedDetail = origOrder.OrderDetails[1];
            var deletedDetail = origOrder.OrderDetails[3];
            var changeTracker = new ChangeTrackingCollection<Order>(origOrder);
            origOrder.OrderDetails[1].Product.ProductName = "xxx";
            origOrder.OrderDetails[2].Quantity++;
            origOrder.OrderDetails[2].ProductId = 1;
            var newUnitPrice = origOrder.OrderDetails[2].UnitPrice + 1;
            origOrder.OrderDetails.RemoveAt(3);
            var addedDetail = new OrderDetail {ProductId = 51, OrderId = 10249, Quantity = 40, UnitPrice = 42.4000M};
            origOrder.OrderDetails.Add(addedDetail);

            var changes = changeTracker.GetChanges();
            var updatedOrder = UpdateOrdersWithDetails(database, changes)[0];

            // Act
            changeTracker.MergeChanges(updatedOrder);

            // Assert
            Assert.Contains(unchangedDetail, origOrder.OrderDetails); // Unchanged present
            Assert.Equal("xxx", origOrder.OrderDetails[1].Product.ProductName); // Prod name updated
            Assert.Equal(updatedOrder.OrderDetails[1].ProductId, origOrder.OrderDetails[2].Product.ProductId); // Changed Product set
            Assert.Equal(newUnitPrice, origOrder.OrderDetails[2].UnitPrice); // Db-generated value set
            Assert.Equal(updatedOrder.OrderDetails[2].Product.ProductId, origOrder.OrderDetails[3].Product.ProductId); // Added detail Product set
            Assert.True(origOrder.OrderDetails.All(d => d.TrackingState == TrackingState.Unchanged)); // Details unchanged
            Assert.Same(addedDetail, origOrder.OrderDetails.Single(d => d.ProductId == 51)); // Ref equality
            Assert.Same(modifiedDetail, origOrder.OrderDetails.Single(d => d.ProductId == 42)); // Ref equality
            Assert.DoesNotContain(deletedDetail, origOrder.OrderDetails); // Detail deleted
            ICollection cachedDeletes = ((ITrackingCollection)origOrder.OrderDetails).GetChanges(true);
            Assert.Empty(cachedDeletes); // Cached deletes have been removed
        }
예제 #43
0
        private static void ManyToOneRelation(HttpClient client)
        {
            Console.WriteLine("\nPress Enter to create a new order for an existing customer");
            Console.ReadLine();

            // Create a new order for an existing customer
            var order = new Order {
                CustomerId = "ALFKI", OrderDate = DateTime.Today, ShippedDate = DateTime.Today.AddDays(1)
            };

            // Add to change tracker to mark as Added
            var orderChangeTracker = new ChangeTrackingCollection <Order>(true)
            {
                order
            };

            // Insert order and merge
            Order updatedOrder = CreateEntity(client, order);

            orderChangeTracker.MergeChanges(updatedOrder);
            PrintOrder(order);

            Console.WriteLine("\nPress Enter to add a new customer to the order");
            Console.ReadLine();

            // Create a new customer
            // NOTE: Marking customer as Added will create a NEW customer
            const string customerId = "WXYZ";
            var          customer   = new Customer
            {
                CustomerId    = customerId,
                CompanyName   = "Widget Company",
                ContactName   = "Jane Doe",
                City          = "New York",
                Country       = "USA",
                TrackingState = TrackingState.Added // Mark as added
            };

            order.Customer   = customer;   // new customer will be created
            order.CustomerId = customerId; // cust will be assigned to order

            // Update order, then accept changes
            updatedOrder = UpdateEntity(client, order);
            Console.WriteLine("\tOrder's customer added: {0}", updatedOrder.Customer != null);
            order.AcceptChanges();
            PrintOrder(order);
            PrintCustomer(order.Customer);

            Console.WriteLine("\nPress Enter to modify order's customer");
            Console.ReadLine();

            // Modify order customer
            var newCompanyName = order.Customer.CompanyName += " - Changed";

            // Update order, then accept changes
            UpdateEntity(client, order);
            var updatedCustomer = GetEntity <Customer, string>(client, customerId);

            Console.WriteLine("\tOrder customer's name modified: {0}",
                              updatedCustomer.CompanyName == newCompanyName);
            customer.AcceptChanges();
            PrintCustomer(customer);

            // Delete the order and customer
            Console.WriteLine("\nPress Enter to delete the order and customer");
            Console.ReadLine();

            // Delete order and verify
            DeleteEntity <Order, int>(client, order.OrderId);
            var orderDeleted = VerifyEntityDeleted <Order, int>(client, order.OrderId);

            Console.WriteLine(orderDeleted ?
                              "Order was successfully deleted" :
                              "Order was NOT deleted");

            // Delete order and verify
            DeleteEntity <Customer, string>(client, customer.CustomerId);
            var customerDeleted = VerifyEntityDeleted <Customer, string>(client, customer.CustomerId);

            Console.WriteLine(customerDeleted ?
                              "Customer was successfully deleted" :
                              "Customer was NOT deleted");
        }
        public void Updated_Parent_With_Children_Should_Merge_Unchanged_Children()
        {
            // Arrange
            var database = new MockNorthwind();

            // Get order, fix up details, clone
            var origOrder = database.Orders[0];
            foreach (var detail in origOrder.OrderDetails)
                detail.Order = origOrder;
            var updatedOrder = origOrder.Clone<Order>();

            // Add unchanged detail to orig order
            origOrder.OrderDetails.Add(new OrderDetail
            {
                ProductId = 1,
                Product = database.Products[0],
                Quantity = 10,
                UnitPrice = 20M,
                OrderId = origOrder.OrderId,
                Order = origOrder
            });

            // Replicate changes in updated order
            updatedOrder.OrderDetails[0].UnitPrice++;
            updatedOrder.OrderDetails.RemoveAt(1);

            // Remove 3rd detail so it can be re-added
            var addedDetail = origOrder.OrderDetails[2];
            origOrder.OrderDetails.Remove(addedDetail);

            // Clone orig order and start tracking
            var changeTracker = new ChangeTrackingCollection<Order>(origOrder);

            // Set state on orig order details
            origOrder.OrderDetails[0].UnitPrice++;
            origOrder.OrderDetails.Add(addedDetail);
            origOrder.OrderDetails.RemoveAt(1);

            // Act

            // Merge updates into orig order
#pragma warning disable 618
            changeTracker.MergeChanges(ref origOrder, updatedOrder);
#pragma warning restore 618

            // Assert
            // Orig reference pointed to updated
            Assert.True(ReferenceEquals(origOrder, updatedOrder));

            // Tracking states set to unchanged
            Assert.Equal(TrackingState.Unchanged, origOrder.OrderDetails[0].TrackingState);
            Assert.Equal(TrackingState.Unchanged, origOrder.OrderDetails[1].TrackingState);
            Assert.Equal(TrackingState.Unchanged, origOrder.OrderDetails[2].TrackingState);

            // Modified properties set to null
            Assert.Null(origOrder.OrderDetails[0].ModifiedProperties);
            Assert.Null(origOrder.OrderDetails[1].ModifiedProperties);
            Assert.Null(origOrder.OrderDetails[2].ModifiedProperties);

            // Detail orders fixed up
            Assert.True(ReferenceEquals(origOrder, origOrder.OrderDetails[0].Order));
            Assert.True(ReferenceEquals(origOrder, origOrder.OrderDetails[1].Order));
            Assert.True(ReferenceEquals(origOrder, origOrder.OrderDetails[2].Order));
        }