public async Task <IEnumerable <QuoteRequest> > GetByIdsAsync(params string[] ids)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(GetByIdsAsync), string.Join("-", ids));

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                var retVal = new List <QuoteRequest>();
                using (var repository = _repositoryFactory())
                {
                    //It is so important to generate change tokens for all ids even for not existing members to prevent an issue
                    //with caching of empty results for non - existing objects that have the infinitive lifetime in the cache
                    //and future unavailability to create objects with these ids.
                    cacheEntry.AddExpirationToken(QuoteCacheRegion.CreateChangeToken(ids));
                    repository.DisableChangesTracking();

                    var dbQuotes = await repository.GetQuoteRequestByIdsAsync(ids);
                    foreach (var dbQuote in dbQuotes)
                    {
                        var quote = dbQuote.ToModel(AbstractTypeFactory <QuoteRequest> .TryCreateInstance());
                        retVal.Add(quote);
                    }
                }

                return retVal.ToArray();
            }));
        }
Beispiel #2
0
        public virtual async Task <PromotionSearchResult> SearchPromotionsAsync(PromotionSearchCriteria criteria)
        {
            var cacheKey = CacheKey.With(GetType(), "SearchPromotionsAsync", criteria.GetCacheKey());

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(PromotionCacheRegion.CreateChangeToken());
                var retVal = AbstractTypeFactory <PromotionSearchResult> .TryCreateInstance();
                using (var repository = _repositoryFactory())
                {
                    var query = GetPromotionsQuery(repository, criteria);

                    var sortInfos = criteria.SortInfos;
                    if (sortInfos.IsNullOrEmpty())
                    {
                        sortInfos = new[] { new SortInfo {
                                                SortColumn = ReflectionUtility.GetPropertyName <Promotion>(x => x.Priority), SortDirection = SortDirection.Descending
                                            } };
                    }
                    query = query.OrderBySortInfos(sortInfos);

                    retVal.TotalCount = await query.CountAsync();

                    if (criteria.Take > 0)
                    {
                        var ids = await query.Select(x => x.Id)
                                  .Skip(criteria.Skip)
                                  .Take(criteria.Take).ToArrayAsync();
                        var promotions = await _promotionService.GetPromotionsByIdsAsync(ids);
                        retVal.Results = promotions.OrderBy(p => ids.ToList().IndexOf(p.Id)).ToList();
                    }
                }
                return retVal;
            }));
        }
Beispiel #3
0
        public async Task <GenericSearchResult <Coupon> > SearchCouponsAsync(CouponSearchCriteria criteria)
        {
            if (criteria == null)
            {
                throw new ArgumentNullException("criteria");
            }

            var cacheKey = CacheKey.With(GetType(), "SearchCouponsAsync", criteria.GetCacheKey());

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(CouponCacheRegion.CreateChangeToken());

                using (var repository = _repositoryFactory())
                {
                    var query = repository.Coupons;

                    if (!string.IsNullOrEmpty(criteria.PromotionId))
                    {
                        query = query.Where(c => c.PromotionId == criteria.PromotionId);
                    }
                    if (!string.IsNullOrEmpty(criteria.Code))
                    {
                        query = query.Where(c => c.Code == criteria.Code);
                    }
                    if (!criteria.Codes.IsNullOrEmpty())
                    {
                        query = query.Where(c => criteria.Codes.Contains(c.Code));
                    }

                    var sortInfos = criteria.SortInfos;
                    //TODO: Sort by TotalUsesCount
                    if (sortInfos.IsNullOrEmpty() || sortInfos.Any(x => x.SortColumn.EqualsInvariant(ReflectionUtility.GetPropertyName <Coupon>(p => p.TotalUsesCount))))
                    {
                        sortInfos = new[] { new SortInfo {
                                                SortColumn = ReflectionUtility.GetPropertyName <Coupon>(x => x.Code), SortDirection = SortDirection.Descending
                                            } };
                    }
                    query = query.OrderBySortInfos(sortInfos);

                    var totalCount = await query.CountAsync();
                    var searchResult = new GenericSearchResult <Coupon> {
                        TotalCount = totalCount
                    };

                    if (criteria.Take > 0)
                    {
                        var ids = await query.Select(x => x.Id).Skip(criteria.Skip).Take(criteria.Take).ToArrayAsync();
                        searchResult.Results = await GetByIdsAsync(ids);
                    }

                    return searchResult;
                }
            }));
        }
        /// <summary>
        /// Evaluate pricelists for special context. All resulting pricelists ordered by priority
        /// </summary>
        /// <param name="evalContext"></param>
        /// <returns></returns>
        public virtual async Task <IEnumerable <Pricelist> > EvaluatePriceListsAsync(PriceEvaluationContext evalContext)
        {
            var cacheKey             = CacheKey.With(GetType(), nameof(EvaluatePriceListsAsync));
            var priceListAssignments = await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async cacheEntry =>
            {
                cacheEntry.AddExpirationToken(PricingCacheRegion.CreateChangeToken());

                return(await GetAllPricelistAssignments());
            });

            var query = priceListAssignments.AsQueryable();

            if (evalContext.CatalogId != null)
            {
                //filter by catalog
                query = query.Where(x => x.CatalogId == evalContext.CatalogId);
            }

            if (evalContext.Currency != null)
            {
                //filter by currency
                query = query.Where(x => x.Pricelist.Currency == evalContext.Currency.ToString());
            }

            if (evalContext.CertainDate != null)
            {
                //filter by date expiration
                query = query.Where(x => (x.StartDate == null || evalContext.CertainDate >= x.StartDate) && (x.EndDate == null || x.EndDate >= evalContext.CertainDate));
            }

            var assignments         = query.AsNoTracking().ToArray();
            var assignmentsToReturn = assignments.Where(x => x.DynamicExpression == null).ToList();

            foreach (var assignment in assignments.Where(x => x.DynamicExpression != null))
            {
                try
                {
                    if (assignment.DynamicExpression.IsSatisfiedBy(evalContext) && assignmentsToReturn.All(x => x.PricelistId != assignment.PricelistId))
                    {
                        assignmentsToReturn.Add(assignment);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Failed to evaluate price assignment condition.");
                }
            }

            return(assignmentsToReturn.OrderByDescending(x => x.Priority).ThenByDescending(x => x.Name).Select(x => x.Pricelist));
        }
