Example #1
0
        public Task <VariantsResponce> Handle(VariantsRequest request, CancellationToken cancellationToken)
        {
            var variationReferences = _relationRepository.GetChildren <ProductVariation>(request.ProductReference);
            var variations          = _contentLoader.GetItems(variationReferences.Select(x => x.Child), new LoaderOptions {
                LanguageLoaderOption.FallbackWithMaster()
            }).OfType <MovieVariant>();

            var prices   = _customerPriceService.GetPrices(variations.Select(x => x.Code)).ToDictionary(x => x.CatalogKey.CatalogEntryCode, y => y);
            var discount = _customerPriceService.GetDiscountPrices(variations.Select(x => x.ContentLink)).ToDictionary(x => x.EntryLink, y => y.DiscountPrices);
            var result   = variations.Select(x => new Variant()
            {
                Code        = x.Code,
                Name        = x.Name,
                Primary     = x.IsPrimary,
                DisplayName = x.MediaTypes,
                NormalPrice = prices.GetPrice(x.Code),
                Discounts   = discount.GetDiscounts(x.ContentLink)
            }).ToList();

            var responce = new VariantsResponce()
            {
                Variants = result
            };

            if (string.IsNullOrEmpty(request.CurrentVariantCode))
            {
                responce.ActiveVariant = result.Where(x => x.Primary).FirstOrDefault();
            }
            else
            {
                responce.ActiveVariant = result.Where(x => x.Code == request.CurrentVariantCode).FirstOrDefault();
            }
            return(Task.FromResult(responce));
        }
        /// <summary>
        /// Gets all variant ids.
        /// </summary>
        /// <returns>An IEnumerable of ids.</returns>
        private IEnumerable <int> GetAllVariantIds()
        {
            List <int> variantIdList = new List <int>();

            IEnumerable <CatalogContent> catalogs = this.contentLoader.GetChildren <CatalogContent>(
                this.referenceConverter.GetRootLink(),
                new LoaderOptions {
                LanguageLoaderOption.MasterLanguage()
            });

            foreach (CatalogContent catalogContent in catalogs)
            {
                if (this.stopSignaled)
                {
                    break;
                }

                foreach (VariationContent variant in this.GetEntriesRecursive <VariationContent>(
                             parentLink: catalogContent.ContentLink,
                             defaultCulture: catalogContent.MasterLanguage))
                {
                    if (this.stopSignaled)
                    {
                        break;
                    }

                    variantIdList.Add(item: this.referenceConverter.GetObjectId(variant.ContentLink));
                }
            }

            return(variantIdList.Distinct());
        }
        private LoaderOptions CreateDefaultListOption()
        {
            LoaderOptions loaderOptions = new LoaderOptions();

            loaderOptions.Add <LanguageLoaderOption>(LanguageLoaderOption.Fallback(_languageAccessor.Language));
            return(loaderOptions);
        }
Example #4
0
 protected virtual LoaderOptions CreateDefaultListOptions()
 {
     return(new LoaderOptions
     {
         LanguageLoaderOption.Fallback(LanguageResolver.GetPreferredCulture())
     });
 }
 public IEnumerable <T> GetChildrenWithReviews <T>(ContentReference contentLink, CultureInfo language) where T : IContentData
 {
     return(GetChildrenWithReviews <T>(contentLink, new LoaderOptions()
     {
         LanguageLoaderOption.Specific(language)
     }, -1, -1));
 }
Example #6
0
        private static IContent GetOrAddLocalizationPage(string[] normalizedKey, CultureInfo culture)
        {
            var localizationPage = LocalizationPageService.Service.GetLocalizationPage(normalizedKey,
                                                                                       new LoaderOptions()
            {
                LanguageLoaderOption.FallbackWithMaster(culture)
            });

            if (localizationPage == null && _updateContent)
            {
                lock (Lock)
                {
                    localizationPage = LocalizationPageService.Service.GetLocalizationPage(normalizedKey,
                                                                                           new LoaderOptions()
                    {
                        LanguageLoaderOption.FallbackWithMaster(culture)
                    });

                    if (localizationPage == null)
                    {
                        localizationPage = LocalizationPageService.Service.AddLocalizationPage(normalizedKey);
                    }
                }
            }

            return(localizationPage);
        }
