Пример #1
0
 public CouponUsageRecordHandler(IPromotionUsageService usageService, IPromotionUsageSearchService promotionUsageSearchService, IPromotionService promotionService)
 {
     _usageService = usageService;
     _promotionUsageSearchService = promotionUsageSearchService;
     EqualityComparer             = AnonymousComparer.Create((PromotionUsage x) => string.Join(":", x.PromotionId, x.CouponCode, x.ObjectId));
     _promotionService            = promotionService;
 }
Пример #2
0
        public void OnNext(OrderChangeEvent value)
        {
            var origStockOutOperations     = new ShipmentItem[] { };
            var modifiedStockOutOperations = new ShipmentItem[] { };

            if (value.OrigOrder != null)
            {
                origStockOutOperations = value.OrigOrder.Shipments.SelectMany(x => x.Items).ToArray();
            }
            if (value.ModifiedOrder != null)
            {
                modifiedStockOutOperations = value.ModifiedOrder.Shipments.SelectMany(x => x.Items).ToArray();
            }

            var originalPositions = new ObservableCollection <KeyValuePair <string, int> >(origStockOutOperations.GroupBy(x => x.LineItem.ProductId).Select(x => new KeyValuePair <string, int>(x.Key, x.Sum(y => y.Quantity))));
            var modifiedPositions = new ObservableCollection <KeyValuePair <string, int> >(modifiedStockOutOperations.GroupBy(x => x.LineItem.ProductId).Select(x => new KeyValuePair <string, int>(x.Key, x.Sum(y => y.Quantity))));

            var changedInventoryInfos = new List <InventoryInfo>();

            var inventoryInfos = _inventoryService.GetProductsInventoryInfos(originalPositions.Select(x => x.Key).Concat(modifiedPositions.Select(x => x.Key)).Distinct().ToArray());

            var comparer = AnonymousComparer.Create((KeyValuePair <string, int> x) => x.Key);

            modifiedPositions.CompareTo(originalPositions, comparer, (state, source, target) => { AdjustInventory(inventoryInfos, changedInventoryInfos, state, source, target); });

            if (changedInventoryInfos.Any())
            {
                _inventoryService.UpsertInventories(changedInventoryInfos);
            }
        }
Пример #3
0
        /// <summary>
        /// Patch changes
        /// </summary>
        /// <param name="source"></param>
        /// <param name="target"></param>
        public static void Patch(this dataModel.Property source, dataModel.Property target)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            var patchInjectionPolicy = new PatchInjection <dataModel.Property>(x => x.PropertyValueType, x => x.IsEnum, x => x.IsMultiValue, x => x.IsLocaleDependant,
                                                                               x => x.IsRequired, x => x.TargetType, x => x.Name);

            target.InjectFrom(patchInjectionPolicy, source);


            //Attributes patch
            if (!source.PropertyAttributes.IsNullCollection())
            {
                var attributeComparer = AnonymousComparer.Create((dataModel.PropertyAttribute x) => x.IsTransient() ?  x.PropertyAttributeName : x.Id);
                source.PropertyAttributes.Patch(target.PropertyAttributes, attributeComparer, (sourceAsset, targetAsset) => sourceAsset.Patch(targetAsset));
            }
            //Property dict values
            if (!source.DictionaryValues.IsNullCollection())
            {
                source.DictionaryValues.Patch(target.DictionaryValues, (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue));
            }
        }
Пример #4
0
        protected virtual CouponUsageRecordJobArgument GetJobArgumentsForCouponUsageRecord(CustomerOrder order)
        {
            var           objectId      = order.Id;
            IHasDiscounts hasDiscounts  = order;
            var           customerId    = order.CustomerId;
            var           customerName  = order.CustomerName;
            var           usageComparer = AnonymousComparer.Create((PromotionUsage x) => string.Join(":", x.PromotionId, x.CouponCode, x.ObjectId));
            var           result        = hasDiscounts.GetFlatObjectsListWithInterface <IHasDiscounts>()
                                          .Where(x => x.Discounts != null)
                                          .SelectMany(x => x.Discounts)
                                          .Where(x => !string.IsNullOrEmpty(x.Coupon))
                                          .Select(x => new PromotionUsage
            {
                CouponCode  = x.Coupon,
                PromotionId = x.PromotionId,
                ObjectId    = objectId,
                ObjectType  = hasDiscounts.GetType().Name,
                UserId      = customerId,
                UserName    = customerName
            })
                                          .Distinct(usageComparer);

            return(new CouponUsageRecordJobArgument()
            {
                OrderId = objectId, PromotionUsages = result.ToArray()
            });
        }