Beispiel #5
0
        public async Task <DynamicContentItem[]> GetContentItemsByIdsAsync(string[] ids)
        {
            var cacheKey = CacheKey.With(GetType(), "GetContentItemsByIdsAsync", string.Join("-", ids));

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(DynamicContentItemCacheRegion.CreateChangeToken());
                DynamicContentItem[] retVal = null;
                using (var repository = _repositoryFactory())
                {
                    retVal = (await repository.GetContentItemsByIdsAsync(ids)).Select(x => x.ToModel(AbstractTypeFactory <DynamicContentItem> .TryCreateInstance())).ToArray();
                }
                return retVal;
            }));
        }
        public virtual Task <PriceSearchResult> SearchPricesAsync(PricesSearchCriteria criteria)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(SearchPricesAsync), criteria.GetCacheKey());

            return(_platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async cacheEntry =>
            {
                cacheEntry.AddExpirationToken(PricesCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(PricingSearchCacheRegion.CreateChangeToken());

                var result = AbstractTypeFactory <PriceSearchResult> .TryCreateInstance();

                using (var repository = _repositoryFactory())
                {
                    var query = await BuildQueryAsync(repository, criteria);
                    var sortInfos = BuildSortExpression(criteria);
                    //Try to replace sorting columns names
                    TryTransformSortingInfoColumnNames(_pricesSortingAliases, sortInfos);

                    if (criteria.GroupByProducts)
                    {
                        var groupedQuery = query.Select(x => x.ProductId).OrderBy(x => x).Distinct();
                        result.TotalCount = await groupedQuery.CountAsync();

                        if (criteria.Take > 0)
                        {
                            query = query.Where(x => groupedQuery.Contains(x.ProductId));
                        }
                    }
                    else
                    {
                        result.TotalCount = await query.CountAsync();
                    }

                    if (criteria.Take > 0)
                    {
                        var priceIds = await query.OrderBySortInfos(sortInfos).ThenBy(x => x.Id)
                                       .Skip(criteria.Skip).Take(criteria.Take)
                                       .Select(x => x.Id)
                                       .AsNoTracking()
                                       .ToArrayAsync();

                        var unorderedResults = await _pricingService.GetPricesByIdAsync(priceIds);
                        result.Results = unorderedResults.OrderBy(x => Array.IndexOf(priceIds, x.Id)).ToList();
                    }
                }
                return result;
            }));
        }