Example #7
0
        public override IEnumerable <ResourceItem> GetAllStrings(string originalKey, string[] normalizedKey, CultureInfo culture)
        {
            // the default provider returns null also for episerver labels so we need to prefix the custom labels.
            if (!IsSupportedKey(normalizedKey))
            {
                yield break;
            }

            // TODO if the normalizedkey length is 1 we need to loop through all the pages and return the result

            var localizationPage = LocalizationPageService.Service.GetLocalizationPage(normalizedKey, new LoaderOptions()
            {
                LanguageLoaderOption.FallbackWithMaster(culture)
            });

            if (localizationPage == null)
            {
                yield break;
            }

            var path = originalKey[originalKey.Length - 1].Equals('/') ? originalKey : originalKey + "/";

            foreach (
                var property in
                ServiceLocator.Current.GetInstance <IContentTypeRepository>()
                .Load(localizationPage.ContentTypeID)
                .PropertyDefinitions.Where(x => x.HelpText.Contains(path)))
            {
                yield return(new ResourceItem(property.HelpText, (string)localizationPage.Property[property.Name].Value, culture));
            }
        }
Example #8
0
        public TTarget GetContent <TTarget>(DocumentIndexModel indexItem, bool filterOnCulture = true) where TTarget : ContentData
        {
            if (indexItem == null || string.IsNullOrEmpty(indexItem.Id))
            {
                return(default(TTarget));
            }
            Guid result;

            if (Guid.TryParse(((IEnumerable <string>)indexItem.Id.Split('|')).FirstOrDefault <string>(), out result))
            {
                LoaderOptions loaderOptions;
                if (filterOnCulture)
                {
                    loaderOptions = this.GetLoaderOptions(indexItem.Language);
                }
                else
                {
                    loaderOptions = new LoaderOptions();
                    loaderOptions.Add <LanguageLoaderOption>(LanguageLoaderOption.Fallback((CultureInfo)null));
                }
                LoaderOptions settings = loaderOptions;
                TTarget       content  = null;
                this._contentRepository.TryGet <TTarget>(result, settings, out content);
                return(content);
            }
            return(default(TTarget));
        }
Example #9
0
        public static MvcHtmlString ResizedPicture(this HtmlHelper helper,
                                                   ContentReference image,
                                                   PictureProfile profile,
                                                   string fallbackUrl = null,
                                                   ResizedPictureViewModel pictureModel = null)
        {
            if (pictureModel == null)
            {
                pictureModel = new ResizedPictureViewModel();
            }

            var imageFound = ServiceLocator.Current.GetInstance <IContentLoader>()
                             .TryGet <IContentData>(image, new LoaderOptions {
                LanguageLoaderOption.FallbackWithMaster()
            },
                                                    out var content) &&
                             content is IImage;

            var baseUrl = imageFound
                ? ResolveImageUrl(image)
                : fallbackUrl;

            if (!pictureModel.ImgElementAttributes.ContainsKey("alt"))
            {
                var alternateText = imageFound
                    ? ((IImage)content).Description
                    : string.Empty;
                pictureModel.ImgElementAttributes.Add("alt", alternateText);
            }

            return(GenerateResizedPicture(baseUrl, profile, content as IResponsiveImage, pictureModel));
        }
        public virtual IEnumerable <T> GetReferencesToCategories <T>(IEnumerable <ContentReference> categories, CultureInfo culture) where T : ICategorizableContent, IContentData
        {
            var loaderOptions = new LoaderOptions {
                LanguageLoaderOption.Specific(culture)
            };

            return(GetReferencesToCategories <T>(categories, loaderOptions));
        }
        private LoaderOptions CreateDefaultLoadOption()
        {
            LoaderOptions loaderOptions = new LoaderOptions
            {
                LanguageLoaderOption.FallbackWithMaster(_languageAccessor.Language)
            };

            return(loaderOptions);
        }