Пример #5
0
        public override void Patch(OperationEntity operation)
        {
            base.Patch(operation);

            var target = operation as PaymentInEntity;

            if (target == null)
            {
                throw new ArgumentException(@"operation argument must be of type PaymentInEntity", nameof(operation));
            }

            target.Amount                = Amount;
            target.Price                 = Price;
            target.PriceWithTax          = PriceWithTax;
            target.DiscountAmount        = DiscountAmount;
            target.DiscountAmountWithTax = DiscountAmountWithTax;
            target.TaxType               = TaxType;
            target.TaxPercentRate        = TaxPercentRate;
            target.TaxTotal              = TaxTotal;
            target.Total                 = Total;
            target.TotalWithTax          = TotalWithTax;

            target.CustomerId       = CustomerId;
            target.CustomerName     = CustomerName;
            target.OrganizationId   = OrganizationId;
            target.OrganizationName = OrganizationName;
            target.GatewayCode      = GatewayCode;
            target.Purpose          = Purpose;
            target.OuterId          = OuterId;
            target.Status           = Status;
            target.AuthorizedDate   = AuthorizedDate;
            target.CapturedDate     = CapturedDate;
            target.VoidedDate       = VoidedDate;
            target.IsCancelled      = IsCancelled;
            target.CancelledDate    = CancelledDate;
            target.CancelReason     = CancelReason;
            target.Sum = Sum;

            if (!Addresses.IsNullCollection())
            {
                Addresses.Patch(target.Addresses, (sourceAddress, targetAddress) => sourceAddress.Patch(targetAddress));
            }

            if (!TaxDetails.IsNullCollection())
            {
                var taxDetailComparer = AnonymousComparer.Create((TaxDetailEntity x) => x.Name);
                TaxDetails.Patch(target.TaxDetails, taxDetailComparer, (sourceTaxDetail, targetTaxDetail) => sourceTaxDetail.Patch(targetTaxDetail));
            }

            if (!Discounts.IsNullCollection())
            {
                var discountComparer = AnonymousComparer.Create((DiscountEntity x) => x.PromotionId);
                Discounts.Patch(target.Discounts, discountComparer, (sourceDiscount, targetDiscount) => sourceDiscount.Patch(targetDiscount));
            }

            if (!Transactions.IsNullCollection())
            {
                Transactions.Patch(target.Transactions, (sourceTran, targetTran) => sourceTran.Patch(targetTran));
            }
        }
Пример #6
0
        public virtual void Patch(DynamicContentPublishingGroupEntity target)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            target.Description = Description;
            target.Name        = Name;
            target.Priority    = Priority;
            target.IsActive    = IsActive;
            target.StoreId     = StoreId;
            target.StartDate   = StartDate;
            target.EndDate     = EndDate;
            target.PredicateVisualTreeSerialized = PredicateVisualTreeSerialized;

            if (!ContentItems.IsNullCollection())
            {
                var itemComparer = AnonymousComparer.Create((PublishingGroupContentItemEntity x) => x.DynamicContentItemId);
                ContentItems.Patch(target.ContentItems, itemComparer, (sourceProperty, targetProperty) => { sourceProperty.Patch(targetProperty); });
            }

            if (!ContentPlaces.IsNullCollection())
            {
                var itemComparer = AnonymousComparer.Create((PublishingGroupContentPlaceEntity x) => x.DynamicContentPlaceId);
                ContentPlaces.Patch(target.ContentPlaces, itemComparer, (sourceProperty, targetProperty) => { sourceProperty.Patch(targetProperty); });
            }
        }
Пример #7
0
        public void Patch(QuoteItemEntity target)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            var _ = this;

            target.ListPrice  = _.ListPrice;
            target.SalePrice  = _.SalePrice;
            target.TaxType    = _.TaxType;
            target.ImageUrl   = _.ImageUrl;
            target.ProductId  = _.ProductId;
            target.Comment    = _.Comment;
            target.CatalogId  = _.CatalogId;
            target.CategoryId = _.CategoryId;
            target.Currency   = _.Currency;
            target.Name       = _.Name;
            target.Sku        = _.Sku;

            if (!ProposalPrices.IsNullCollection())
            {
                var tierPriceComparer = AnonymousComparer.Create((TierPriceEntity x) => x.Quantity + "-" + x.Price);
                ProposalPrices.Patch(target.ProposalPrices, tierPriceComparer, (sourceTierPrice, targetTierPrice) => { });
            }
        }
        protected async Task <Member[]> SearchMembersByIdAndOuterIdAsync(string[] internalIds, string[] outerIds, string[] memberTypes, bool deepSearch = false)
        {
            var criteriaById = new ExtendedMembersSearchCriteria()
            {
                ObjectIds   = internalIds,
                MemberTypes = memberTypes,
                DeepSearch  = deepSearch,
                Skip        = 0,
                Take        = ModuleConstants.Settings.PageSize
            };

            var membersById = internalIds.IsNullOrEmpty() ? Array.Empty <Member>() : (await _memberSearchService.SearchMembersAsync(criteriaById)).Results;

            var criteriaByOuterId = new ExtendedMembersSearchCriteria()
            {
                OuterIds    = outerIds,
                MemberTypes = memberTypes,
                DeepSearch  = deepSearch,
                Skip        = 0,
                Take        = ModuleConstants.Settings.PageSize
            };

            var membersByOuterId = outerIds.IsNullOrEmpty() ? Array.Empty <Member>() : (await _memberSearchService.SearchMembersAsync(criteriaByOuterId)).Results;

            var existedMembers = membersById.Union(membersByOuterId
                                                   , AnonymousComparer.Create <Member>((x, y) => x.Id == y.Id, x => x.Id.GetHashCode())).ToArray();

            return(existedMembers);
        }
