Exemplo n.º 1
0
        /// <summary>
        /// Render template by content and parameters
        /// </summary>
        /// <param name="templateContent"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public string RenderTemplate(string templateContent, Dictionary <string, object> parameters)
        {
            if (String.IsNullOrEmpty(templateContent))
            {
                return(templateContent);
            }
            if (parameters == null)
            {
                parameters = new Dictionary <string, object>();
            }

            Template.FileSystem = this;

            var renderParams = new RenderParameters()
            {
                LocalVariables = Hash.FromDictionary(parameters)
            };

            var parsedTemplate = _cacheManager.Get(GetCacheKey("ParseTemplate", templateContent.GetHashCode().ToString()), "LiquidTheme", () => { return(Template.Parse(templateContent)); });

            var retVal = parsedTemplate.RenderWithTracing(renderParams);

            //Copy key values which were generated in rendering to out parameters
            if (parameters != null && parsedTemplate.Registers != null)
            {
                foreach (var registerPair in parsedTemplate.Registers)
                {
                    parameters[registerPair.Key] = registerPair.Value;
                }
            }

            return(retVal);
        }
        /// <summary>
        /// Read shopify theme settings from 'config' folder
        /// </summary>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public IDictionary GetSettings(string defaultValue = null)
        {
            return(_cacheManager.Get(GetCacheKey("GetSettings", defaultValue), "LiquidThemeRegion", () =>
            {
                var retVal = new DefaultableDictionary(defaultValue);
                //Read first settings from global theme
                var resultSettings = InnerGetSettings(_globalThemeBlobProvider, "");
                //Then load from current theme
                var currentThemeSettings = InnerGetSettings(_themeBlobProvider, CurrentThemePath);
                if (currentThemeSettings != null)
                {
                    if (resultSettings == null) // if there is no default settings, use just current theme
                    {
                        resultSettings = currentThemeSettings;
                    }
                    else
                    {
                        resultSettings.Merge(currentThemeSettings, new JsonMergeSettings {
                            MergeArrayHandling = MergeArrayHandling.Merge
                        });
                    }
                }


                if (resultSettings != null)
                {
                    var dict = resultSettings.ToObject <Dictionary <string, object> >().ToDictionary(x => x.Key, x => x.Value);
                    retVal = new DefaultableDictionary(dict, defaultValue);
                }

                return retVal;
            }));
        }
 /// <summary>
 /// Return hash of requested asset (used for file versioning)
 /// </summary>
 /// <param name="filePath"></param>
 /// <returns></returns>
 public string GetAssetHash(string filePath)
 {
     return(_cacheManager.Get(GetCacheKey("GetAssetHash", filePath), "LiquidThemeRegion", () =>
     {
         using (var stream = GetAssetStream(filePath))
         {
             var hashAlgorithm = CryptoConfig.AllowOnlyFipsAlgorithms ? (SHA256) new SHA256CryptoServiceProvider() : new SHA256Managed();
             return HttpServerUtility.UrlTokenEncode(hashAlgorithm.ComputeHash(stream));
         }
     }));
 }