Example #12
0
        public T GetFirstBySegment <T>(string urlSegment, CultureInfo culture) where T : CategoryData
        {
            var loaderOptions = new LoaderOptions
            {
                LanguageLoaderOption.Specific(culture)
            };

            return(GetFirstBySegment <T>(urlSegment, loaderOptions));
        }
        public IEnumerable <EnhancedStructureStoreContentDataModel> GetLatestVersions(IEnumerable <ContentReference> ids,
                                                                                      NameValueCollection queryString)
        {
            if (ids == null)
            {
                return(null);
            }

            var draftLinks = new List <ContentReference>();

            foreach (var id in ids)
            {
                if (_currentProject.ProjectId.HasValue)
                {
                    var projectReference = _projectContentResolver.GetProjectReference(id, _currentProject.ProjectId.Value);
                    draftLinks.Add(projectReference);
                    continue;
                }

                var content = _contentLoader.Get <IContent>(id) as IVersionable;
                if (content == null)
                {
                    draftLinks.Add(id);
                    continue;
                }

                if (content.Status == VersionStatus.Published)
                {
                    var contentVersion =
                        _contentVersionRepository.LoadCommonDraft(id, _languageResolver.GetPreferredCulture().Name);
                    if (contentVersion != null)
                    {
                        draftLinks.Add(contentVersion.ContentLink);
                        continue;
                    }
                }

                draftLinks.Add(id);
            }

            var contents = _contentLoader.GetItems(draftLinks,
                                                   new LoaderOptions {
                LanguageLoaderOption.FallbackWithMaster()
            });
            var queryParameters = new ContentQueryParameters
            {
                AllParameters    = queryString,
                CurrentPrincipal = PrincipalInfo.CurrentPrincipal
            };

            // The ContentVersionFilter modify content links.
            // We have to use this filter here to make sure that we will use proper links
            return(_contentStoreModelCreator
                   .CreateContentDataStoreModels <EnhancedStructureStoreContentDataModel>(contents, queryParameters).ToList());
        }
Example #14
0
        /// <summary>
        /// Gets a list of populated syndication items created from the dependent content references on the gived SyndicationFeedPage.
        /// </summary>
        /// <returns></returns>
        public IEnumerable <SyndicationItem> GetSyndicationItems()
        {
            var contentReferences = FeedContentResolver.GetContentReferences(FeedContext);
            var contentItems      = ContentLoader.GetItems(contentReferences, new LoaderOptions {
                LanguageLoaderOption.Fallback()
            });
            var filteredItems    = FeedFilterer.FilterSyndicationContent(contentItems, FeedContext);
            var syndicationItems = filteredItems.Select(CreateSyndicationItem).ToList();

            return(syndicationItems.OrderByDescending(c => c.LastUpdatedTime).Take(FeedContext.FeedPageType.MaximumItems));
        }
        public static IList <T> GetContentItems <T>(this IEnumerable <ContentAreaItem> contentAreaItems) where T : IContentData
        {
            if (contentAreaItems == null || !contentAreaItems.Any())
            {
                return(null);
            }

            return(_contentLoader.Value
                   .GetItems(contentAreaItems.Select(_ => _.ContentLink), new LoaderOptions {
                LanguageLoaderOption.FallbackWithMaster()
            })
                   .OfType <T>()
                   .ToList());
        }