Пример #9
0
        public void TestMaxByFuncTSourceTKeyIComparableTKey()
        {
            Person taro = new Person {
                Name = "Taro", Age = 28
            };
            Person jiro = new Person {
                Name = "Jiro", Age = 27
            };
            Person saburo = new Person {
                Name = "Saburo", Age = 26
            };
            Person anotherSaburo = new Person {
                Name = "Saburo", Age = 26
            };
            IComparer <string> comparer = AnonymousComparer.Create((string lhs, string rhs) => lhs.Length - rhs.Length);

            {
                IList <Person> maxNameLengthPersons = new [] { taro, jiro, saburo }.MaxBy(it => it.Name, comparer);
                Assert.True(maxNameLengthPersons.SequenceEqual(new [] { saburo }));
            }

            {
                IList <Person> maxNameLengthPersons = new [] { taro, jiro, saburo, anotherSaburo }.MaxBy(it => it.Name, comparer);
                Assert.True(maxNameLengthPersons.SequenceEqual(new [] { saburo, anotherSaburo }));
            }

            {
                Assert.Catch <InvalidOperationException> (() => {
                    new Person[] { }.MaxBy(it => it.Name, comparer);
                });
            }
        }
Пример #10
0
        public virtual void Patch(PropertyEntity target)
        {
            target.PropertyValueType = PropertyValueType;
            target.IsEnum            = IsEnum;
            target.IsMultiValue      = IsMultiValue;
            target.IsLocaleDependant = IsLocaleDependant;
            target.IsRequired        = IsRequired;
            target.TargetType        = TargetType;
            target.Name = Name;

            target.CatalogId  = CatalogId;
            target.CategoryId = CategoryId;

            if (!PropertyAttributes.IsNullCollection())
            {
                var attributeComparer = AnonymousComparer.Create((PropertyAttributeEntity x) => x.IsTransient() ? x.PropertyAttributeName : x.Id);
                PropertyAttributes.Patch(target.PropertyAttributes, attributeComparer, (sourceAsset, targetAsset) => sourceAsset.Patch(targetAsset));
            }
            if (!DictionaryItems.IsNullCollection())
            {
                var dictItemComparer = AnonymousComparer.Create((PropertyDictionaryItemEntity x) => $"{x.Alias}-${x.PropertyId}");
                DictionaryItems.Patch(target.DictionaryItems, dictItemComparer, (sourceDictItem, targetDictItem) => sourceDictItem.Patch(targetDictItem));
            }
            if (!DisplayNames.IsNullCollection())
            {
                var displayNamesComparer = AnonymousComparer.Create((PropertyDisplayNameEntity x) => $"{x.Name}-{x.Locale}");
                DisplayNames.Patch(target.DisplayNames, displayNamesComparer, (sourceDisplayName, targetDisplayName) => sourceDisplayName.Patch(targetDisplayName));
            }

            if (!ValidationRules.IsNullCollection())
            {
                ValidationRules.Patch(target.ValidationRules, (sourceRule, targetRule) => sourceRule.Patch(targetRule));
            }
        }
Пример #11
0
        /// <summary>
        /// Patch CatalogBase type
        /// </summary>
        /// <param name="source"></param>
        /// <param name="target"></param>
        public static void Patch(this LineItemEntity source, LineItemEntity target)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }


            var patchInjectionPolicy = new PatchInjection <LineItemEntity>(x => x.BasePrice, x => x.Price,
                                                                           x => x.Quantity, x => x.DiscountAmount, x => x.Tax, x => x.Height, x => x.Length,
                                                                           x => x.Width, x => x.MeasureUnit, x => x.WeightUnit, x => x.Weight, x => x.TaxType, x => x.IsCancelled, x => x.CancelledDate, x => x.CancelReason);

            target.InjectFrom(patchInjectionPolicy, source);


            if (!source.Discounts.IsNullCollection())
            {
                source.Discounts.Patch(target.Discounts, new DiscountComparer(), (sourceDiscount, targetDiscount) => sourceDiscount.Patch(targetDiscount));
            }

            if (!source.TaxDetails.IsNullCollection())
            {
                var taxDetailComparer = AnonymousComparer.Create((TaxDetailEntity x) => x.Name);
                source.TaxDetails.Patch(target.TaxDetails, taxDetailComparer, (sourceTaxDetail, targetTaxDetail) => sourceTaxDetail.Patch(targetTaxDetail));
            }
        }