Beispiel #7
0
        protected virtual async Task <IList <ImageChange> > GetChangeFiles(ThumbnailTask task, DateTime?changedSince, ICancellationToken token)
        {
            var options = await GetOptionsCollection();

            var cacheKey = CacheKey.With(GetType(), "GetChangeFiles", task.WorkPath, changedSince?.ToString(), string.Join(":", options.Select(x => x.FileSuffix)));

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(BlobChangesCacheRegion.CreateChangeToken(task, changedSince));

                var allBlobInfos = await ReadBlobFolderAsync(task.WorkPath, token);
                var orignalBlobInfos = GetOriginalItems(allBlobInfos, options.Select(x => x.FileSuffix).ToList());

                var result = new List <ImageChange>();
                foreach (var blobInfo in orignalBlobInfos)
                {
                    token?.ThrowIfCancellationRequested();

                    var imageChange = new ImageChange
                    {
                        Name = blobInfo.Name,
                        Url = blobInfo.Url,
                        ModifiedDate = blobInfo.ModifiedDate,
                        ChangeState = !changedSince.HasValue ? EntryState.Added : GetItemState(blobInfo, changedSince, task.ThumbnailOptions)
                    };
                    result.Add(imageChange);
                }
                return result.Where(x => x.ChangeState != EntryState.Unchanged).ToList();
            }));
        }
        protected virtual async Task <IDictionary <string, Category> > PreloadCategoriesAsync(string catalogId)
        {
            var cacheKey = CacheKey.With(GetType(), "PreloadCategories", catalogId);

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(CatalogCacheRegion.CreateChangeToken());

                CategoryEntity[] entities;
                using (var repository = _repositoryFactory())
                {
                    repository.DisableChangesTracking();

                    entities = await repository.GetCategoriesByIdsAsync(repository.Categories.Select(x => x.Id).ToArray(), CategoryResponseGroup.Full);
                }
                var result = entities.Select(x => x.ToModel(AbstractTypeFactory <Category> .TryCreateInstance()))
                             .ToDictionary(x => x.Id, StringComparer.OrdinalIgnoreCase)
                             .WithDefaultValue(null);

                await LoadDependenciesAsync(result.Values, result);
                ApplyInheritanceRules(result.Values);

                // Fill outlines for categories
                _outlineService.FillOutlinesForObjects(result.Values, catalogId);
                return result;
            }));
        }
        public virtual async Task <TaxProvider[]> GetByIdsAsync(string[] ids, string responseGroup)
        {
            var cacheKey = CacheKey.With(GetType(), "GetByIdsAsync", string.Join("-", ids));

            return(await _memCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                var result = new List <TaxProvider>();

                using (var repository = _repositoryFactory())
                {
                    repository.DisableChangesTracking();
                    var existEntities = await repository.GetStoreTaxProviderByIdsAsync(ids, responseGroup);
                    foreach (var existEntity in existEntities)
                    {
                        var taxProvider = AbstractTypeFactory <TaxProvider> .TryCreateInstance(string.IsNullOrEmpty(existEntity.TypeName) ? $"{existEntity.Code}TaxProvider" : existEntity.TypeName);
                        if (taxProvider != null)
                        {
                            existEntity.ToModel(taxProvider);

                            await _settingManager.DeepLoadSettingsAsync(taxProvider);
                            result.Add(taxProvider);
                        }
                    }
                    cacheEntry.AddExpirationToken(TaxCacheRegion.CreateChangeToken());
                    return result.ToArray();
                }
            }));
        }
        public async Task <ShoppingCartSearchResult> SearchCartAsync(ShoppingCartSearchCriteria criteria)
        {
            var result = AbstractTypeFactory <ShoppingCartSearchResult> .TryCreateInstance();

            var cacheKey = CacheKey.With(GetType(), nameof(SearchCartAsync), criteria.GetCacheKey());

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async cacheEntry =>
            {
                cacheEntry.AddExpirationToken(CartSearchCacheRegion.CreateChangeToken());
                using (var repository = _repositoryFactory())
                {
                    //Optimize performance and CPU usage
                    repository.DisableChangesTracking();

                    var sortInfos = BuildSortExpression(criteria);
                    var query = BuildQuery(repository, criteria);

                    result.TotalCount = await query.CountAsync();
                    if (criteria.Take > 0)
                    {
                        var ids = await query.OrderBySortInfos(sortInfos).ThenBy(x => x.Id)
                                  .Select(x => x.Id)
                                  .Skip(criteria.Skip).Take(criteria.Take)
                                  .ToArrayAsync();

                        result.Results = (await _cartService.GetByIdsAsync(ids, criteria.ResponseGroup)).OrderBy(x => Array.IndexOf(ids, x.Id)).ToList();
                    }

                    return result;
                }
            }));
        }
        public virtual async Task <DemoProductPart[]> GetByIdsAsync(string[] partIds)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(GetByIdsAsync), string.Join("-", partIds.OrderBy(x => x)));

            var result = await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async cacheEntry =>
            {
                var parts = Array.Empty <DemoProductPart>();

                if (!partIds.IsNullOrEmpty())
                {
                    using var repository = (DemoCatalogRepository)_repositoryFactory();

                    //Optimize performance and CPU usage
                    repository.DisableChangesTracking();

                    var entities = await repository.GetProductPartsByIdsAsync(partIds);

                    parts = entities
                            .Select(x => x.ToModel(AbstractTypeFactory <DemoProductPart> .TryCreateInstance()))
                            .ToArray();

                    cacheEntry.AddExpirationToken(DemoProductPartCacheRegion.CreateChangeToken(partIds));
                }

                return(parts);
            });

            return(result);
        }
        public async Task <DynamicContentItemSearchResult> SearchContentItemsAsync(DynamicContentItemSearchCriteria criteria)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(SearchContentItemsAsync), criteria.GetCacheKey());

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(DynamicContentItemCacheRegion.CreateChangeToken());
                var result = AbstractTypeFactory <DynamicContentItemSearchResult> .TryCreateInstance();
                using (var repository = _repositoryFactory())
                {
                    var sortInfos = BuildSortExpression(criteria);
                    var query = BuildQuery(criteria, repository);

                    result.TotalCount = await query.CountAsync();

                    if (criteria.Take > 0)
                    {
                        var ids = await query.OrderBySortInfos(sortInfos).ThenBy(x => x.Id)
                                  .Select(x => x.Id)
                                  .Skip(criteria.Skip).Take(criteria.Take)
                                  .ToArrayAsync();
                        result.Results = (await _dynamicContentService.GetContentItemsByIdsAsync(ids))
                                         .OrderBy(x => Array.IndexOf(ids, x.Id)).ToList();
                    }
                }
                return result;
            }));
        }
        public async Task <SubscriptionInfo[]> GetByIdsAsync(string[] ids, string responseGroup = null)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(GetByIdsAsync), string.Join("-", ids));

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(SubscriptionCacheRegion.CreateChangeToken());

                var result = new List <SubscriptionInfo>();

                if (!ids.IsNullOrEmpty())
                {
                    using (var repository = _subscriptionRepositoryFactory())
                    {
                        var entities = await repository.GetSubscriptionsByIdsAsync(ids);

                        if (!entities.IsNullOrEmpty())
                        {
                            result.AddRange(entities.Select(x => x.ToModel(AbstractTypeFactory <SubscriptionInfo> .TryCreateInstance())));
                        }
                    }
                }

                return result.ToArray();
            }));
        }