Example #16
0
        private LoaderOptions GetLoaderOptions(string languageCode)
        {
            if (string.IsNullOrEmpty(languageCode))
            {
                LoaderOptions loaderOptions = new LoaderOptions();
                loaderOptions.Add <LanguageLoaderOption>(LanguageLoaderOption.FallbackWithMaster((CultureInfo)null));
                return(loaderOptions);
            }
            CultureInfo   language       = languageCode == "iv" ? CultureInfo.InvariantCulture : CultureInfo.GetCultureInfo(languageCode);
            LoaderOptions loaderOptions1 = new LoaderOptions();

            loaderOptions1.Add <LanguageLoaderOption>(LanguageLoaderOption.Specific(language));
            return(loaderOptions1);
        }
        public async Task <CartContentResponce> Handle(CartContentRequest request, CancellationToken cancellationToken)
        {
            var cart = _cartFactory.LoadOrCreateCart();

            var allLineItems  = cart.GetAllLineItems();
            var lineItemCodes = allLineItems.Select(x => x.Code).Distinct();
            var variants      = _contentLoader.GetItems(_referenceConverter.GetContentLinks(lineItemCodes).Select(x => x.Value), new LoaderOptions {
                LanguageLoaderOption.FallbackWithMaster()
            }).OfType <MovieVariant>();
            var prices    = _customerPriceService.GetPrices(variants.Select(x => x.Code)).ToDictionary(x => x.CatalogKey.CatalogEntryCode, x => x);
            var discounts = _customerPriceService.GetDiscountPrices(variants.Select(x => x.ContentLink)).ToDictionary(x => x.EntryLink, x => x);
            var products  = variants.Select(
                x => new
            {
                variant = x.ContentLink,
                product = _contentLoader.GetItems(x.GetParentProducts(), new LoaderOptions {
                    LanguageLoaderOption.FallbackWithMaster()
                }).OfType <MovieProduct>()
            }).ToDictionary(x => x.variant, x => x.product.FirstOrDefault());

            var lineItems = cart.GetAllLineItems().Select(x => new LineItem()
            {
                Code             = x.Code,
                DisplayName      = x.DisplayName,
                Quantity         = Convert.ToInt32(x.Quantity),
                ImageUrl         = "",//products[variants.Where(y => y.Code == x.Code).Select(y => y.ContentLink).First()].PosterPath,
                Price            = prices[x.Code].UnitPrice.ToString(),
                DiscountPrice    = discounts[variants.First(y => y.Code == x.Code).ContentLink].DiscountPrices.Last().Price.ToString(),
                ProductReference = products[variants.Where(y => y.Code == x.Code).Select(y => y.ContentLink).First()].ContentLink
            });

            var total            = _orderGroupCalculator.GetOrderGroupTotals(cart);
            var tax              = _orderGroupCalculator.GetTaxTotal(cart);
            var orderDiscount    = _orderGroupCalculator.GetOrderDiscountTotal(cart);
            var lineItemDiscount = new Money(cart.GetAllLineItems().Sum(x => x.GetEntryDiscount()), cart.Currency);
            var noDiscount       = new Money(allLineItems.Sum(x => prices[x.Code].UnitPrice.Amount * x.Quantity), cart.Currency);
            var model            = new CartContentResponce()
            {
                LineItems     = lineItems,
                Total         = total.Total.ToString(),
                ItemsDiscount = lineItemDiscount.ToString(),
                OrderDiscount = orderDiscount.ToString(),
                NoDiscount    = noDiscount.ToString()
            };

            return(await Task.FromResult(model));
        }
Example #18
0
        public static LoaderOptions CreateLoaderOptionsFromAgruments <TSource>(this ResolveFieldContext <TSource> context)
        {
            if (!context.HasArgument(Constants.Arguments.ARGUMENT_ALLOWFALLBACK_LANG))
            {
                throw new ArgumentException($"ResolveFieldContext does not contain any argument \"{Constants.Arguments.ARGUMENT_ALLOWFALLBACK_LANG}\"");
            }

            var allowFallbackLang = context.GetArgument <bool>(Constants.Arguments.ARGUMENT_ALLOWFALLBACK_LANG);
            var locale            = context.GetLocaleFromArgument();

            return(new LoaderOptions
            {
                allowFallbackLang
                    ? LanguageLoaderOption.Fallback(locale)
                    : LanguageLoaderOption.Specific(locale)
            });
        }
        private Dictionary <StartPage, IEnumerable <SitePageData> > GetStartPagesWithDescendants()
        {
            var dictionary = new Dictionary <StartPage, IEnumerable <SitePageData> >();
            var startPages = _contentLoader.GetChildren <StartPage>(SiteDefinition.Current.RootPage, new LoaderOptions {
                LanguageLoaderOption.MasterLanguage()
            });

            foreach (var startPage in startPages)
            {
                var descendants = _contentLoader.GetDescendents(startPage.ContentLink).ToSitePageData().Where(p =>
                                                                                                              !(p.Robots is null) && !p.Robots.ToLower().Contains("noindex") && !(p is IExcludeFromSiteMap));

                dictionary.Add(startPage, descendants);
            }

            return(dictionary);
        }
        private static ContentReference GetOrCreateCategoriesRoot(this IContentRepository contentRepository, ContentReference parentLink, string name, string routeSegment)
        {
            var loaderOptions = new LoaderOptions
            {
                LanguageLoaderOption.FallbackWithMaster()
            };

            var rootCategory = contentRepository.GetChildren <CategoryRoot>(parentLink, loaderOptions).FirstOrDefault();

            if (rootCategory != null)
            {
                return(rootCategory.ContentLink);
            }

            rootCategory              = contentRepository.GetDefault <CategoryRoot>(parentLink);
            rootCategory.Name         = name;
            rootCategory.RouteSegment = routeSegment;
            return(contentRepository.Save(rootCategory, SaveAction.Publish, AccessLevel.NoAccess));
        }
        private TaxonomyData GetTaxonomyDataRecursively(SegmentContext segmentContext)
        {
            var contentReference = this.taxonomyRoot;

            var loaderOptions = new LoaderOptions
            {
                LanguageLoaderOption.FallbackWithMaster(CultureInfo.GetCultureInfo(segmentContext.Language))
            };

            TaxonomyData taxonomyData = null;

            while (true)
            {
                var segment = segmentContext.GetNextValue(segmentContext.RemainingPath);

                if (string.IsNullOrEmpty(segment.Next))
                {
                    break;
                }

                var content = this.contentLoader.GetBySegment(contentReference, segment.Next, loaderOptions);

                if (content == null)
                {
                    break;
                }

                contentReference = content.ContentLink;

                if (content is TaxonomyData)
                {
                    taxonomyData = content as TaxonomyData;

                    // Only set remaining path if we found what we were looking for,
                    // otherwise let others try to parse the URL.
                    segmentContext.RemainingPath = segment.Remaining;
                }
            }

            return(taxonomyData);
        }