Пример #12
0
        /// <summary>
        /// Patch CatalogBase type
        /// </summary>
        /// <param name="source"></param>
        /// <param name="target"></param>
        public static void Patch(this ShipmentEntity source, ShipmentEntity target)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            var patchInjection = new PatchInjection <ShipmentEntity>(x => x.ShipmentMethodCode, x => x.Total,
                                                                     x => x.ShippingPrice, x => x.DiscountTotal, x => x.TaxTotal,
                                                                     x => x.TaxIncluded, x => x.Currency,
                                                                     x => x.WeightUnit, x => x.WeightValue,
                                                                     x => x.DimensionHeight, x => x.DimensionLength, x => x.DimensionUnit,
                                                                     x => x.DimensionWidth, x => x.TaxType);

            target.InjectFrom(patchInjection, source);


            if (!source.Addresses.IsNullCollection())
            {
                source.Addresses.Patch(target.Addresses, new AddressComparer(), (sourceAddress, targetAddress) => sourceAddress.Patch(targetAddress));
            }
            if (source.Items != null)
            {
                source.Items.Patch(target.Items, (sourceItem, targetItem) => sourceItem.Patch(targetItem));
            }
            if (!source.TaxDetails.IsNullCollection())
            {
                var taxDetailComparer = AnonymousComparer.Create((TaxDetailEntity x) => x.Name);
                source.TaxDetails.Patch(target.TaxDetails, taxDetailComparer, (sourceTaxDetail, targetTaxDetail) => sourceTaxDetail.Patch(targetTaxDetail));
            }
            if (!source.Discounts.IsNullCollection())
            {
                source.Discounts.Patch(target.Discounts, new DiscountComparer(), (sourceDiscount, targetDiscount) => sourceDiscount.Patch(targetDiscount));
            }
        }
        /// <summary>
        /// Patch changes
        /// </summary>
        /// <param name="source"></param>
        /// <param name="target"></param>
        public static void Patch(this dataModel.Organization source, dataModel.Organization target)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }
            var patchInjection = new PatchInjection <dataModel.Organization>(x => x.Name, x => x.Description,
                                                                             x => x.OwnerId, x => x.OrgType,
                                                                             x => x.BusinessCategory);

            target.InjectFrom(patchInjection, source);

            if (!source.Phones.IsNullCollection())
            {
                var phoneComparer = AnonymousComparer.Create((dataModel.Phone x) => x.Number);
                source.Phones.Patch(target.Phones, phoneComparer, (sourcePhone, targetPhone) => targetPhone.Number = sourcePhone.Number);
            }
            if (!source.Emails.IsNullCollection())
            {
                var addressComparer = AnonymousComparer.Create((dataModel.Email x) => x.Address);
                source.Emails.Patch(target.Emails, addressComparer, (sourceEmail, targetEmail) => targetEmail.Address = sourceEmail.Address);
            }
            if (!source.Addresses.IsNullCollection())
            {
                source.Addresses.Patch(target.Addresses, new AddressComparer(), (sourceAddress, targetAddress) => sourceAddress.Patch(targetAddress));
            }
            if (!source.Notes.IsNullCollection())
            {
                var noteComparer = AnonymousComparer.Create((dataModel.Note x) => x.Id);
                source.Notes.Patch(target.Notes, noteComparer, (sourceNote, targetNote) => sourceNote.Patch(targetNote));
            }
        }
Пример #14
0
        public async Task SaveChangesAsync(IHasAssociations[] owners)
        {
            var changedEntities = new List <AssociationEntity>();

            foreach (var owner in owners)
            {
                if (owner.Associations != null)
                {
                    var dbAssociations = owner.Associations.Select(x => AbstractTypeFactory <AssociationEntity> .TryCreateInstance().FromModel(x)).ToArray();
                    foreach (var dbAssociation in dbAssociations)
                    {
                        dbAssociation.ItemId = owner.Id;
                    }
                    changedEntities.AddRange(dbAssociations);
                }
            }

            using (var repository = _repositoryFactory())
            {
                //Optimize performance and CPU usage
                repository.DisableChangesTracking();

                var itemIds       = owners.Where(x => x.Id != null).Select(x => x.Id).ToArray();
                var existEntities = await repository.Associations.Where(x => itemIds.Contains(x.ItemId)).ToArrayAsync();

                var target = new { Associations = new ObservableCollection <AssociationEntity>(existEntities) };
                var source = new { Associations = new ObservableCollection <AssociationEntity>(changedEntities) };

                //changeTracker.Attach(target);
                var associationComparer = AnonymousComparer.Create((AssociationEntity x) => x.ItemId + ":" + x.AssociationType + ":" + x.AssociatedItemId + ":" + x.AssociatedCategoryId);
                source.Associations.Patch(target.Associations, associationComparer, (sourceAssociation, targetAssociation) => sourceAssociation.Patch(targetAssociation));

                await repository.UnitOfWork.CommitAsync();
            }
        }
Пример #15
0
        public DynamicProperty[] SaveProperties(DynamicProperty[] properties)
        {
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }

            using (var repository = _repositoryFactory())
                using (var changeTracker = GetChangeTracker(repository))
                {
                    var sourceProperties = properties.Select(x => x.ToEntity()).ToList();
                    var targetProperties = repository.GetDynamicPropertiesForTypes(properties.Select(x => x.ObjectType).Distinct().ToArray()).ToList();
                    var comparer         = AnonymousComparer.Create((DynamicPropertyEntity x) => $"{x.Id?.ToLowerInvariant() ?? x.Name.ToLowerInvariant()}:{x.ObjectType.ToLowerInvariant()}");
                    sourceProperties.CompareTo(targetProperties, comparer, (state, source, target) =>
                    {
                        if (state == EntryState.Modified)
                        {
                            changeTracker.Attach(target);
                            source.Patch(target);
                        }
                        else if (state == EntryState.Added)
                        {
                            repository.Add(source);
                        }
                    });
                    repository.UnitOfWork.Commit();

                    var result = repository.GetDynamicPropertiesByIds(sourceProperties.Select(p => p.Id).ToArray())
                                 .Select(p => p.ToModel())
                                 .ToArray();
                    return(result);
                }
        }