Beispiel #14
0
        public virtual async Task <CustomerSegment[]> GetByIdsAsync(string[] ids)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(GetByIdsAsync), string.Join("-", ids.OrderBy(x => x)));

            var result = await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async cacheEntry =>
            {
                var rules = Array.Empty <CustomerSegment>();

                if (!ids.IsNullOrEmpty())
                {
                    using var customerSegmentsRepository = _customerSegmentRepositoryFactory();

                    //Optimize performance and CPU usage
                    customerSegmentsRepository.DisableChangesTracking();

                    var entities = await customerSegmentsRepository.GetByIdsAsync(ids);

                    rules = entities
                            .Select(x => x.ToModel(AbstractTypeFactory <CustomerSegment> .TryCreateInstance()))
                            .ToArray();

                    cacheEntry.AddExpirationToken(CustomerSegmentCacheRegion.CreateChangeToken(ids));
                }

                return(rules);
            });

            return(result);
        }
Beispiel #15
0
        public async Task <ProductVideoSearchResult> SearchVideoLinksAsync(ProductVideoSearchCriteria criteria)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(SearchVideoLinksAsync), criteria.GetCacheKey());

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(ProductVideoCacheRegion.CreateChangeToken());
                var result = AbstractTypeFactory <ProductVideoSearchResult> .TryCreateInstance();

                using (var repository = _repositoryFactory())
                {
                    var query = repository.VideoLinks.Where(x => criteria.ProductIds.Contains(x.ProductId));

                    result.TotalCount = await query.CountAsync();

                    if (criteria.Take > 0)
                    {
                        var videoLinksIds = await query.OrderByDescending(x => x.CreatedDate).Skip(criteria.Skip)
                                            .Take(criteria.Take)
                                            .Select(x => x.Id)
                                            .ToArrayAsync();

                        var priorResults = await _productVideoService.GetByIdsAsync(videoLinksIds);
                        //TODO warning EF1001: Microsoft.EntityFrameworkCore.Internal.EnumerableExtensions is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs.
                        result.Results = priorResults;
                    }

                    return result;
                }
            }));
        }
