Ejemplo n.º 1
0
        private static PlatformMemoryCache GetPlatformMemoryCache()
        {
            var memoryCache         = new MemoryCache(Options.Create(new MemoryCacheOptions()));
            var platformMemoryCache = new PlatformMemoryCache(memoryCache, Options.Create(new CachingOptions()), new Mock <ILogger <PlatformMemoryCache> >().Object);

            return(platformMemoryCache);
        }
        private RegisteredEventService GetRegisteredEventService()
        {
            var memoryCache         = new MemoryCache(Options.Create(new MemoryCacheOptions()));
            var platformMemoryCache = new PlatformMemoryCache(memoryCache, Options.Create(new CachingOptions()), new Mock <ILogger <PlatformMemoryCache> >().Object);

            return(new RegisteredEventService(platformMemoryCache));
        }
Ejemplo n.º 3
0
        public virtual async Task <GenericSearchResult <InventoryInfo> > SearchInventoriesAsync(InventorySearchCriteria criteria)
        {
            var cacheKey = CacheKey.With(GetType(), "SearchInventoriesAsync", criteria.GetCacheKey());

            return(await PlatformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(InventorySearchCacheRegion.CreateChangeToken());
                var result = new GenericSearchResult <InventoryInfo>();
                using (var repository = RepositoryFactory())
                {
                    repository.DisableChangesTracking();

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

                    result.TotalCount = await query.CountAsync();
                    if (criteria.Take > 0)
                    {
                        var inventoryIds = await query.Select(x => x.Id).Skip(criteria.Skip).Take(criteria.Take).ToArrayAsync();
                        result.Results = (await InventoryService.GetByIdsAsync(inventoryIds, criteria.ResponseGroup)).AsQueryable().OrderBySortInfos(sortInfos).ToArray();
                    }
                }
                return result;
            }));
        }
Ejemplo n.º 4
0
        public virtual async Task <GenericSearchResult <Store> > SearchStoresAsync(StoreSearchCriteria criteria)
        {
            var cacheKey = CacheKey.With(GetType(), "SearchStoresAsync", criteria.GetCacheKey());

            return(await PlatformMemoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(StoreSearchCacheRegion.CreateChangeToken());
                var result = new GenericSearchResult <Store>();
                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;
            }));
        }
Ejemplo n.º 5
0
        private NotificationService GetNotificationServiceWithPlatformMemoryCache()
        {
            var memoryCache         = new MemoryCache(Options.Create(new MemoryCacheOptions()));
            var platformMemoryCache = new PlatformMemoryCache(memoryCache, Options.Create(new CachingOptions()), new Mock <ILogger <PlatformMemoryCache> >().Object);

            return(GetNotificationService(platformMemoryCache));
        }
        private CouponService GetCouponServiceImplWithPlatformMemoryCache()
        {
            var memoryCache         = new MemoryCache(Options.Create(new MemoryCacheOptions()));
            var platformMemoryCache = new PlatformMemoryCache(memoryCache, Options.Create(new CachingOptions()), new Mock <ILogger <PlatformMemoryCache> >().Object);

            _repositoryMock.Setup(ss => ss.UnitOfWork).Returns(_unitOfWorkMock.Object);

            return(GetCouponService(platformMemoryCache, _repositoryMock.Object));
        }
        private PaymentPlanService GetPaymentPlanServiceWithPlatformMemoryCache()
        {
            var memoryCache         = new MemoryCache(Options.Create(new MemoryCacheOptions()));
            var platformMemoryCache = new PlatformMemoryCache(memoryCache, Options.Create(new CachingOptions()), new Mock <ILogger <PlatformMemoryCache> >().Object);

            _subscriptionRepositoryFactoryMock.Setup(ss => ss.UnitOfWork).Returns(_unitOfWorkMock.Object);

            return(GetPaymentPlanService(platformMemoryCache));
        }
        private ShoppingCartService GetCustomerOrderServiceWithPlatformMemoryCache()
        {
            var memoryCache         = new MemoryCache(Options.Create(new MemoryCacheOptions()));
            var platformMemoryCache = new PlatformMemoryCache(memoryCache, Options.Create(new CachingOptions()), new Mock <ILogger <PlatformMemoryCache> >().Object);

            _cartRepositoryMock.Setup(ss => ss.UnitOfWork).Returns(_mockUnitOfWork.Object);

            return(GetShoppingCartService(platformMemoryCache));
        }