Пример #16
0
        public void TestDistinctUntileChangedKeyselectorComparer()
        {
            IEqualityComparer <Point> comparer = AnonymousComparer.Create <Point> ((lhs, rhs) => lhs == rhs, it => it.X ^ it.Y);

            Assert.True(new [] {
                new { value = 1, point = new Point(0, 0) },
                new { value = 2, point = new Point(0, 1) },
                new { value = 3, point = new Point(1, 1) },
                new { value = 4, point = new Point(1, 2) },
            }.DistinctUntilChanged(it => it.point, comparer).SequenceEqual(new [] {
                new { value = 1, point = new Point(0, 0) },
                new { value = 2, point = new Point(0, 1) },
                new { value = 3, point = new Point(1, 1) },
                new { value = 4, point = new Point(1, 2) },
            }));

            Assert.True(new [] {
                new { value = 1, point = new Point(0, 0) },
                new { value = 2, point = new Point(0, 1) },
                new { value = 3, point = new Point(1, 1) },
                new { value = 4, point = new Point(1, 1) },
                new { value = 5, point = new Point(1, 1) },
                new { value = 6, point = new Point(1, 2) },
            }.DistinctUntilChanged(it => it.point, comparer).SequenceEqual(new [] {
                new { value = 1, point = new Point(0, 0) },
                new { value = 2, point = new Point(0, 1) },
                new { value = 3, point = new Point(1, 1) },
                new { value = 6, point = new Point(1, 2) },
            }));
        }
        public virtual void Patch(DynamicContentPublishingGroupEntity target)
        {
            if (target == null)
            {
                throw new NullReferenceException(nameof(target));
            }

            target.Description                   = this.Description;
            target.Name                          = this.Name;
            target.Priority                      = this.Priority;
            target.IsActive                      = this.IsActive;
            target.StoreId                       = this.StoreId;
            target.StartDate                     = this.StartDate;
            target.EndDate                       = this.EndDate;
            target.ConditionExpression           = this.ConditionExpression;
            target.PredicateVisualTreeSerialized = this.PredicateVisualTreeSerialized;

            if (!this.ContentItems.IsNullCollection())
            {
                var itemComparer = AnonymousComparer.Create((PublishingGroupContentItemEntity x) => x.DynamicContentItemId);
                this.ContentItems.Patch(target.ContentItems, itemComparer, (sourceProperty, targetProperty) => { });
            }

            if (!this.ContentPlaces.IsNullCollection())
            {
                var itemComparer = AnonymousComparer.Create((PublishingGroupContentPlaceEntity x) => x.DynamicContentPlaceId);
                this.ContentPlaces.Patch(target.ContentPlaces, itemComparer, (sourceProperty, targetProperty) => { });
            }
        }
        /// <summary>
        /// Saves collections of associations for given objects. Replaces all collection - adds new, updates existing and deletes associations that are not presented in the saved objects associations.
        /// </summary>
        /// <param name="owners"></param>
        /// <returns></returns>
        public async Task SaveChangesAsync(IHasAssociations[] owners)
        {
            var changedEntities = new List <AssociationEntity>();

            foreach (var owner in owners)
            {
                if (owner.Associations != null)
                {
                    var dbAssociations = owner.Associations.Select(x => AbstractTypeFactory <AssociationEntity> .TryCreateInstance().FromModel(x)).ToArray();
                    foreach (var dbAssociation in dbAssociations)
                    {
                        dbAssociation.ItemId = owner.Id;
                    }

                    changedEntities.AddRange(dbAssociations);
                }
            }

            using (var repository = _repositoryFactory())
            {
                var itemIds = owners.Where(x => x.Id != null).Select(x => x.Id).ToArray();

                var associationComparer = AnonymousComparer.Create((AssociationEntity x) => x.ItemId + ":" + x.AssociationType + ":" + x.AssociatedItemId + ":" + x.AssociatedCategoryId);

                var existingEntities = new ObservableCollection <AssociationEntity>(repository.Associations.Where(x => itemIds.Contains(x.ItemId)).ToList());

                existingEntities.ObserveCollection(x => repository.Add(x), x => repository.Remove(x));
                changedEntities.Patch(existingEntities, associationComparer, (sourceAssociation, targetAssociation) => sourceAssociation.Patch(targetAssociation));

                await repository.UnitOfWork.CommitAsync();
            }
        }
Пример #19
0
        public void AdjustInventoryHandler_GetProductInventoryChanges_ForOrderChanges(GenericChangedEntry <CustomerOrder> orderChangedEntry,
                                                                                      IEnumerable <AdjustInventoryOrderChangedEventHandler.ProductInventoryChange> expectedChanges)
        {
            // Arrange
            var inventoryServiceMock = new Mock <IInventoryService>();
            var settingsManagerMock  = new Mock <ISettingsManager>();

            var storeServiceMock = new Mock <IStoreService>();

            storeServiceMock.Setup(x => x.GetById(TestStoreId))
            .Returns(new Store {
                MainFulfillmentCenterId = TestFulfillmentCenterId
            });

            var targetHandler = new AdjustInventoryOrderChangedEventHandler(inventoryServiceMock.Object,
                                                                            storeServiceMock.Object, settingsManagerMock.Object);

            // Act
            var actualChanges = targetHandler.GetProductInventoryChangesFor(orderChangedEntry);

            // Assert
            var equalityComparer = AnonymousComparer.Create((AdjustInventoryOrderChangedEventHandler.ProductInventoryChange x) => $"{x.FulfillmentCenterId} {x.ProductId} {x.QuantityDelta}");

            Assert.Equal(expectedChanges, actualChanges, equalityComparer);
        }