#pragma warning disable S4457 // Parameter validation in "async"/"await" methods should be wrapped
        public virtual async Task <PromotionUsageSearchResult> SearchUsagesAsync(PromotionUsageSearchCriteria criteria)
#pragma warning restore S4457 // Parameter validation in "async"/"await" methods should be wrapped
        {
            if (criteria == null)
            {
                throw new ArgumentNullException(nameof(criteria));
            }

            var cacheKey = CacheKey.With(GetType(), nameof(SearchUsagesAsync), criteria.GetCacheKey());

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(PromotionUsageSearchCacheRegion.CreateChangeToken());

                var result = AbstractTypeFactory <PromotionUsageSearchResult> .TryCreateInstance();

                using (var repository = _repositoryFactory())
                {
                    var sortInfos = BuildSortExpression(criteria);
                    var query = BuildQuery(repository, criteria);

                    result.TotalCount = await query.CountAsync();

                    if (criteria.Take > 0)
                    {
                        var usages = await query.OrderBySortInfos(sortInfos).ThenBy(x => x.Id)
                                     .Skip(criteria.Skip).Take(criteria.Take)
                                     .ToArrayAsync();
                        result.Results = usages.Select(x => x.ToModel(AbstractTypeFactory <PromotionUsage> .TryCreateInstance())).ToList();
                    }

                    return result;
                }
            }));
        }
Beispiel #17
0
        public virtual async Task <IEnumerable <ShoppingCart> > GetByIdsAsync(string[] cartIds, string responseGroup = null)
        {
            var retVal   = new List <ShoppingCart>();
            var cacheKey = CacheKey.With(GetType(), "GetByIdsAsync", string.Join("-", cartIds), responseGroup);

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                using (var repository = _repositoryFactory())
                {
                    //Disable DBContext change tracking for better performance
                    repository.DisableChangesTracking();

                    var cartEntities = await repository.GetShoppingCartsByIdsAsync(cartIds, responseGroup);
                    foreach (var cartEntity in cartEntities)
                    {
                        var cart = cartEntity.ToModel(AbstractTypeFactory <ShoppingCart> .TryCreateInstance());
                        //Calculate totals only for full responseGroup
                        if (responseGroup == null)
                        {
                            _totalsCalculator.CalculateTotals(cart);
                        }
                        retVal.Add(cart);
                        cacheEntry.AddExpirationToken(CartCacheRegion.CreateChangeToken(cart));
                    }
                }

                await _dynamicPropertyService.LoadDynamicPropertyValuesAsync(retVal.ToArray <IHasDynamicProperties>());

                return retVal;
            }));
        }
        public async virtual Task <Association[]> GetByIdsAsync(string[] itemIds)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(GetByIdsAsync), string.Join("-", itemIds.OrderBy(x => x)));

            var result = await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async cacheEntry =>
            {
                var rules = Array.Empty <Association>();

                if (!itemIds.IsNullOrEmpty())
                {
                    using (var dynamicAssociationsRepository = _associationsRepositoryFactory())
                    {
                        //Optimize performance and CPU usage
                        dynamicAssociationsRepository.DisableChangesTracking();

                        var entities = await dynamicAssociationsRepository.GetAssociationsByIdsAsync(itemIds);

                        rules = entities
                                .Select(x => x.ToModel(AbstractTypeFactory <Association> .TryCreateInstance()))
                                .ToArray();

                        cacheEntry.AddExpirationToken(AssociationCacheRegion.CreateChangeToken(itemIds));
                    }
                }

                return(rules);
            });

            return(result);
        }
        public async Task <Store[]> GetByIdsAsync(string[] ids)
        {
            var cacheKey = CacheKey.With(GetType(), "GetByIdsAsync", string.Join("-", ids));

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                var stores = new List <Store>();

                using (var repository = _repositoryFactory())
                {
                    var dbStores = await repository.GetStoresByIdsAsync(ids);
                    foreach (var dbStore in dbStores)
                    {
                        var store = AbstractTypeFactory <Store> .TryCreateInstance();
                        dbStore.ToModel(store);

                        PopulateStore(store, dbStore);

                        await _settingManager.DeepLoadSettingsAsync(store);
                        stores.Add(store);
                        cacheEntry.AddExpirationToken(StoreCacheRegion.CreateChangeToken(store));
                    }
                }

                var result = stores.ToArray();
                var taskLoadDynamicPropertyValues = _dynamicPropertyService.LoadDynamicPropertyValuesAsync(result);
                var taskLoadSeoForObjects = _seoService.LoadSeoForObjectsAsync(result);
                await Task.WhenAll(taskLoadDynamicPropertyValues, taskLoadSeoForObjects);

                return result;
            }));
        }
        public virtual async Task <PromotionSearchResult> SearchPromotionsAsync(PromotionSearchCriteria criteria)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(SearchPromotionsAsync), criteria.GetCacheKey());

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(PromotionSearchCacheRegion.CreateChangeToken());

                var result = AbstractTypeFactory <PromotionSearchResult> .TryCreateInstance();

                using (var repository = _repositoryFactory())
                {
                    var sortInfos = BuildSortExpression(criteria);
                    var query = BuildQuery(repository, criteria);
                    //https://github.com/zzzprojects/EntityFramework-Plus/issues/293
                    //Workaround ArgumentException with CountAsync have no predicate when query has a Cast or OfType expression
                    result.TotalCount = await query.CountAsync(x => true);

                    if (criteria.Take > 0)
                    {
                        var ids = await query.OrderBySortInfos(sortInfos).ThenBy(x => x.Id)
                                  .Select(x => x.Id)
                                  .Skip(criteria.Skip).Take(criteria.Take)
                                  .ToArrayAsync();

                        result.Results = (await _promotionService.GetPromotionsByIdsAsync(ids))
                                         .OrderBy(x => Array.IndexOf(ids, x.Id)).ToList();
                    }
                }
                return result;
            }));
        }
