public virtual List <ProductListViewModel> GetSearchResults(string language)
        {
            IContentLoader     loader         = ServiceLocator.Current.GetInstance <IContentLoader>();
            ProductService     productService = ServiceLocator.Current.GetInstance <ProductService>();
            ReferenceConverter refConverter   = ServiceLocator.Current.GetInstance <ReferenceConverter>();

            SearchResults <FindProduct> results = GetResults(language);

            List <ProductListViewModel> searchResult = new List <ProductListViewModel>();

            foreach (SearchHit <FindProduct> searchHit in results.Hits)
            {
                ContentReference contentLink = refConverter.GetContentLink(searchHit.Document.Id, CatalogContentType.CatalogEntry, 0);

                // The content can be deleted from the db, but still exist in the index
                IContentData content = null;
                if (loader.TryGet(contentLink, out content))
                {
                    IProductListViewModelInitializer modelInitializer = content as IProductListViewModelInitializer;
                    if (modelInitializer != null)
                    {
                        searchResult.Add(productService.GetProductListViewModel(modelInitializer));
                    }
                }
            }

            return(searchResult);
        }
        /// <summary>
        ///     Returns friendly URL for provided content reference.
        /// </summary>
        /// <param name="contentReference">Content reference for which to create friendly url.</param>
        /// <param name="language">Language of content.</param>
        /// <param name="includeHost">Mark if include host name in the url, unless it is external url then it still will contain absolute url.</param>
        /// <param name="ignoreContextMode"></param>
        /// <param name="urlResolver">Optional UrlResolver instance.</param>
        /// <param name="contentLoader">Optional ContentLoader instance.</param>
        /// <returns>String representation of URL for provided content reference.</returns>
        public static string GetFriendlyUrl(
            this ContentReference contentReference,
            string language,
            bool includeHost             = false,
            bool ignoreContextMode       = false,
            UrlResolver urlResolver      = null,
            IContentLoader contentLoader = null)
        {
            if (contentReference.IsNullOrEmpty())
            {
                return(string.Empty);
            }

            if (urlResolver == null)
            {
                urlResolver = ServiceLocator.Current.GetInstance <UrlResolver>();
            }

            var url = ignoreContextMode
                ? urlResolver.GetUrl(contentReference, language, new VirtualPathArguments {
                ContextMode = ContextMode.Default
            })
                : urlResolver.GetUrl(contentReference, language);

            if (!string.IsNullOrWhiteSpace(url) &&
                url.StartsWith("/link/", StringComparison.InvariantCultureIgnoreCase) &&
                url.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase))
            {
                // caller asked for friendly url, but got ugly one
                if (Guid.TryParse(url.ToLower().Replace("/link/", string.Empty).Replace(".aspx", string.Empty),
                                  out var targetContentGuid))
                {
                    if (contentLoader == null)
                    {
                        contentLoader = ServiceLocator.Current.GetInstance <IContentLoader>();
                    }

                    if (contentLoader.TryGet <IContent>(targetContentGuid, out var destinationContent) &&
                        destinationContent.ContentLink != contentReference)
                    {
                        // in case this is shortcut from one IContent instance to another IContent instance, will try to get target content friendly url instead
                        url = ignoreContextMode
                            ? urlResolver.GetUrl(destinationContent.ContentLink, language, new VirtualPathArguments {
                            ContextMode = ContextMode.Default
                        })
                            : urlResolver.GetUrl(destinationContent.ContentLink, language);
                    }
                }
            }

            if (includeHost)
            {
                return(url.AddHost());
            }

            var content  = Get <IContent>(contentReference);
            var pageData = content as PageData;

            return(pageData?.LinkType == PageShortcutType.External ? url : url.RemoveHost());
        }
        public static IList <KeyValuePair <string, string> > GetAssetsWithType(this IAssetContainer assetContainer,
                                                                               IContentLoader contentLoader, UrlResolver urlResolver)
        {
            var assets = new List <KeyValuePair <string, string> >();

            if (assetContainer.CommerceMediaCollection != null)
            {
                assets.AddRange(
                    assetContainer.CommerceMediaCollection
                    .Select(media =>
                {
                    if (contentLoader.TryGet <IContentMedia>(media.AssetLink, out var contentMedia))
                    {
                        var type = "Image";
                        var url  = urlResolver.GetUrl(media.AssetLink, null, new VirtualPathArguments()
                        {
                            ContextMode = ContextMode.Default
                        });
                        if (contentMedia is IContentVideo)
                        {
                            type = "Video";
                        }

                        return(new KeyValuePair <string, string>(type, url));
                    }

                    return(new KeyValuePair <string, string>(string.Empty, string.Empty));
                })
                    .Where(x => x.Key != string.Empty)
                    );
            }

            return(assets);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Default search hit, which utilizes a 'vulcanSearchDescription' to set the summary, which can be added to content models via IVulcanSearchHitDescription;
        /// </summary>
        /// <param name="contentHit"></param>
        /// <param name="contentLoader"></param>
        /// <returns></returns>
        public static VulcanSearchHit DefaultBuildSearchHit(IHit <IContent> contentHit, IContentLoader contentLoader)
        {
            ContentReference contentReference = null;

            if (ContentReference.TryParse(contentHit.Id, out contentReference))
            {
                IContent content;

                if (contentLoader.TryGet(contentReference, out content))
                {
                    var    searchDescriptionCheck = contentHit.Fields.Where(x => x.Key == SearchDescriptionField).FirstOrDefault();
                    string storedDescription      = searchDescriptionCheck.Value != null ? (searchDescriptionCheck.Value as JArray).FirstOrDefault().ToString() : null;
                    var    fallbackDescription    = content as IVulcanSearchHitDescription;
                    string description            = storedDescription != null?storedDescription.ToString() :
                                                        fallbackDescription != null ? fallbackDescription.VulcanSearchDescription : string.Empty;

                    var result = new VulcanSearchHit()
                    {
                        Id      = content.ContentLink,
                        Title   = content.Name,
                        Summary = description,
                        Url     = urlResolver.GetUrl(contentReference)
                    };

                    return(result);
                }
            }

            throw new Exception($"{nameof(contentHit)} doesn't implement IContent!");
        }
        protected IRedirect ResolveRule <T>(RedirectRule rule, Func <RedirectRule, T> constructRedirect) where T : IRedirect
        {
            if (rule == null)
            {
                return(new NullRedirectRule());
            }

            if (!rule.ContentId.HasValue)
            {
                return(constructRedirect(rule));
            }

            if (!_contentLoader.TryGet <PageData>(new ContentReference(rule.ContentId.Value), out var content))
            {
                return(new NullRedirectRule());
            }

            var filter = new FilterPublished();

            if (filter.ShouldFilter(content))
            {
                return(new NullRedirectRule());
            }

            return(constructRedirect(rule));
        }
        public void GetAllBlobs()
        {
            _blobResolver = ServiceLocator.Current.GetInstance <IBlobFactory>();
            var globalAssetsRoot = EPiServer.Web.SiteDefinition.Current.GlobalAssetsRoot;

            var mediaChildRefs = _readRepo.GetDescendents(globalAssetsRoot);

            foreach (var child in mediaChildRefs)
            {
                var image = _readRepo.TryGet <ImageData>(child, out var imageData);
                if (!image)
                {
                    continue;
                }

                var blobLink = UrlHelper.GetExternalUrlNoHttpContext(imageData.ContentLink);
                if (!RemoteFileExists(blobLink))
                {
                    continue;
                }

                CompressBlob(imageData);
            }
            _log.Error(
                $"Success: Optimized {ImageCompressor.OptimizedImagesCount} images (Saved: {ImageCompressor.TotallySavedMbs} mb)." +
                $"\nSkipped {ImageCompressor.SkippedImagesCount} images.");
        }
Ejemplo n.º 7
0
        public async Task <ActionResult> ShareReviewLink(string id, string email, string subject, string message)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            if (string.IsNullOrWhiteSpace(_notificationOptions.NotificationEmailAddress))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Sender email address is not configured. Contact with system administrator"));
            }

            var externalReviewLink = _externalReviewLinksRepository.GetContentByToken(id);

            if (externalReviewLink == null)
            {
                return(new HttpNotFoundResult("Token not found"));
            }

            if (!_contentLoader.TryGet(externalReviewLink.ContentLink, out IContent content))
            {
                return(new HttpNotFoundResult("Content not found"));
            }

            await SendMail(externalReviewLink, email, subject, message);

            return(Rest(true));
        }