Example #22
0
        public ActionResult Index()
        {
            var items = _contentLoader
                        .GetChildren <SBRobotsTxt>(ContentReference.StartPage, new LoaderOptions {
                LanguageLoaderOption.FallbackWithMaster()
            });

            var content = "User-agent: *" + Environment.NewLine + "Disallow: /episerver";

            if (items != null)
            {
                var robotTxtPages = items.ToList();

                if (robotTxtPages.Any())
                {
                    content = robotTxtPages.First().RobotsContent;
                }
            }

            return((ActionResult)this.Content(content, "text/plain", Encoding.UTF8));
        }
Example #23
0
        public static IEnumerable <IContent> GetAllLanguageVersions(this IContentLoader contentLoader, ContentReference contentReference)
        {
            var content = contentLoader.Get <IContent>(contentReference);

            if (content is ILocalizable rootContent)
            {
                foreach (var cultureInfo in rootContent.ExistingLanguages)
                {
                    var loaderOptions = new LoaderOptions {
                        LanguageLoaderOption.Specific(cultureInfo)
                    };
                    var contentInSpecificLanguage = contentLoader.Get <IContent>(contentReference.ToReferenceWithoutVersion(), loaderOptions);

                    yield return(contentInSpecificLanguage);
                }
            }
            else
            {
                yield return(content);
            }
        }
Example #24
0
        public static IEnumerable <T> GetAllVariants <T>(this ContentReference contentLink) where T : VariationContent
        {
            switch (ReferenceConverter.Value.GetContentType(contentLink))
            {
            case CatalogContentType.CatalogNode:
                var entries = ContentLoader.Value.GetChildren <T>(contentLink,
                                                                  new LoaderOptions {
                    LanguageLoaderOption.FallbackWithMaster()
                });

                foreach (var productContent in entries.OfType <ProductContent>())
                {
                    entries = entries.Union(productContent.GetVariants()
                                            .Select(c => ContentLoader.Value.Get <T>(c)));
                }

                return(entries);

            case CatalogContentType.CatalogEntry:
                var entryContent = ContentLoader.Value.Get <EntryContentBase>(contentLink);

                if (entryContent is ProductContent p)
                {
                    return(p.GetVariants().Select(c => ContentLoader.Value.Get <T>(c)));
                }

                if (entryContent is T)
                {
                    return(new List <T> {
                        entryContent as T
                    });
                }

                break;
            }

            return(Enumerable.Empty <T>());
        }
Example #25
0
        private TaxonomyData GetTaxonomyDataRecursively(SegmentContext segmentContext)
        {
            var contentReference = this.taxonomyRoot;

            var loaderOptions = new LoaderOptions
            {
                LanguageLoaderOption.FallbackWithMaster(CultureInfo.GetCultureInfo(segmentContext.Language))
            };

            TaxonomyData taxonomyData = null;

            while (true)
            {
                var segment = this.ReadNextSegment(segmentContext);

                if (string.IsNullOrEmpty(segment.Next))
                {
                    break;
                }

                var content = this.contentLoader.GetBySegment(contentReference, segment.Next, loaderOptions);

                if (content == null)
                {
                    break;
                }

                contentReference = content.ContentLink;

                if (content is TaxonomyData)
                {
                    taxonomyData = content as TaxonomyData;
                }
            }

            return(taxonomyData);
        }
Example #26
0
 private IEnumerable <StartPage> GetStartPages() => _contentRepository
 .GetChildren <StartPage>(SiteDefinition.Current.RootPage, new LoaderOptions {
     LanguageLoaderOption.MasterLanguage()
 });