Beispiel #21
0
        public async Task <ShoppingCartSearchResult> SearchCartAsync(ShoppingCartSearchCriteria criteria)
        {
            var retVal = AbstractTypeFactory <ShoppingCartSearchResult> .TryCreateInstance();

            var cacheKey = CacheKey.With(GetType(), "SearchCartAsync", criteria.GetCacheKey());

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async cacheEntry =>
            {
                cacheEntry.AddExpirationToken(CartSearchCacheRegion.CreateChangeToken());
                using (var repository = _repositoryFactory())
                {
                    var sortInfos = GetSortInfos(criteria);
                    var query = GetQuery(repository, criteria, sortInfos);

                    retVal.TotalCount = await query.CountAsync();
                    if (criteria.Take > 0)
                    {
                        var cartIds = await query.Select(x => x.Id).Skip(criteria.Skip).Take(criteria.Take).ToArrayAsync();
                        retVal.Results = (await _cartService.GetByIdsAsync(cartIds, criteria.ResponseGroup)).AsQueryable().OrderBySortInfos(sortInfos).ToArray();
                    }

                    return retVal;
                }
            }));
        }
Beispiel #22
0
        public virtual async Task <StoreSearchResult> SearchStoresAsync(StoreSearchCriteria criteria)
        {
            var cacheKey = CacheKey.With(GetType(), "SearchStoresAsync", criteria.GetCacheKey());

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(StoreCacheRegion.CreateChangeToken());
                var result = AbstractTypeFactory <StoreSearchResult> .TryCreateInstance();
                using (var repository = _repositoryFactory())
                {
                    var sortInfos = criteria.SortInfos;
                    if (sortInfos.IsNullOrEmpty())
                    {
                        sortInfos = new[]
                        {
                            new SortInfo
                            {
                                SortColumn = "Name"
                            }
                        };
                    }

                    var query = GetStoresQuery(repository, criteria, sortInfos);

                    result.TotalCount = await query.CountAsync();
                    if (criteria.Take > 0)
                    {
                        var storeIds = await query.Select(x => x.Id).Skip(criteria.Skip).Take(criteria.Take).ToArrayAsync();
                        result.Results = (await _storeService.GetByIdsAsync(storeIds)).AsQueryable().OrderBySortInfos(sortInfos).ToList();
                    }
                }
                return result;
            }));
        }