Пример #20
0
        public virtual void Patch(PropertyEntity target)
        {
            target.PropertyValueType = this.PropertyValueType;
            target.IsEnum            = this.IsEnum;
            target.IsMultiValue      = this.IsMultiValue;
            target.IsLocaleDependant = this.IsLocaleDependant;
            target.IsRequired        = this.IsRequired;
            target.TargetType        = this.TargetType;
            target.Name = this.Name;

            if (!this.PropertyAttributes.IsNullCollection())
            {
                var attributeComparer = AnonymousComparer.Create((PropertyAttributeEntity x) => x.IsTransient() ? x.PropertyAttributeName : x.Id);
                this.PropertyAttributes.Patch(target.PropertyAttributes, attributeComparer, (sourceAsset, targetAsset) => sourceAsset.Patch(targetAsset));
            }
            if (!this.DictionaryValues.IsNullCollection())
            {
                this.DictionaryValues.Patch(target.DictionaryValues, (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue));
            }
            if (!this.DisplayNames.IsNullCollection())
            {
                var displayNamesComparer = AnonymousComparer.Create((PropertyDisplayNameEntity x) => $"{x.Name}-{x.Locale}");
                this.DisplayNames.Patch(target.DisplayNames, displayNamesComparer, (sourceDisplayName, targetDisplayName) => sourceDisplayName.Patch(targetDisplayName));
            }

            if (!this.ValidationRules.IsNullCollection())
            {
                this.ValidationRules.Patch(target.ValidationRules, (sourceRule, targetRule) => sourceRule.Patch(targetRule));
            }
        }
        public static void Patch(this ApplicationUserExtended user, ApplicationUser dbUser)
        {
            dbUser.Id                   = user.Id ?? dbUser.Id;
            dbUser.LockoutEnabled       = user.LockoutEnabled;
            dbUser.LockoutEndDateUtc    = user.LockoutEndDateUtc;
            dbUser.PasswordHash         = user.PasswordHash ?? dbUser.PasswordHash;
            dbUser.PhoneNumber          = user.PhoneNumber ?? dbUser.PhoneNumber;
            dbUser.PhoneNumberConfirmed = user.PhoneNumberConfirmed;
            dbUser.SecurityStamp        = user.SecurityStamp ?? dbUser.SecurityStamp;
            dbUser.TwoFactorEnabled     = user.TwoFactorEnabled;
            dbUser.UserName             = user.UserName ?? dbUser.UserName;
            dbUser.AccessFailedCount    = user.AccessFailedCount;
            dbUser.EmailConfirmed       = user.EmailConfirmed;
            dbUser.Email                = user.Email ?? dbUser.Email;

            // Copy logins
            if (user.Logins != null)
            {
                var changedLogins = user.Logins.Select(x => new IdentityUserLogin
                {
                    LoginProvider = x.LoginProvider,
                    ProviderKey   = x.ProviderKey,
                    UserId        = dbUser.Id
                }).ToList();

                var comparer = AnonymousComparer.Create((IdentityUserLogin x) => x.LoginProvider);
                changedLogins.Patch(dbUser.Logins, comparer, (sourceItem, targetItem) => { sourceItem.ProviderKey = targetItem.ProviderKey; });
            }
        }
Пример #22
0
        public void SaveSettings(SettingEntry[] settings)
        {
            if (settings != null && settings.Any())
            {
                var settingKeys = settings.Select(x => String.Join("-", x.Name, x.ObjectType, x.Id)).Distinct().ToArray();


                using (var changeTracker = new ObservableChangeTracker())
                {
                    var alreadyExistSettings = _baseUnitOfWork.BaseWorkArea.Setting.Query()
                                               .Include(s => s.SettingValues)
                                               .Where(x => settingKeys.Contains(x.Name + "-" + x.ObjectType + "-" + x.Id))
                                               .ToList();

                    changeTracker.AddAction = x => _baseUnitOfWork.ExecuteAndCommit(uow => { uow.BaseWorkArea.Setting.Add((SettingEntity)x); });
                    //Need for real remove object from nested collection (because EF default remove references only)
                    changeTracker.RemoveAction = x => _baseUnitOfWork.ExecuteAndCommit(uow => { uow.BaseWorkArea.Setting.Delete((SettingEntity)x); });

                    var target = new { Settings = new List <SettingEntity>(alreadyExistSettings) };
                    var source = new { Settings = new List <SettingEntity>(settings.Select(x => x.ToEntity())) };

                    changeTracker.Attach(target);
                    var settingComparer = AnonymousComparer.Create((SettingEntity x) => String.Join("-", x.Name, x.ObjectType, x.Id));
                    source.Settings.Patch(target.Settings, settingComparer, (sourceSetting, targetSetting) => sourceSetting.Patch(targetSetting));
                }

                ClearCache();
            }
        }