Exemplo n.º 4
0
        protected virtual IList <coreDto.SeoInfo> GetAllSeoRecords(string slug)
        {
            var result = new List <coreDto.SeoInfo>();

            if (!string.IsNullOrEmpty(slug))
            {
                var coreApi   = _coreApiFactory();
                var apiResult = _cacheManager.Get(string.Join(":", "Commerce.GetSeoInfoBySlug", slug), "ApiRegion", () => coreApi.Commerce.GetSeoInfoBySlug(slug));
                result.AddRange(apiResult);
            }

            return(result);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Read shopify theme settings from 'config' folder
        /// </summary>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public IDictionary GetSettings(string defaultValue = null)
        {
            return(_cacheManager.Get(GetCacheKey("GetSettings", defaultValue), "LiquidThemeRegion", () =>
            {
                var retVal = new DefaultableDictionary(defaultValue);

                //Load all data from current theme config
                var currentThemeSettings = InnerGetAllSettings(_themeBlobProvider, CurrentThemePath);

                //Load all data from global theme config
                var resultSettings = InnerGetAllSettings(_globalThemeBlobProvider, string.Empty);

                if (currentThemeSettings != null)
                {
                    //Merge two configs
                    resultSettings.Merge(currentThemeSettings, new JsonMergeSettings {
                        MergeArrayHandling = MergeArrayHandling.Merge
                    });
                }

                //Get actual preset from merged config
                var currentPreset = resultSettings.GetValue("current");
                if (currentPreset is JValue)
                {
                    string currentPresetName = ((JValue)currentPreset).Value.ToString();
                    var presets = resultSettings.GetValue("presets") as JObject;
                    if (presets == null || !presets.Children().Any())
                    {
                        throw new StorefrontException("Setting presets not defined");
                    }

                    IList <JProperty> allPresets = presets.Children().Cast <JProperty>().ToList();
                    resultSettings = allPresets.FirstOrDefault(p => p.Name == currentPresetName).Value as JObject;
                    if (resultSettings == null)
                    {
                        throw new StorefrontException($"Setting preset with name '{currentPresetName}' not found");
                    }
                }
                if (currentPreset is JObject)
                {
                    resultSettings = (JObject)currentPreset;
                }

                var dict = resultSettings.ToObject <Dictionary <string, object> >().ToDictionary(x => x.Key, x => x.Value);
                retVal = new DefaultableDictionary(dict, defaultValue);

                return retVal;
            }));
        }
Exemplo n.º 6
0
        protected virtual IMutablePagedList <QuoteRequest> GetCustomerQuotes(CustomerInfo customer)
        {
            var workContext = _workContextFactory();
            Func <int, int, IEnumerable <SortInfo>, IPagedList <QuoteRequest> > quotesGetter = (pageNumber, pageSize, sortInfos) =>
            {
                var quoteSearchCriteria = new quoteDto.QuoteRequestSearchCriteria
                {
                    Take       = pageSize,
                    CustomerId = customer.Id,
                    Skip       = (pageNumber - 1) * pageSize,
                    StoreId    = workContext.CurrentStore.Id
                };
                var cacheKey = "GetCustomerQuotes-" + quoteSearchCriteria.GetHashCode();
                var quoteRequestsResponse = _cacheManager.Get(cacheKey, string.Format(_customerQuotesCacheRegionFormat, customer.Id), () => _quoteApi.QuoteModule.Search(quoteSearchCriteria));
                return(new StaticPagedList <QuoteRequest>(quoteRequestsResponse.QuoteRequests.Select(x => x.ToQuoteRequest(workContext.AllCurrencies, workContext.CurrentLanguage)),
                                                          pageNumber, pageSize, quoteRequestsResponse.TotalCount.Value));
            };

            return(new MutablePagedList <QuoteRequest>(quotesGetter, 1, QuoteSearchCriteria.DefaultPageSize));
        }
Exemplo n.º 7
0
        private List <VirtoCommerceDomainCommerceModelSeoInfo> GetSeoRecords(string slug)
        {
            var seoRecords = new List <VirtoCommerceDomainCommerceModelSeoInfo>();

            if (!string.IsNullOrEmpty(slug))
            {
                seoRecords = _cacheManager.Get(string.Join(":", "CommerceGetSeoInfoBySlug", slug), "ApiRegion", () => _commerceCoreApi.CommerceGetSeoInfoBySlug(slug));
            }

            return(seoRecords);
        }
Exemplo n.º 8
0
        private IMutablePagedList <QuoteRequest> GetCustomerQuotes(CustomerInfo customer)
        {
            var workContext = _workContextFactory();
            Func <int, int, IPagedList <QuoteRequest> > quotesGetter = (pageNumber, pageSize) =>
            {
                var quoteSearchCriteria = new QuoteModule.Client.Model.QuoteRequestSearchCriteria
                {
                    Count      = pageSize,
                    CustomerId = customer.Id,
                    Start      = (pageNumber - 1) * pageSize,
                    StoreId    = workContext.CurrentStore.Id
                };
                var cacheKey = "GetCustomerQuotes-" + quoteSearchCriteria.GetHashCode();
                var quoteRequestsResponse = _cacheManager.Get(cacheKey, string.Format(_customerQuotesCacheRegionFormat, customer.Id), () => _quoteApi.QuoteModuleSearch(quoteSearchCriteria));
                return(new StaticPagedList <QuoteRequest>(quoteRequestsResponse.QuoteRequests.Select(x => x.ToWebModel(workContext.AllCurrencies, workContext.CurrentLanguage)),
                                                          pageNumber, pageSize, quoteRequestsResponse.TotalCount.Value));
            };

            return(new MutablePagedList <QuoteRequest>(quotesGetter));
        }
Exemplo n.º 9
0
        private List <catalogModel.SeoInfo> GetSeoRecords(string slug)
        {
            var seoRecords = new List <catalogModel.SeoInfo>();

            if (!string.IsNullOrEmpty(slug))
            {
                seoRecords = _cacheManager.Get(string.Join(":", "CommerceGetSeoInfoBySlug", slug), "ApiRegion", () =>
                                               _commerceCoreApi.CommerceGetSeoInfoBySlug(slug).Select(s => s.ToCatalogModel()).ToList());
            }

            return(seoRecords);
        }
        public override async Task Invoke(IOwinContext context)
        {
            if (IsStorefrontRequest(context.Request))
            {
                var workContext = _container.Resolve <WorkContext>();

                var linkListService      = _container.Resolve <IMenuLinkListService>();
                var cartBuilder          = _container.Resolve <ICartBuilder>();
                var catalogSearchService = _container.Resolve <ICatalogSearchService>();

                // Initialize common properties
                workContext.RequestUrl   = context.Request.Uri;
                workContext.AllCountries = _allCountries;
                workContext.AllStores    = await _cacheManager.GetAsync("GetAllStores", "ApiRegion", async() => await GetAllStoresAsync());

                if (workContext.AllStores != null && workContext.AllStores.Any())
                {
                    // Initialize request specific properties
                    workContext.CurrentStore    = GetStore(context, workContext.AllStores);
                    workContext.CurrentLanguage = GetLanguage(context, workContext.AllStores, workContext.CurrentStore);
                    workContext.AllCurrencies   = await _cacheManager.GetAsync("GetAllCurrencies-" + workContext.CurrentLanguage.CultureName, "ApiRegion", async() => { return((await _commerceApi.CommerceGetAllCurrenciesAsync()).Select(x => x.ToWebModel(workContext.CurrentLanguage)).ToArray()); });

                    //Sync store currencies with avail in system
                    foreach (var store in workContext.AllStores)
                    {
                        store.SyncCurrencies(workContext.AllCurrencies, workContext.CurrentLanguage);
                        store.CurrentSeoInfo = store.SeoInfos.FirstOrDefault(x => x.Language == workContext.CurrentLanguage);
                    }

                    //Set current currency
                    workContext.CurrentCurrency = GetCurrency(context, workContext.CurrentStore);

                    var qs = HttpUtility.ParseQueryString(workContext.RequestUrl.Query);
                    //Initialize catalog search criteria
                    workContext.CurrentCatalogSearchCriteria = new CatalogSearchCriteria(workContext.CurrentLanguage, workContext.CurrentCurrency, qs)
                    {
                        CatalogId = workContext.CurrentStore.Catalog
                    };

                    //This line make delay categories loading initialization (categories can be evaluated on view rendering time)
                    workContext.Categories = new MutablePagedList <Category>((pageNumber, pageSize) =>
                    {
                        var criteria        = workContext.CurrentCatalogSearchCriteria.Clone();
                        criteria.PageNumber = pageNumber;
                        criteria.PageSize   = pageSize;
                        var result          = catalogSearchService.SearchCategories(criteria);
                        foreach (var category in result)
                        {
                            category.Products = new MutablePagedList <Product>((pageNumber2, pageSize2) =>
                            {
                                criteria.CategoryId = category.Id;
                                criteria.PageNumber = pageNumber2;
                                criteria.PageSize   = pageSize2;
                                var searchResult    = catalogSearchService.SearchProducts(criteria);
                                //Because catalog search products returns also aggregations we can use it to populate workContext using C# closure
                                //now workContext.Aggregation will be contains preloaded aggregations for current category
                                workContext.Aggregations = new MutablePagedList <Aggregation>(searchResult.Aggregations);
                                return(searchResult.Products);
                            });
                        }
                        return(result);
                    });
                    //This line make delay products loading initialization (products can be evaluated on view rendering time)
                    workContext.Products = new MutablePagedList <Product>((pageNumber, pageSize) =>
                    {
                        var criteria        = workContext.CurrentCatalogSearchCriteria.Clone();
                        criteria.PageNumber = pageNumber;
                        criteria.PageSize   = pageSize;

                        var result = catalogSearchService.SearchProducts(criteria);
                        //Prevent double api request for get aggregations
                        //Because catalog search products returns also aggregations we can use it to populate workContext using C# closure
                        //now workContext.Aggregation will be contains preloaded aggregations for current search criteria
                        workContext.Aggregations = new MutablePagedList <Aggregation>(result.Aggregations);
                        return(result.Products);
                    });
                    //This line make delay aggregation loading initialization (aggregation can be evaluated on view rendering time)
                    workContext.Aggregations = new MutablePagedList <Aggregation>((pageNumber, pageSize) =>
                    {
                        var criteria        = workContext.CurrentCatalogSearchCriteria.Clone();
                        criteria.PageNumber = pageNumber;
                        criteria.PageSize   = pageSize;
                        //Force to load products and its also populate workContext.Aggregations by preloaded values
                        workContext.Products.Slice(pageNumber, pageSize);
                        return(workContext.Aggregations);
                    });

                    workContext.CurrentOrderSearchCriteria = new Model.Order.OrderSearchCriteria(qs);
                    workContext.CurrentQuoteSearchCriteria = new Model.Quote.QuoteSearchCriteria(qs);

                    //Get current customer
                    workContext.CurrentCustomer = await GetCustomerAsync(context);

                    //Validate that current customer has to store access
                    ValidateUserStoreLogin(context, workContext.CurrentCustomer, workContext.CurrentStore);
                    MaintainAnonymousCustomerCookie(context, workContext);

                    // Gets the collection of external login providers
                    var externalAuthTypes = context.Authentication.GetExternalAuthenticationTypes();

                    workContext.ExternalLoginProviders = externalAuthTypes.Select(at => new LoginProvider
                    {
                        AuthenticationType = at.AuthenticationType,
                        Caption            = at.Caption,
                        Properties         = at.Properties
                    }).ToList();

                    workContext.ApplicationSettings = GetApplicationSettings();

                    //Do not load shopping cart and other for resource requests
                    if (!IsAssetRequest(context.Request))
                    {
                        //Shopping cart
                        await cartBuilder.GetOrCreateNewTransientCartAsync(workContext.CurrentStore, workContext.CurrentCustomer, workContext.CurrentLanguage, workContext.CurrentCurrency);

                        workContext.CurrentCart = cartBuilder.Cart;

                        if (workContext.CurrentStore.QuotesEnabled)
                        {
                            await _quoteRequestBuilder.GetOrCreateNewTransientQuoteRequestAsync(workContext.CurrentStore, workContext.CurrentCustomer, workContext.CurrentLanguage, workContext.CurrentCurrency);

                            workContext.CurrentQuoteRequest = _quoteRequestBuilder.QuoteRequest;
                        }

                        var linkLists = await _cacheManager.GetAsync("GetAllStoreLinkLists-" + workContext.CurrentStore.Id, "ApiRegion", async() => await linkListService.LoadAllStoreLinkListsAsync(workContext.CurrentStore.Id));

                        workContext.CurrentLinkLists = linkLists.Where(x => x.Language == workContext.CurrentLanguage).ToList();
                        // load all static content
                        var staticContents = _cacheManager.Get(string.Join(":", "AllStoreStaticContent", workContext.CurrentStore.Id), "ContentRegion", () =>
                        {
                            var allContentItems   = _staticContentService.LoadStoreStaticContent(workContext.CurrentStore).ToList();
                            var blogs             = allContentItems.OfType <Blog>().ToArray();
                            var blogArticlesGroup = allContentItems.OfType <BlogArticle>().GroupBy(x => x.BlogName, x => x).ToList();

                            foreach (var blog in blogs)
                            {
                                var blogArticles = blogArticlesGroup.FirstOrDefault(x => string.Equals(x.Key, blog.Name, StringComparison.OrdinalIgnoreCase));
                                if (blogArticles != null)
                                {
                                    blog.Articles = new MutablePagedList <BlogArticle>(blogArticles);
                                }
                            }

                            return(new { Pages = allContentItems, Blogs = blogs });
                        });
                        workContext.Pages = new MutablePagedList <ContentItem>(staticContents.Pages);
                        workContext.Blogs = new MutablePagedList <Blog>(staticContents.Blogs);

                        // Initialize blogs search criteria
                        workContext.CurrentBlogSearchCritera = new BlogSearchCriteria(qs);

                        //Pricelists
                        var pricelistCacheKey = string.Join("-", "EvaluatePriceLists", workContext.CurrentStore.Id, workContext.CurrentCustomer.Id);
                        workContext.CurrentPricelists = await _cacheManager.GetAsync(pricelistCacheKey, "ApiRegion", async() =>
                        {
                            var evalContext = new VirtoCommerceDomainPricingModelPriceEvaluationContext
                            {
                                StoreId    = workContext.CurrentStore.Id,
                                CatalogId  = workContext.CurrentStore.Catalog,
                                CustomerId = workContext.CurrentCustomer.Id,
                                Quantity   = 1
                            };
                            var pricingResult = await _pricingModuleApi.PricingModuleEvaluatePriceListsAsync(evalContext);
                            return(pricingResult.Select(p => p.ToWebModel()).ToList());
                        });
                    }
                }
            }

            await Next.Invoke(context);
        }
Exemplo n.º 11
0
        protected virtual async Task HandleNonAssetRequest(IOwinContext context, WorkContext workContext)
        {
            await InitializeShoppingCart(context, workContext);

            if (workContext.CurrentStore.QuotesEnabled)
            {
                var quoteRequestBuilder = Container.Resolve <IQuoteRequestBuilder>();
                await quoteRequestBuilder.GetOrCreateNewTransientQuoteRequestAsync(workContext.CurrentStore, workContext.CurrentCustomer, workContext.CurrentLanguage, workContext.CurrentCurrency);

                workContext.CurrentQuoteRequest = quoteRequestBuilder.QuoteRequest;
            }

            var linkListService = Container.Resolve <IMenuLinkListService>();
            var linkLists       = await CacheManager.GetAsync("GetAllStoreLinkLists-" + workContext.CurrentStore.Id, "ApiRegion", async() => await linkListService.LoadAllStoreLinkListsAsync(workContext.CurrentStore.Id));

            workContext.CurrentLinkLists = linkLists.GroupBy(x => x.Name).Select(x => x.FindWithLanguage(workContext.CurrentLanguage)).Where(x => x != null).ToList();

            // load all static content
            var staticContents = CacheManager.Get(string.Join(":", "AllStoreStaticContent", workContext.CurrentStore.Id), "ContentRegion", () =>
            {
                var staticContentService = Container.Resolve <IStaticContentService>();
                var allContentItems      = staticContentService.LoadStoreStaticContent(workContext.CurrentStore).ToList();
                var blogs             = allContentItems.OfType <Blog>().ToArray();
                var blogArticlesGroup = allContentItems.OfType <BlogArticle>().GroupBy(x => x.BlogName, x => x).ToList();

                foreach (var blog in blogs)
                {
                    var blogArticles = blogArticlesGroup.FirstOrDefault(x => string.Equals(x.Key, blog.Name, StringComparison.OrdinalIgnoreCase));
                    if (blogArticles != null)
                    {
                        blog.Articles = new MutablePagedList <BlogArticle>(blogArticles);
                    }
                }

                return(new { Pages = allContentItems, Blogs = blogs });
            });

            workContext.Pages = new MutablePagedList <ContentItem>(staticContents.Pages.Where(x => x.Language.IsInvariant || x.Language == workContext.CurrentLanguage));
            workContext.Blogs = new MutablePagedList <Blog>(staticContents.Blogs.Where(x => x.Language.IsInvariant || x.Language == workContext.CurrentLanguage));

            // Initialize blogs search criteria
            workContext.CurrentBlogSearchCritera = new BlogSearchCriteria(workContext.QueryString);

            //Pricelists
            var pricelistCacheKey = string.Join("-", "EvaluatePriceLists", workContext.CurrentStore.Id, workContext.CurrentCustomer.Id);

            workContext.CurrentPricelists = await CacheManager.GetAsync(pricelistCacheKey, "ApiRegion", async() =>
            {
                var evalContext      = workContext.ToPriceEvaluationContextDto();
                var pricingModuleApi = Container.Resolve <IPricingModuleApiClient>();
                var pricingResult    = await pricingModuleApi.PricingModule.EvaluatePriceListsAsync(evalContext);
                return(pricingResult.Select(p => p.ToPricelist(workContext.AllCurrencies, workContext.CurrentLanguage)).ToList());
            });

            // Vendors with their products
            workContext.Vendors = new MutablePagedList <Vendor>((pageNumber, pageSize, sortInfos) =>
            {
                var catalogSearchService = Container.Resolve <ICatalogSearchService>();
                var customerService      = Container.Resolve <ICustomerService>();
                var vendors = customerService.SearchVendors(null, pageNumber, pageSize, sortInfos);

                foreach (var vendor in vendors)
                {
                    vendor.Products = new MutablePagedList <Product>((pageNumber2, pageSize2, sortInfos2) =>
                    {
                        var criteria = new ProductSearchCriteria
                        {
                            VendorId      = vendor.Id,
                            PageNumber    = pageNumber2,
                            PageSize      = pageSize2,
                            ResponseGroup = workContext.CurrentProductSearchCriteria.ResponseGroup & ~ItemResponseGroup.ItemWithVendor,
                            SortBy        = SortInfo.ToString(sortInfos2),
                        };
                        var searchResult = catalogSearchService.SearchProducts(criteria);
                        return(searchResult.Products);
                    }, 1, ProductSearchCriteria.DefaultPageSize);
                }

                return(vendors);
            }, 1, VendorSearchCriteria.DefaultPageSize);
        }