Beispiel #23
0
        public override async Task <Role> FindByNameAsync(string roleName)
        {
            var cacheKey = CacheKey.With(GetType(), "FindByNameAsync", roleName);
            var result   = await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(SecurityCacheRegion.CreateChangeToken());
                var role = await base.FindByNameAsync(roleName);
                if (role != null)
                {
                    await LoadRolePermissionsAsync(role);
                }
                return(role);
            }, cacheNullValue : false);

            return(result);
        }
        public async Task <SubscriptionSearchResult> SearchAsync(SubscriptionSearchCriteria searchCriteria)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(SearchAsync), searchCriteria.GetCacheKey());

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(SubscriptionSearchCacheRegion.CreateChangeToken());
                var result = new SubscriptionSearchResult();

                using (var repository = _subscriptionRepositoryFactory())
                {
                    repository.DisableChangesTracking();

                    var sortInfos = BuildSortExpression(searchCriteria);
                    var query = BuildQuery(searchCriteria, repository);

                    result.TotalCount = await query.CountAsync();

                    if (searchCriteria.Take > 0 && result.TotalCount > 0)
                    {
                        var subscriptionIds = query.OrderBySortInfos(sortInfos)
                                              .ThenBy(x => x.Id)
                                              .Select(x => x.Id)
                                              .Skip(searchCriteria.Skip)
                                              .Take(searchCriteria.Take)
                                              .ToArray();

                        result.Results = (await _subscriptionService.GetByIdsAsync(subscriptionIds, searchCriteria.ResponseGroup)).OrderBy(x => Array.IndexOf(subscriptionIds, x.Id)).ToArray();
                    }
                }

                return result;
            }));
        }
Beispiel #25
0
        public async Task <ProductAssociationSearchResult> SearchProductAssociationsAsync(ProductAssociationSearchCriteria criteria)
        {
            if (criteria == null)
            {
                throw new ArgumentNullException(nameof(criteria));
            }

            var cacheKey = CacheKey.With(GetType(), "SearchProductAssociationsAsync", criteria.GetCacheKey());

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(AssociationSearchCacheRegion.CreateChangeToken());
                var result = AbstractTypeFactory <ProductAssociationSearchResult> .TryCreateInstance();
                if (!criteria.ObjectIds.IsNullOrEmpty())
                {
                    using (var repository = _catalogRepositoryFactory())
                    {
                        //Optimize performance and CPU usage
                        repository.DisableChangesTracking();

                        var dbResult = await repository.SearchAssociations(criteria);

                        result.TotalCount = dbResult.TotalCount;
                        result.Results = dbResult.Results
                                         .Select(x => x.ToModel(AbstractTypeFactory <ProductAssociation> .TryCreateInstance())).ToList();
                    }
                }
                return result;
            }));
        }
        public async Task <PaymentMethod[]> GetByIdsAsync(string[] ids, string responseGroup)
        {
            var cacheKey = CacheKey.With(GetType(), "GetByIdsAsync", string.Join("-", ids));

            return(await _memCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                var result = new List <PaymentMethod>();

                using (var repository = _repositoryFactory())
                {
                    repository.DisableChangesTracking();
                    var existEntities = await repository.GetStorePaymentMethodsByIdsAsync(ids, responseGroup);
                    foreach (var existEntity in existEntities)
                    {
                        var paymentMethod = AbstractTypeFactory <PaymentMethod> .TryCreateInstance(string.IsNullOrEmpty(existEntity.TypeName) ? existEntity.Code : existEntity.TypeName);
                        if (paymentMethod != null)
                        {
                            existEntity.ToModel(paymentMethod);

                            await _settingManager.DeepLoadSettingsAsync(paymentMethod);
                            result.Add(paymentMethod);
                        }
                    }
                    cacheEntry.AddExpirationToken(PaymentCacheRegion.CreateChangeToken());
                    return result.ToArray();
                }
            }));
        }
Beispiel #27
0
        public override async Task <ApplicationUser> FindByLoginAsync(string loginProvider, string providerKey)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(FindByLoginAsync), loginProvider, providerKey);
            var result   = await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                var user = await base.FindByLoginAsync(loginProvider, providerKey);
                if (user != null)
                {
                    await LoadUserDetailsAsync(user);
                    cacheEntry.AddExpirationToken(SecurityCacheRegion.CreateChangeTokenForUser(user));
                }
                return(user);
            }, cacheNullValue : false);

            return(result);
        }