Ejemplo n.º 8
0
        public void Add(Guid contentGuid)
        {
            var currentContact = CustomerContext.Current.CurrentContact;

            if (currentContact != null)
            {
                var contentReference = _permanentLinkMapper.Find(contentGuid).ContentReference;
                var contact          = new FoundationContact(currentContact);
                var bookmarkModel    = new BookmarkModel();
                if (_contentLoader.TryGet <IContent>(contentReference, out var content))
                {
                    bookmarkModel.ContentLink = contentReference;
                    bookmarkModel.ContentGuid = content.ContentGuid;
                    bookmarkModel.Name        = content.Name;
                    bookmarkModel.Url         = _urlResolver.GetUrl(content);
                }
                var contactBookmarks = contact.ContactBookmarks;
                if (contactBookmarks.FirstOrDefault(x => x.ContentGuid == bookmarkModel.ContentGuid) == null)
                {
                    contactBookmarks.Add(bookmarkModel);
                }
                contact.Bookmarks = JsonConvert.SerializeObject(contactBookmarks);
                contact.SaveChanges();
            }
        }
Ejemplo n.º 9
0
        public JsonResult UpdateItem(string id, bool recursive = false)
        {
            try
            {
                if (_contentLoader.TryGet(ContentReference.Parse(id), out IContent content))
                {
                    string indexName = null;

                    // Point catalog content to correct index
                    if (Constants.CommerceProviderName.Equals(content.ContentLink.ProviderName))
                    {
                        string lang = _indexer.GetLanguage(content);
                        indexName = _settings.GetCustomIndexName($"{_settings.Index}-{Constants.CommerceProviderName}", lang);
                    }

                    IndexingStatus status = recursive
                        ? _indexer.UpdateStructure(content, indexName)
                        : _indexer.Update(content, indexName);

                    return(Json(new { status = status.ToString() }));
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error updating item with id '" + id + "'", ex);
                return(Json(new { status = nameof(IndexingStatus.Error), error = ex.Message }));
            }

            return(Json(new { status = nameof(IndexingStatus.Error) }));
        }
Ejemplo n.º 10
0
 private IEnumerable <ISettingsPage> GetSettingsPages(ContentReference contentReference)
 {
     foreach (var ancestor in Enumerable.Repeat(contentReference, 1).Concat(_contentLoader.GetAncestors(contentReference)?.Select(c => c.ContentLink)))
     {
         if (_contentLoader.TryGet <ISettingsPage>(ancestor, out var settingPage))
         {
             yield return(settingPage);
         }
     }
 }
Ejemplo n.º 11
0
        public IEnumerable <ProductListViewModel> GetSimilarProducts(int contentId)
        {
            const int maxRecommendedProducts   = 10;
            List <ProductListViewModel> models = new List <ProductListViewModel>();

            SetLanguage();
            string           language    = Language;
            ContentReference contentLink = _referenceConverter.GetContentLink(contentId, CatalogContentType.CatalogEntry, 0);
            IContent         contentItem;

            if (_contentLoader.TryGet(contentLink, out contentItem))
            {
                EntryContentBase entryContent = contentItem as EntryContentBase;
                if (entryContent != null)
                {
                    var currentCustomer     = CustomerContext.Current.CurrentContact;
                    var recommendedProducts = _recommendationService.GetRecommendedProducts(entryContent,
                                                                                            _currentCustomerService.GetCurrentUserId(), maxRecommendedProducts);


                    foreach (var content in recommendedProducts.Products)
                    {
                        ProductListViewModel model     = null;
                        VariationContent     variation = content as VariationContent;
                        if (variation != null)
                        {
                            model = new ProductListViewModel(variation, _currentMarket.GetCurrentMarket(),
                                                             currentCustomer);
                        }
                        else
                        {
                            ProductContent product = content as ProductContent;
                            if (product != null)
                            {
                                model = _productService.GetProductListViewModel(product as IProductListViewModelInitializer);

                                // Fallback
                                if (model == null)
                                {
                                    model = new ProductListViewModel(product, _currentMarket.GetCurrentMarket(),
                                                                     currentCustomer);
                                }
                            }
                        }

                        if (model != null)
                        {
                            models.Add(model);
                        }
                    }
                }
            }

            return(models);
        }
Ejemplo n.º 12
0
        private void OnCreatedContent(object sender, ContentEventArgs e)
        {
            Logger.Debug("OnCreatedContent raised.");

            if (!(e is CopyContentEventArgs))
            {
                // Return now if the was anything other than a copy action.
                return;
            }

            ContentReference newContentLink = e.ContentLink;

            if (ContentReference.IsNullOrEmpty(newContentLink) ||
                newContentLink.ProviderName != ReferenceConverter.CatalogProviderKey ||
                !_contentLoader.TryGet(newContentLink, CultureInfo.InvariantCulture, out CatalogContentBase catalogContentBase))
            {
                Logger.Debug("Copied content is not catalog content.");
                return;
            }

            switch (catalogContentBase)
            {
            case EntryContentBase entryContent:
                ICollection <ProductContent> products = GetProductsAffected(entryContent);

                foreach (ProductContent product in products)
                {
                    _productExportService.ExportProduct(product, null);
                }

                _productExportService.ExportProductAssets(products);
                _productExportService.ExportProductRecommendations(products, null);

                break;

            case NodeContent _:
                // No need to export child entries on a copy/duplicate action, as there will not be any.
                // Only re-publish the category structure.
                _categoryExportService.StartFullCategoryExport();
                break;
            }
        }
        private IContent GetContentPreviousVersion(ContentReference reference)
        {
            if (ContentReference.IsNullOrEmpty(reference))
            {
                return(null);
            }

            var previousVersionReference = reference.ToReferenceWithoutVersion();

            return(_contentLoader.TryGet <IContent>(previousVersionReference, out var content) ? content : null);
        }
        private IContent GetReadableContentFromRoute(RouteValueDictionary routeValues)
        {
            var      contentLink = routeValues[RoutingConstants.NodeKey] as ContentReference;
            IContent content;

            if (_contentLoader.TryGet(contentLink, out content) && ((ISecurable)content).GetSecurityDescriptor().HasAccess(PrincipalInfo.AnonymousPrincipal, AccessLevel.Read))
            {
                return(content);
            }
            return(null);
        }
Ejemplo n.º 15
0
        public ActionResult Index(string returnUrl)
        {
            var model = new UserViewModel();

            _contentLoader.TryGet(ContentReference.StartPage, out DemoHomePage homePage);

            model.Logo                     = Url.ContentUrl(homePage?.SiteLogo);
            model.ResetPasswordUrl         = Url.ContentUrl(homePage?.ResetPasswordPage);
            model.Title                    = "Login";
            model.LoginViewModel.ReturnUrl = returnUrl;
            return(View(model));
        }
        public async Task ExportItem(IContent content, IDataExporter exporter, IContentLoader contentLoader)
        {
            var exportedFileLocation = Path.GetTempFileName();
            var stream   = new FileStream(exportedFileLocation, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
            var settings = new Dictionary <string, object>
            {
                [this._contentSyncOptions.SettingPageLink]    = content.ContentLink,
                [this._contentSyncOptions.SettingRecursively] = false,
                [this._contentSyncOptions.SettingPageFiles]   = true,
                [this._contentSyncOptions.SettingIncludeContentTypeDependencies] = true
            };

            var sourceRoots = new List <ExportSource>
            {
                new ExportSource(content.ContentLink, ExportSource.NonRecursive)
            };

            var options = ExportOptions.DefaultOptions;

            options.ExcludeFiles = false;
            options.IncludeReferencedContentTypes = true;

            contentLoader.TryGet(content.ParentLink, out IContent parent);

            var state = new ExportState
            {
                Stream       = stream,
                Exporter     = exporter,
                FileLocation = exportedFileLocation,
                Options      = options,
                SourceRoots  = sourceRoots,
                Settings     = settings,
                Parent       = parent?.ContentGuid ?? Guid.Empty
            };

            if (state.Parent == Guid.Empty)
            {
                return;
            }

            try
            {
                exporter.Export(state.Stream, state.SourceRoots, state.Options);
                exporter.Dispose();
                await SendContent(state.FileLocation, state.Parent);
            }
            catch (Exception ex)
            {
                exporter.Abort();
                exporter.Status.Log.Error("Can't export package because: {0}", ex, ex.Message);
            }
        }
Ejemplo n.º 17
0
        private IEnumerable <BestBet> GetBestBetsForLanguage(string language, string index)
        {
            foreach (BestBet bestBet in _bestBetsRepository.GetBestBets(language, index))
            {
                var contentLink = new ContentReference(Convert.ToInt32(ContentReference.Parse(bestBet.Id).ID), bestBet.Provider);
                if (_contentLoader.TryGet(contentLink, out IContent content))
                {
                    bestBet.Name = content.Name;
                }

                yield return(bestBet);
            }
        }
        public void RenderContentReference_ImageContentReference_ReturnsImageView()
        {
            // Arrange
            var contentReference = new ContentReference(123);

            _stubContentLoader.TryGet(contentReference, out ImageData _).Returns(true);

            // Act
            var result = _propertyViewerController.RenderContentReference(contentReference, "en");

            // Assert
            Assert.AreEqual("_Image", result.ViewName);
        }
Ejemplo n.º 19
0
        public void OnGet()
        {
            var routes = _actionDescriptorCollectionProvider.ActionDescriptors.Items.Where(
                ad => ad.AttributeRouteInfo != null).Select(ad => new RouteModel
            {
                Name     = ad.AttributeRouteInfo.Name.Split('_')[0],
                Template = ad.AttributeRouteInfo.Template
            }).ToList();

            var path           = routes.FirstOrDefault(x => x.Template == Request.Path.Value);
            var hasCurrentPage = contentLoader.TryGet(new Guid(path.Name), out T CurrentPage);

            epiPage = CurrentPage;
        }
        public override string Execute()
        {
            if (_contentLoader.TryGet(_referenceConverter.GetRootLink(), out IContent content))
            {
                var securableContent         = (IContentSecurable)content;
                var defaultAccessControlList = (IContentSecurityDescriptor)securableContent.GetContentSecurityDescriptor().CreateWritableClone();
                defaultAccessControlList.AddEntry(new AccessControlEntry(RoleNames.CommerceAdmins, AccessLevel.FullAccess, SecurityEntityType.Role));
                defaultAccessControlList.AddEntry(new AccessControlEntry(EveryoneRole.RoleName, AccessLevel.Read, SecurityEntityType.Role));

                _contentSecurityRepository.Save(content.ContentLink, defaultAccessControlList, SecuritySaveType.Replace);
                return("fix");
            }
            return("nothing to fix");
        }
 public override ValidationResult IsValid(
     ContentReference value,
     ValidationContext validationContext,
     IEnumerable <Type> allowedTypes,
     IEnumerable <Type> restrictedTypes)
 {
     if (value == null)
     {
         return(null);
     }
     return(_contentLoader.TryGet <IContent>(value.Id, out var content) ?
            _contentValidator.IsValid(content, validationContext, allowedTypes, restrictedTypes) :
            null);
 }
Ejemplo n.º 22
0
        private ActionResult ValidateContent(ContentReference id)
        {
            if (!_contentLoader.TryGet(id, out IContent content))
            {
                return(new HttpNotFoundResult("Content not found"));
            }

            if (!content.QueryDistinctAccess(AccessLevel.Edit))
            {
                return(new RestStatusCodeResult(HttpStatusCode.Forbidden, "Access denied"));
            }

            return(null);
        }
Ejemplo n.º 23
0
        public PartialViewResult RenderContentReference(ContentReference contentReference, string language)
        {
            if (_contentLoader.TryGet(contentReference, out ImageData _))
            {
                return(PartialView("_Image", contentReference));
            }

            var model = new ContentReferenceModel
            {
                ContentReference = contentReference,
                Language         = language
            };

            return(PartialView("_ContentReference", model));
        }
        private NewsCardDto Map(ContentAreaItem item)
        {
            if (!_contentLoader.TryGet(item.ContentLink, out IHasCardRendering cardRendering))
            {
                return(null);
            }

            return(new NewsCardDto
            {
                Title = cardRendering.Title,
                ImageUrl = _urlResolver.GetUrl(cardRendering.Image),
                Author = cardRendering.Author,
                LinkUrl = _urlResolver.GetUrl(cardRendering.ContentLink)
            });
        }
        private static bool ValidateCorrectType <T>(ContentReference contentLink,
                                                    IContentLoader contentLoader)
            where T : IContentMedia
        {
            if (typeof(T) == typeof(IContentMedia))
            {
                return(true);
            }

            if (ContentReference.IsNullOrEmpty(contentLink))
            {
                return(false);
            }

            return(contentLoader.TryGet(contentLink, out T _));
        }
Ejemplo n.º 26
0
        public bool Match(Route route, SegmentContext segmentContext, string parameterName)
        {
            if (ContentReference.IsNullOrEmpty(segmentContext.RoutedContentLink))
            {
                return(false);
            }

            TContentType content;

            if (_contentLoader.TryGet(segmentContext.RoutedContentLink, out content) == false)
            {
                return(false);
            }

            segmentContext.RoutedObject = content;
            return(true);
        }
Ejemplo n.º 27
0
        private IList <string> TagsForProduct(ProductContent product)
        {
            var result = new List <string>();
            var link   = product.ParentLink;

            if (_contentLoader.TryGet(link, out NodeContent category))
            {
                result.Add(category.Code.SanitizeKey());
                result.AddRange(ParentTagsForCategory(category));
            }
            else
            {
                _log.Warning("Parent link is not linking to a category as expected");
            }

            return(result);
        }
Ejemplo n.º 28
0
        public ActionResult Index(NodeContent currentContent)
        {
            SetLanguage();
            string language = Language;
            var    client   = SearchClient.Instance;

            IContentLoader     loader         = ServiceLocator.Current.GetInstance <IContentLoader>();
            ProductService     productService = ServiceLocator.Current.GetInstance <ProductService>();
            ReferenceConverter refConverter   = ServiceLocator.Current.GetInstance <ReferenceConverter>();


            try
            {
                SearchResults <FindProduct> results = client.Search <FindProduct>()
                                                      .Filter(x => x.ParentCategoryId.Match(currentContent.ContentLink.ID))
                                                      .Filter(x => x.Language.Match(language))
                                                      .StaticallyCacheFor(TimeSpan.FromMinutes(1))
                                                      .GetResult();

                List <ProductListViewModel> searchResult = new List <ProductListViewModel>();
                foreach (SearchHit <FindProduct> searchHit in results.Hits)
                {
                    ContentReference contentLink = refConverter.GetContentLink(searchHit.Document.Id, CatalogContentType.CatalogEntry, 0);

                    // The content can be deleted from the db, but still exist in the index
                    IContentData content = null;
                    if (loader.TryGet(contentLink, out content))
                    {
                        IProductListViewModelInitializer modelInitializer = content as IProductListViewModelInitializer;
                        if (modelInitializer != null)
                        {
                            searchResult.Add(productService.GetProductListViewModel(modelInitializer));
                        }
                    }
                }


                return(PartialView("Blocks/NodeContentPartial", searchResult));
            }

            catch (Exception)
            {
                return(PartialView("Blocks/NodeContentPartial", null));
            }
        }
Ejemplo n.º 29
0
        public virtual CartItemViewModel CreateCartItemViewModel(ICart cart, ILineItem lineItem, EntryContentBase entry)
        {
            var basePrice = lineItem.Properties["BasePrice"] != null?decimal.Parse(lineItem.Properties["BasePrice"].ToString()) : 0;

            var optionPrice = lineItem.Properties["OptionPrice"] != null?decimal.Parse(lineItem.Properties["OptionPrice"].ToString()) : 0;

            var viewModel = new CartItemViewModel
            {
                Code                = lineItem.Code,
                DisplayName         = lineItem.DisplayName,
                ImageUrl            = entry.GetAssets <IContentImage>(_contentLoader, _urlResolver).FirstOrDefault() ?? "",
                DiscountedPrice     = GetDiscountedPrice(cart, lineItem),
                BasePrice           = new Money(basePrice, _currencyService.GetCurrentCurrency()),
                OptionPrice         = new Money(optionPrice, _currencyService.GetCurrentCurrency()),
                PlacedPrice         = new Money(lineItem.PlacedPrice, _currencyService.GetCurrentCurrency()),
                Quantity            = lineItem.Quantity,
                Url                 = entry.GetUrl(_relationRepository, _urlResolver),
                Entry               = entry,
                IsAvailable         = _pricingService.GetCurrentPrice(entry.Code).HasValue,
                DiscountedUnitPrice = GetDiscountedUnitPrice(cart, lineItem),
                IsGift              = lineItem.IsGift,
                Description         = entry["Description"] != null ? entry["Description"].ToString() : "",
                IsDynamicProduct    = lineItem.Properties["VariantOptionCodes"] != null
            };

            var productLink = entry is VariationContent?
                              entry.GetParentProducts(_relationRepository).FirstOrDefault() :
                                  entry.ContentLink;

            if (_contentLoader.TryGet(productLink, out EntryContentBase catalogContent))
            {
                var product = catalogContent as GenericProduct;
                if (product != null)
                {
                    viewModel.Brand = GetBrand(product);
                    var variant = entry as GenericVariant;
                    if (variant != null)
                    {
                        viewModel.AvailableSizes = GetAvailableSizes(product, variant);
                    }
                }
            }

            return(viewModel);
        }
Ejemplo n.º 30
0
        internal static void UpdateIndex(object sender, ContentSecurityEventArg e)
        {
            Logger.Debug($"ACL changed for '{e.ContentLink}'");

            var published = VersionRepository.LoadPublished(e.ContentLink);

            if (published == null)
            {
                Logger.Debug("Previously unpublished, do nothing");
                return;
            }

            if (ContentLoader.TryGet(e.ContentLink, out IContent content))
            {
                Logger.Debug("Valid content, update index");
                EPiIndexer.Update(content);
            }
        }