Пример #23
0
        public virtual void Patch(CategoryEntity target)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            target.CatalogId        = CatalogId;
            target.ParentCategoryId = ParentCategoryId;
            target.Code             = Code;
            target.Name             = Name;
            target.TaxType          = TaxType;
            target.Priority         = Priority;
            target.IsActive         = IsActive;

            if (!CategoryPropertyValues.IsNullCollection())
            {
                CategoryPropertyValues.Patch(target.CategoryPropertyValues, (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue));
            }

            if (!OutgoingLinks.IsNullCollection())
            {
                var categoryRelationComparer = AnonymousComparer.Create((CategoryRelationEntity x) => string.Join(":", x.TargetCatalogId, x.TargetCategoryId));
                OutgoingLinks.Patch(target.OutgoingLinks, categoryRelationComparer, (sourceLink, targetLink) => sourceLink.Patch(targetLink));
            }

            if (!Images.IsNullCollection())
            {
                Images.Patch(target.Images, (sourceImage, targetImage) => sourceImage.Patch(targetImage));
            }
        }
Пример #24
0
        /// <summary>
        /// Patch CatalogBase type
        /// </summary>
        /// <param name="source"></param>
        /// <param name="target"></param>
        public static void Patch(this dataModel.Catalog source, dataModel.Catalog target)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            var patchInjectionPolicy = new PatchInjection <dataModel.Catalog>(x => x.Name, x => x.DefaultLanguage);

            target.InjectFrom(patchInjectionPolicy, source);

            //Languages patch
            var sourceCatalog = source as dataModel.Catalog;
            var targetCatalog = target as dataModel.Catalog;

            if (sourceCatalog != null && targetCatalog != null && !sourceCatalog.CatalogLanguages.IsNullCollection())
            {
                var languageComparer = AnonymousComparer.Create((dataModel.CatalogLanguage x) => x.Language);
                sourceCatalog.CatalogLanguages.Patch(targetCatalog.CatalogLanguages, languageComparer,
                                                     (sourceLang, targetlang) => sourceLang.Patch(targetlang));
            }

            //Property values
            if (sourceCatalog != null && !sourceCatalog.CatalogPropertyValues.IsNullCollection())
            {
                sourceCatalog.CatalogPropertyValues.Patch(targetCatalog.CatalogPropertyValues, (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue));
            }
        }
Пример #25
0
        public void SaveSettings(SettingEntry[] settings)
        {
            if (settings != null && settings.Any())
            {
                var settingKeys = settings.Select(x => String.Join("-", x.Name, x.ObjectType, x.ObjectId)).Distinct().ToArray();

                using (var repository = _repositoryFactory())
                    using (var changeTracker = new ObservableChangeTracker())
                    {
                        var alreadyExistSettings = repository.Settings
                                                   .Include(s => s.SettingValues)
                                                   .Where(x => settingKeys.Contains(x.Name + "-" + x.ObjectType + "-" + x.ObjectId))
                                                   .ToList();

                        changeTracker.AddAction = x => repository.Add(x);
                        //Need for real remove object from nested collection (because EF default remove references only)
                        changeTracker.RemoveAction = x => repository.Remove(x);

                        var target = new { Settings = new ObservableCollection <SettingEntity>(alreadyExistSettings) };
                        var source = new { Settings = new ObservableCollection <SettingEntity>(settings.Select(x => AbstractTypeFactory <SettingEntity> .TryCreateInstance().FromModel(x))) };

                        changeTracker.Attach(target);
                        var settingComparer = AnonymousComparer.Create((SettingEntity x) => String.Join("-", x.Name, x.ObjectType, x.ObjectId));
                        source.Settings.Patch(target.Settings, settingComparer, (sourceSetting, targetSetting) => sourceSetting.Patch(targetSetting));

                        repository.UnitOfWork.Commit();
                    }

                ClearCache(settings);
            }
        }
Пример #26
0
        public async Task <Property[]> GetPropertiesAsync(BulkActionContext context)
        {
            var result      = new List <Property>();
            var propertyIds = new HashSet <string>();
            var dataSource  = _dataSourceFactory.Create(context);

            result.AddRange(GetStandardProperties());

            while (await dataSource.FetchAsync())
            {
                var productIds = dataSource.Items.Select(item => item.Id).ToArray();
                var products   = await _itemService.GetByIdsAsync(productIds, (ItemResponseGroup.ItemInfo | ItemResponseGroup.ItemProperties).ToString());

                // using only product inherited properties from categories,
                // own product props (only from PropertyValues) are not set via bulk update action
                var newProperties = products.SelectMany(CollectionSelector())
                                    .Distinct(AnonymousComparer.Create <Property, string>(property => property.Id))
                                    .Where(property => !propertyIds.Contains(property.Id)).ToArray();

                propertyIds.AddRange(newProperties.Select(property => property.Id));
                result.AddRange(newProperties);
            }

            foreach (var property in result)
            {
                await FillOwnerName(property);
            }

            return(result.ToArray());
        }
Пример #27
0
        public override async Task <IdentityResult> UpdateAsync(Role role)
        {
            //TODO: Unstable method work, sometimes throws EF already being tracked exception
            //https://github.com/aspnet/Identity/issues/1807
            var result = await base.UpdateAsync(role);

            if (result.Succeeded && role.Permissions != null)
            {
                var sourcePermissionClaims = role.Permissions.Select(x => new Claim(PlatformConstants.Security.Claims.PermissionClaimType, x.Name)).ToList();
                var targetPermissionClaims = (await GetClaimsAsync(role)).Where(x => x.Type == PlatformConstants.Security.Claims.PermissionClaimType).ToList();
                var comparer = AnonymousComparer.Create((Claim x) => x.Value);
                //Add
                foreach (var sourceClaim in sourcePermissionClaims.Except(targetPermissionClaims, comparer))
                {
                    await base.AddClaimAsync(role, sourceClaim);
                }
                //Remove
                foreach (var targetClaim in targetPermissionClaims.Except(sourcePermissionClaims, comparer).ToArray())
                {
                    await base.RemoveClaimAsync(role, targetClaim);
                }

                SecurityCacheRegion.ExpireRegion();
            }
            return(result);
        }