Beispiel #28
0
        public virtual async Task <SubscriptionSearchResult> SearchSubscriptionsAsync(SubscriptionSearchCriteria criteria)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(SearchSubscriptionsAsync), criteria.GetCacheKey());

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async cacheEntry =>
            {
                cacheEntry.AddExpirationToken(SubscriptionSearchCacheRegion.CreateChangeToken());

                var retVal = AbstractTypeFactory <SubscriptionSearchResult> .TryCreateInstance();
                using (var repository = _subscriptionRepositoryFactory())
                {
                    repository.DisableChangesTracking();

                    var query = BuildQuery(repository, criteria);
                    var sortInfos = BuildSortExpression(criteria);

                    retVal.TotalCount = await query.CountAsync();

                    if (criteria.Take > 0)
                    {
                        var subscriptionsIds = await query.OrderBySortInfos(sortInfos).ThenBy(x => x.Id)
                                               .Select(x => x.Id)
                                               .Skip(criteria.Skip).Take(criteria.Take)
                                               .ToArrayAsync();

                        //Load subscriptions with preserving sorting order
                        var unorderedResults = await _subscriptionService.GetByIdsAsync(subscriptionsIds, criteria.ResponseGroup);
                        retVal.Results = unorderedResults.OrderBy(x => Array.IndexOf(subscriptionsIds, x.Id)).ToArray();
                    }

                    return retVal;
                }
            }));
        }
        public virtual async Task <Subscription[]> GetByIdsAsync(string[] subscriptionIds, string responseGroup = null)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(GetByIdsAsync), string.Join("-", subscriptionIds), responseGroup);

            return(await _platformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async cacheEntry =>
            {
                var retVal = new List <Subscription>();
                var subscriptionResponseGroup = EnumUtility.SafeParseFlags(responseGroup, SubscriptionResponseGroup.Full);
                using (var repository = _subscriptionRepositoryFactory())
                {
                    repository.DisableChangesTracking();

                    var subscriptionEntities = await repository.GetSubscriptionsByIdsAsync(subscriptionIds, responseGroup);
                    foreach (var subscriptionEntity in subscriptionEntities)
                    {
                        var subscription = AbstractTypeFactory <Subscription> .TryCreateInstance();
                        if (subscription != null)
                        {
                            subscription = subscriptionEntity.ToModel(subscription);

                            retVal.Add(subscription);
                        }
                    }
                }

                CustomerOrder[] orderPrototypes = null;
                CustomerOrder[] subscriptionOrders = null;

                if (subscriptionResponseGroup.HasFlag(SubscriptionResponseGroup.WithOrderPrototype))
                {
                    orderPrototypes = await _customerOrderService.GetByIdsAsync(retVal.Select(x => x.CustomerOrderPrototypeId).ToArray());
                }
                if (subscriptionResponseGroup.HasFlag(SubscriptionResponseGroup.WithRelatedOrders))
                {
                    //Loads customer order prototypes and related orders for each subscription via order service
                    var criteria = new CustomerOrderSearchCriteria
                    {
                        SubscriptionIds = subscriptionIds
                    };
                    subscriptionOrders = (await _customerOrderSearchService.SearchCustomerOrdersAsync(criteria)).Results.ToArray();
                }

                foreach (var subscription in retVal)
                {
                    if (!orderPrototypes.IsNullOrEmpty())
                    {
                        subscription.CustomerOrderPrototype = orderPrototypes.FirstOrDefault(x => x.Id == subscription.CustomerOrderPrototypeId);
                    }
                    if (!subscriptionOrders.IsNullOrEmpty())
                    {
                        subscription.CustomerOrders = subscriptionOrders.Where(x => x.SubscriptionId == subscription.Id).ToList();
                        subscription.CustomerOrdersIds = subscription.CustomerOrders.Select(x => x.Id).ToArray();
                    }

                    cacheEntry.AddExpirationToken(SubscriptionCacheRegion.CreateChangeToken(subscription));
                }

                return retVal.ToArray();
            }));
        }
Beispiel #30
0
        public virtual async Task <ChangeLogSearchResult> SearchAsync(ChangeLogSearchCriteria criteria)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(SearchAsync), criteria.GetCacheKey());
            var result   = await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(ChangeLogCacheRegion.CreateChangeToken());
                var searchResult = AbstractTypeFactory <ChangeLogSearchResult> .TryCreateInstance();

                using (var repository = _repositoryFactory())
                {
                    repository.DisableChangesTracking();

                    var sortInfos = GetSortInfos(criteria);
                    var query     = GetQuery(repository, criteria, sortInfos);

                    searchResult.TotalCount = await query.CountAsync();
                    if (criteria.Take > 0)
                    {
                        searchResult.Results = (await query.AsNoTracking().Skip(criteria.Skip).Take(criteria.Take).ToArrayAsync()).Select(x => x.ToModel(AbstractTypeFactory <OperationLog> .TryCreateInstance())).ToList();
                    }
                }
                return(searchResult);
            });

            return(result);
        }