Ejemplo n.º 9
0
        private MemberService GetMemberServiceWithPlatformMemoryCache()
        {
            _userSearchServiceMock.Setup(x => x.SearchUsersAsync(It.IsAny <UserSearchCriteria>()))
            .ReturnsAsync(new UserSearchResult());

            var memoryCache         = new MemoryCache(Options.Create(new MemoryCacheOptions()));
            var platformMemoryCache = new PlatformMemoryCache(memoryCache, Options.Create(new CachingOptions()), new Mock <ILogger <PlatformMemoryCache> >().Object);

            return(GetMemberService(platformMemoryCache));
        }
Ejemplo n.º 10
0
        private AssociationService CreateDynamicAssociationService()
        {
            var memoryCache         = new MemoryCache(Options.Create(new MemoryCacheOptions()));
            var platformMemoryCache = new PlatformMemoryCache(memoryCache, Options.Create(new CachingOptions()), new Mock <ILogger <PlatformMemoryCache> >().Object);

            _dynamicAssociationsRepository.Setup(x => x.UnitOfWork).Returns(_unityOfWorkMock.Object);

            var result = new AssociationService(() => _dynamicAssociationsRepository.Object, platformMemoryCache, _eventPublisherMock.Object);

            return(result);
        }
        private static IMarketingPromoEvaluator GetPromotionEvaluationPolicy(IEnumerable <Promotion> promotions)
        {
            var result = new PromotionSearchResult
            {
                Results = promotions.ToList()
            };

            var promoSearchServiceMock = new Mock <IPromotionSearchService>();

            promoSearchServiceMock.Setup(x => x.SearchPromotionsAsync(It.IsAny <PromotionSearchCriteria>())).ReturnsAsync(result);

            var memoryCache         = new MemoryCache(Options.Create(new MemoryCacheOptions()));
            var platformMemoryCache = new PlatformMemoryCache(memoryCache, Options.Create(new CachingOptions()), new Mock <ILogger <PlatformMemoryCache> >().Object);

            return(new BestRewardPromotionPolicy(promoSearchServiceMock.Object, platformMemoryCache));
        }
        public void DefaultCachingOptions_Are_Applied()
        {
            var defaultOptions = Options.Create(new CachingOptions()
            {
                CacheSlidingExpiration = TimeSpan.FromMilliseconds(10)
            });
            var logger = new Moq.Mock <ILogger <PlatformMemoryCache> >();
            var sut    = new PlatformMemoryCache(CreateCache(), defaultOptions, logger.Object);

            sut.GetOrCreateExclusive("test-key", cacheOptions =>
            {
                Assert.Equal(cacheOptions.SlidingExpiration, TimeSpan.FromMilliseconds(10));
                return(1);
            });
            Thread.Sleep(100);
            var result = sut.GetOrCreateExclusive("test-key", cacheOptions =>
            {
                return(2);
            });

            Assert.Equal(2, result);
        }
        public PolicyBenchmark()
        {
            // Register discriminators for promotion rewards to allow custom jsonconverters work correctly
            PolymorphJsonConverter.RegisterTypeForDiscriminator(typeof(PromotionReward), nameof(PromotionReward.Id));

            // Register the resulting trees expressions into the AbstractFactory<IConditionTree> to allow custom jsonconverters work correctly
            foreach (var conditionTree in AbstractTypeFactory <PromotionConditionAndRewardTreePrototype> .TryCreateInstance().Traverse <IConditionTree>(x => x.AvailableChildren))
            {
                AbstractTypeFactory <IConditionTree> .RegisterType(conditionTree.GetType());
            }
            foreach (var conditionTree in AbstractTypeFactory <DynamicContentConditionTreePrototype> .TryCreateInstance().Traverse <IConditionTree>(x => x.AvailableChildren))
            {
                AbstractTypeFactory <IConditionTree> .RegisterType(conditionTree.GetType());
            }

            // Create disabled memory cache to test full calculations every policy call
            var memoryCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));

            disabledPlatformMemoryCache = new PlatformMemoryCache(memoryCache, Options.Create(new CachingOptions()
            {
                CacheEnabled = false
            }), new Mock <ILogger <PlatformMemoryCache> >().Object);


            // Mock evaluation context from pctx_mock.json file
            pCtx = MockPromotionEvaluationContext();

            // Mock promotions from promotions_mock.json file
            // If you want to have jsons like this from live system to benchmark different promotions combination, just call
            // in marketing module debug:
            // JsonConvert.SerializeObject(dynamicPromotion.DynamicExpression, new ConditionJsonConverter(doNotSerializeAvailCondition: true))
            // in immediate or watch
            promoSearchServiceMock = new Moq.Mock <IPromotionSearchService>();
            promoSearchServiceMock.Setup(x => x.SearchPromotionsAsync(It.IsAny <PromotionSearchCriteria>())).ReturnsAsync(MockPromotionSearchResult());


            _bestRewardPolicy = GetBestRewardPromotionPolicy();
            _stackablePolicy  = GetCombineStackablePromotionPolicy();
        }