Пример #28
0
        public virtual void Patch(PromotionEntity target)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            target.StartDate   = StartDate;
            target.EndDate     = EndDate;
            target.StoreId     = StoreId;
            target.Name        = Name;
            target.Description = Description;
            target.IsActive    = IsActive;
            target.IsExclusive = IsExclusive;
            target.EndDate     = EndDate;
            target.Priority    = Priority;
            target.PredicateVisualTreeSerialized = PredicateVisualTreeSerialized;
            target.PerCustomerLimit         = PerCustomerLimit;
            target.TotalLimit               = TotalLimit;
            target.PerCustomerLimit         = PerCustomerLimit;
            target.IsAllowCombiningWithSelf = IsAllowCombiningWithSelf;

            if (!Stores.IsNullCollection())
            {
                var comparer = AnonymousComparer.Create((PromotionStoreEntity entity) => entity.StoreId);
                Stores.Patch(target.Stores, comparer, (sourceEntity, targetEntity) => targetEntity.StoreId = sourceEntity.StoreId);
            }
        }
Пример #29
0
        public virtual void Patch(MemberDataEntity target)
        {
            var patchInjection = new PatchInjection <MemberDataEntity>(x => x.Name);

            target.InjectFrom(patchInjection, this);

            if (!this.Phones.IsNullCollection())
            {
                var phoneComparer = AnonymousComparer.Create((PhoneDataEntity x) => x.Number);
                this.Phones.Patch(target.Phones, phoneComparer, (sourcePhone, targetPhone) => targetPhone.Number = sourcePhone.Number);
            }

            if (!this.Emails.IsNullCollection())
            {
                var addressComparer = AnonymousComparer.Create((EmailDataEntity x) => x.Address);
                this.Emails.Patch(target.Emails, addressComparer, (sourceEmail, targetEmail) => targetEmail.Address = sourceEmail.Address);
            }

            if (!this.Addresses.IsNullCollection())
            {
                this.Addresses.Patch(target.Addresses, new AddressDataEntityComparer(), (sourceAddress, targetAddress) => sourceAddress.Patch(targetAddress));
            }

            if (!this.Notes.IsNullCollection())
            {
                var noteComparer = AnonymousComparer.Create((NoteDataEntity x) => x.Id ?? x.Body);
                this.Notes.Patch(target.Notes, noteComparer, (sourceNote, targetNote) => sourceNote.Patch(targetNote));
            }

            if (!this.MemberRelations.IsNullCollection())
            {
                var relationComparer = AnonymousComparer.Create((MemberRelationDataEntity x) => x.AncestorId);
                this.MemberRelations.Patch(target.MemberRelations, relationComparer, (sourceRel, targetRel) => { /*Nothing todo*/ });
            }
        }
Пример #30
0
        protected virtual async Task <SeoEntity> FindEntityBySlugPath(string path, WorkContext workContext)
        {
            path = path.Trim('/');

            var slugs    = path.Split('/');
            var lastSlug = slugs.LastOrDefault();

            // Get all SEO records for requested slug and also all other SEO records with different slug and languages but related to the same object
            var allSeoRecords = await GetAllSeoRecordsAsync(lastSlug);

            var bestSeoRecords = GetBestMatchingSeoRecords(allSeoRecords, workContext.CurrentStore, workContext.CurrentLanguage, lastSlug);

            var seoEntityComparer = AnonymousComparer.Create((SeoEntity x) => string.Join(":", x.ObjectType, x.ObjectId, x.SeoPath));
            // Find distinct objects
            var entities = bestSeoRecords
                           .Select(s => new SeoEntity {
                ObjectType = s.ObjectType, ObjectId = s.ObjectId, SeoPath = s.SemanticUrl
            })
                           .Distinct(seoEntityComparer)
                           .ToList();

            // Don't load objects for non-SEO links
            if (workContext.CurrentStore.SeoLinksType != SeoLinksType.None)
            {
                foreach (var group in entities.GroupBy(e => e.ObjectType))
                {
                    await LoadObjectsAndBuildFullSeoPaths(group.Key, group.ToList(), workContext.CurrentStore, workContext.CurrentLanguage);
                }

                entities = entities.Where(e => !string.IsNullOrEmpty(e.SeoPath)).ToList();
            }

            // If found multiple entities, keep those which have the requested SEO path
            if (entities.Count > 1)
            {
                entities = entities.Where(e => e.SeoPath.EqualsInvariant(path)).ToList();
            }

            // If still found multiple entities, give up
            var result = entities.Count == 1 ? entities.FirstOrDefault() : null;

            if (result == null)
            {
                // Try to find a static page
                var page = FindPageBySeoPath(path, workContext);
                if (page != null)
                {
                    result = new SeoEntity
                    {
                        ObjectType     = "Page",
                        SeoPath        = page.Url,
                        ObjectInstance = page,
                    };
                }
            }

            return(result);
        }