Ejemplo n.º 14
0
        public async Task <GenericSearchResult <ShoppingCart> > SearchCartAsync(ShoppingCartSearchCriteria criteria)
        {
            var retVal   = new GenericSearchResult <ShoppingCart>();
            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;
                }
            }));
        }
Ejemplo n.º 15
0
        public static CustomUserManager TestCustomUserManager(Mock <IUserStore <ApplicationUser> > storeMock = null,
                                                              UserOptionsExtended userOptions = null, IdentityOptions identityOptions = null, PlatformMemoryCache platformMemoryCache = null, IEventPublisher eventPublisher = null, Func <ISecurityRepository> repositoryFactory = null, Mock <IUserPasswordHasher> passwordHasher = null)
        {
            storeMock ??= new Mock <IUserStore <ApplicationUser> >();
            storeMock.As <IUserRoleStore <ApplicationUser> >()
            .Setup(x => x.GetRolesAsync(It.IsAny <ApplicationUser>(), CancellationToken.None))
            .ReturnsAsync(Array.Empty <string>());
            storeMock.As <IUserLoginStore <ApplicationUser> >()
            .Setup(x => x.GetLoginsAsync(It.IsAny <ApplicationUser>(), CancellationToken.None))
            .ReturnsAsync(Array.Empty <UserLoginInfo>());
            storeMock.Setup(x => x.UpdateAsync(It.IsAny <ApplicationUser>(), CancellationToken.None))
            .ReturnsAsync(IdentityResult.Success);

            var identityOptionsMock = new Mock <IOptions <IdentityOptions> >();

            if (identityOptions != null)
            {
                identityOptionsMock.Setup(o => o.Value).Returns(identityOptions);
            }

            if (passwordHasher == null)
            {
                passwordHasher = new Mock <IUserPasswordHasher>();
                passwordHasher.Setup(x => x.VerifyHashedPassword(It.IsAny <ApplicationUser>(), It.IsAny <string>(), It.IsAny <string>()))
                .Returns(PasswordVerificationResult.Success);
            }

            userOptions ??= new UserOptionsExtended
            {
                MaxPasswordAge = new TimeSpan(0)
            };
            var userOptionsMock = new Mock <IOptions <UserOptionsExtended> >();

            userOptionsMock.Setup(o => o.Value).Returns(userOptions);
            var userValidators = new List <IUserValidator <ApplicationUser> >();
            var validator      = new Mock <IUserValidator <ApplicationUser> >();

            userValidators.Add(validator.Object);

            repositoryFactory ??= () => Mock.Of <ISecurityRepository>();
            var passwordOptionsMock = new Mock <IOptions <PasswordOptionsExtended> >();

            passwordOptionsMock.Setup(o => o.Value).Returns(new PasswordOptionsExtended());

            var pwdValidators = new PasswordValidator <ApplicationUser>[] { new CustomPasswordValidator(new CustomIdentityErrorDescriber(), repositoryFactory, passwordHasher.Object, passwordOptionsMock.Object) };

            var roleManagerMock = new Mock <RoleManager <Role> >(Mock.Of <IRoleStore <Role> >(),
                                                                 new[] { Mock.Of <IRoleValidator <Role> >() },
                                                                 Mock.Of <ILookupNormalizer>(),
                                                                 Mock.Of <IdentityErrorDescriber>(),
                                                                 Mock.Of <ILogger <RoleManager <Role> > >());

            var userManager = new CustomUserManager(storeMock.Object,
                                                    identityOptionsMock.Object,
                                                    passwordHasher.Object,
                                                    passwordHasher.Object,
                                                    userOptionsMock.Object,
                                                    userValidators,
                                                    pwdValidators,
                                                    Mock.Of <ILookupNormalizer>(),
                                                    Mock.Of <IdentityErrorDescriber>(),
                                                    Mock.Of <IServiceProvider>(),
                                                    Mock.Of <ILogger <UserManager <ApplicationUser> > >(),
                                                    roleManagerMock.Object,
                                                    platformMemoryCache ?? Mock.Of <IPlatformMemoryCache>(),
                                                    eventPublisher,
                                                    repositoryFactory,
                                                    passwordOptionsMock.Object);

            validator.Setup(x => x.ValidateAsync(userManager, It.IsAny <ApplicationUser>()))
            .ReturnsAsync(IdentityResult.Success).Verifiable();
            return(userManager);
        }