Esempio n. 1
0
        public Money GetShippingTaxTotal(IShipment shipment, IMarket market, Currency currency)
        {
            if (shipment.ShippingAddress == null)
            {
                return(new Money(0m, currency));
            }

            var shippingTaxes = new List <ITaxValue>();

            foreach (var item in shipment.LineItems)
            {
                //get the variation entry that the item is associated with
                var reference = _referenceConverter.GetContentLink(item.Code);
                var entry     = _contentRepository.Get <VariationContent>(reference);
                if (entry == null || !entry.TaxCategoryId.HasValue)
                {
                    continue;
                }

                //get the tax values applicable for the entry. If not taxes found then continue with next line item.
                var taxCategory = CatalogTaxManager.GetTaxCategoryNameById(entry.TaxCategoryId.Value);

                var taxes = GetTaxValues(taxCategory, market.DefaultLanguage.Name, shipment.ShippingAddress).ToList();
                if (taxes.Count <= 0)
                {
                    continue;
                }

                shippingTaxes.AddRange(
                    taxes.Where(x => x.TaxType == TaxType.ShippingTax &&
                                !shippingTaxes.Any(y => y.Name.Equals(x.Name))));
            }

            return(new Money(CalculateShippingTax(shippingTaxes, shipment, market, currency), currency));
        }
Esempio n. 2
0
        private void CatalogKeyEventUpdated(object sender, EventNotificationEventArgs e)
        {
            if (!KachingConfiguration.Instance.ListenToRemoteEvents && !IsLocalEvent(e))
            {
                return;
            }

            if (!(Deserialize(e) is PriceUpdateEventArgs e1))
            {
                return;
            }

            Logger.Debug("PriceUpdated raised.");

            var contentLinks = new HashSet <ContentReference>(
                e1.CatalogKeys.Select(key => _referenceConverter.GetContentLink(key.CatalogEntryCode)));

            IEnumerable <ContentReference> affectedProductLinks = GetAffectedProductReferences(contentLinks);

            ProductContent[] products = _contentLoader.GetItems(affectedProductLinks, CultureInfo.InvariantCulture)
                                        .OfType <ProductContent>()
                                        .ToArray();

            foreach (ProductContent productContent in products)
            {
                _productExportService.ExportProduct(productContent, null);
            }
        }
        public AddToCartResult AddToCart(ICart cart, string code, decimal quantity, string deliveryMethod, string warehouseCode)
        {
            var contentLink  = _referenceConverter.GetContentLink(code);
            var entryContent = _contentLoader.Get <EntryContentBase>(contentLink);

            return(AddToCart(cart, entryContent, quantity, deliveryMethod, warehouseCode));
        }
Esempio n. 4
0
        public virtual IEnumerable <T> GetSiblingVariants <T>(string code) where T : VariationContent
        {
            var productRelations  = _relationRepository.GetParents <ProductVariation>(_referenceConverter.GetContentLink(code));
            var siblingsRelations = _relationRepository.GetChildren <ProductVariation>(productRelations.First().Parent);

            return(GetVariants <T>(siblingsRelations.Select(x => x.Child), _languageResolver.GetPreferredCulture()));
        }
        public IViewComponentResult Import(QuickOrderProductViewModel[] productsList)
        {
            var returnedMessages = new List <string>();

            ModelState.Clear();

            if (Cart == null)
            {
                _cart = _cartService.LoadOrCreateCart(_cartService.DefaultCartName);
            }

            foreach (var product in productsList)
            {
                if (!product.ProductName.Equals("removed"))
                {
                    var variationReference = _referenceConverter.GetContentLink(product.Sku);
                    var currentQuantity    = GetCurrentItemQuantity(product.Sku);
                    product.Quantity += (int)currentQuantity;
                    var responseMessage = _quickOrderService.ValidateProduct(variationReference, Convert.ToDecimal(product.Quantity), product.Sku);
                    AddToCartQuickOrder(_cart, product, returnedMessages, responseMessage);
                }
            }

            if (returnedMessages.Count == 0)
            {
                returnedMessages.Add("All items were added to cart.");
            }
            TempData["messages"] = returnedMessages;

            var model = new { Message = returnedMessages, TotalItem = Cart.GetAllLineItems().Sum(x => x.Quantity) };

            return(new ContentViewComponentResult(JsonConvert.SerializeObject(model)));
        }
Esempio n. 6
0
        public ActionResult AddToCart(RequestParamsToCart param)
        {
            ModelState.Clear();

            if (SharedCart.Cart == null)
            {
                _sharedCart = new CartWithValidationIssues
                {
                    Cart             = _cartService.LoadOrCreateCart(_cartService.DefaultSharedCartName, OrganizationId),
                    ValidationIssues = new Dictionary <ILineItem, List <ValidationIssue> >()
                };
            }

            param.Store = "delivery";
            var result = _cartService.AddToCart(SharedCart.Cart, param);

            if (result.EntriesAddedToCart)
            {
                _orderRepository.Save(SharedCart.Cart);
                var productName = "";
                var entryLink   = _referenceConverter.GetContentLink(param.Code);
                productName = _contentLoader.Get <EntryContentBase>(entryLink).DisplayName;

                return(Json(new ChangeCartJsonResult
                {
                    StatusCode = 1,
                    CountItems = (int)SharedCart.Cart.GetAllLineItems().Sum(x => x.Quantity),
                    Message = productName + " is added to the shared cart  successfully."
                }));
            }

            return(Json(new ChangeCartJsonResult {
                StatusCode = -1, Message = result.GetComposedValidationMessage()
            }));
        }
        public AddToCartResult AddToCart(ICart cart, RequestParamsToCart requestParams)
        {
            var contentLink  = _referenceConverter.GetContentLink(requestParams.Code);
            var entryContent = _contentLoader.Get <EntryContentBase>(contentLink);

            return(AddToCart(cart, entryContent, requestParams.Quantity, requestParams.Store, requestParams.SelectedStore, requestParams.DynamicCodes));
        }
Esempio n. 8
0
        protected virtual ContentReference GetCatalogRoot()
        {
            var ids = GetCatalogIds().ToList();

            if (ids.Any())
            {
                return(_referenceConverter.GetContentLink(ids.First(), CatalogContentType.Catalog, 0));
            }

            return(ContentReference.EmptyReference);
        }
        public ActionResult Index(AdminPage currentPage)
        {
            AdminViewModel   model = new AdminViewModel();
            ContentReference aRef  = _referenceConverter.GetContentLink("Shirts_1");
            ContentReference aRef2 = _referenceConverter.GetContentLink("Men_1");
            ContentReference aRef3 = _referenceConverter.GetContentLink(2, CatalogContentType.CatalogEntry, 0);

            CheckReferenceConverter(aRef, model);
            CheckReferenceConverter(aRef2, model);
            CheckReferenceConverter(aRef3, model);

            return(View(model));
        }
Esempio n. 10
0
        public virtual IHttpActionResult GetProducts()
        {
            var contentLink = _referenceConverter.GetContentLink("shoes");
            var category    = _contentRepository.Get <FashionNode>(contentLink);

            var list = new List <Product>();

            foreach (var item in _contentRepository.GetChildren <FashionProduct>(category.ContentLink))
            {
                list.Add(GetByCode(item));
            }

            return(Ok(list));
        }
        public Interfaces.IRecommendations GetRecommendedProducts(EntryContentBase catalogEntry, string userId, int maxCount)
        {
            var recommendationsForProduct = _trackedRecommendationService.GetRecommendationsForProduct(catalogEntry.Code, maxCount);

            List <ContentReference> links = new List <ContentReference>();

            foreach (string code in recommendationsForProduct.ProductCodes)
            {
                links.Add(_referenceConverter.GetContentLink(code, CatalogContentType.CatalogEntry));
            }

            Interfaces.IRecommendations recommendations = new ProductRecommendations(recommendationsForProduct.RecommenderName, _contentRepository.GetItems(links, catalogEntry.Language));
            return(recommendations);
        }
Esempio n. 12
0
        private void OnPriceUpdated(object sender, PriceUpdateEventArgs e)
        {
            Logger.Debug("OnPriceUpdated raised.");

            var contentLinks = new HashSet <ContentReference>(
                e.CatalogKeys.Select(key => _referenceConverter.GetContentLink(key.CatalogEntryCode)));

            IEnumerable <ProductContent> products = GetProductsAffected(contentLinks);

            foreach (ProductContent productContent in products)
            {
                _productExportService.ExportProduct(productContent, null);
            }
        }
Esempio n. 13
0
        private void AddLinksFromMediaToCodes(IContent contentMedia, IEnumerable <EntryCode> codes)
        {
            var media = new CommerceMedia {
                AssetLink = contentMedia.ContentLink, GroupName = "default", AssetType = "episerver.core.icontentmedia"
            };

            foreach (EntryCode entryCode in codes)
            {
                ContentReference contentReference = _referenceConverter.GetContentLink(entryCode.Code);

                IAssetContainer writableContent = null;
                if (_contentRepository.TryGet(contentReference, out EntryContentBase entry))
                {
                    writableContent = (EntryContentBase)entry.CreateWritableClone();
                }

                if (_contentRepository.TryGet(contentReference, out NodeContent node))
                {
                    writableContent = (NodeContent)node.CreateWritableClone();
                }

                if (writableContent == null)
                {
                    _logger.Error($"Can't get a suitable content (with code {entryCode.Code} to add CommerceMedia to, meaning it's neither EntryContentBase nor NodeContent.");
                    continue;
                }

                CommerceMedia existingMedia = writableContent.CommerceMediaCollection.FirstOrDefault(x => x.AssetLink.Equals(media.AssetLink));
                if (existingMedia != null)
                {
                    writableContent.CommerceMediaCollection.Remove(existingMedia);
                }

                if (entryCode.IsMainPicture)
                {
                    _logger.Debug($"Setting '{contentMedia.Name}' as main media on {entryCode.Code}");
                    media.SortOrder = 0;
                    writableContent.CommerceMediaCollection.Insert(0, media);
                }
                else
                {
                    _logger.Debug($"Adding '{contentMedia.Name}' as media on {entryCode.Code}");
                    media.SortOrder = 1;
                    writableContent.CommerceMediaCollection.Add(media);
                }

                _contentRepository.Save((IContent)writableContent, SaveAction.Publish, AccessLevel.NoAccess);
            }
        }
Esempio n. 14
0
        private string GetOutlineForNode(string nodeCode)
        {
            if (string.IsNullOrEmpty(nodeCode))
            {
                return("");
            }
            var outline     = nodeCode;
            var currentNode = _contentRepository.Get <NodeContent>(_referenceConverter.GetContentLink(nodeCode));
            var parent      = _contentRepository.Get <CatalogContentBase>(currentNode.ParentLink);

            while (!ContentReference.IsNullOrEmpty(parent.ParentLink))
            {
                var catalog = parent as CatalogContent;
                if (catalog != null)
                {
                    outline = string.Format("{1}/{0}", outline, catalog.Name);
                }

                var parentNode = parent as NodeContent;
                if (parentNode != null)
                {
                    outline = string.Format("{1}/{0}", outline, parentNode.Code);
                }

                parent = _contentRepository.Get <CatalogContentBase>(parent.ParentLink);
            }
            return(outline);
        }
Esempio n. 15
0
        protected void PrimeCacheImpl()
        {
            ICatalogSystem       catalog            = ServiceLocator.Current.GetInstance <ICatalogSystem>();
            IContentRepository   repository         = ServiceLocator.Current.GetInstance <IContentRepository>();
            ReferenceConverter   referenceConverter = ServiceLocator.Current.GetInstance <ReferenceConverter>();
            CatalogContentLoader contentLoader      = ServiceLocator.Current.GetInstance <CatalogContentLoader>();

            // Get all catalogs
            CatalogDto catalogDto = catalog.GetCatalogDto();

            _log.Debug("Found {0} catalogs. Start iterating.", catalogDto.Catalog.Count);
            foreach (CatalogDto.CatalogRow catalogRow in catalogDto.Catalog)
            {
                _log.Debug("Loading all categories for catalog {0} ({1})", catalogRow.Name, catalogRow.CatalogId);
                // Get all Categories on first level
                CatalogNodes nodes = catalog.GetCatalogNodes(catalogRow.CatalogId,
                                                             new CatalogNodeResponseGroup(CatalogNodeResponseGroup.ResponseGroup.CatalogNodeInfo));
                _log.Debug("Loaded {0} categories using ICatalogSystem", nodes.CatalogNode.Count());
                // Get them as content too
                foreach (CatalogNode node in nodes.CatalogNode)
                {
                    ContentReference nodeReference = referenceConverter.GetContentLink(node.CatalogNodeId, CatalogContentType.CatalogNode, 0);
                    NodeContent      content       = repository.Get <EPiServer.Commerce.Catalog.ContentTypes.NodeContent>(nodeReference);
                    _log.Debug("Loded Category Content: {0}", content.Name);
                    WalkCategoryTree(content, repository, contentLoader, catalog, referenceConverter);
                }
            }
        }
Esempio n. 16
0
        public void UpdateSearchDocument(ref SearchDocument document, string entryCode, string language)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            var languageCulture = CultureInfo.GetCultureInfo(language);
            var contentLink     = _referenceConverter.GetContentLink(entryCode);
            var entryContent    = _contentLoader.Get <EntryContentBase>(contentLink, languageCulture);
            var relatedProducts = GetProducts(entryContent, languageCulture).ToArray();
            var relatedVariants = GetVariants(relatedProducts, languageCulture).ToArray();

            AddPrices(document, new[] { entryContent });
            AddCodes(document, relatedVariants);
            AddBrands(document, relatedProducts);
            AddPrices(document, relatedVariants);
            AddColors(document, relatedVariants);
            AddSizes(document, relatedVariants);

            document.Add(new SearchField("code", entryContent.Code, new[] { SearchField.Store.YES, SearchField.IncludeInDefaultSearch.YES }));
            document.Add(new SearchField("displayname", entryContent.DisplayName));
            document.Add(new SearchField("image_url", _assetUrlResolver.GetAssetUrl <IContentImage>(entryContent)));
            document.Add(new SearchField("content_link", entryContent.ContentLink.ToString()));
            document.Add(new SearchField("created", entryContent.Created.ToString("yyyyMMddhhmmss")));
            document.Add(new SearchField("top_category_name", GetTopCategoryName(entryContent)));

            stopwatch.Stop();
            _log.Debug(string.Format("Indexing of {0} for {1} took {2}", entryContent.Code, language, stopwatch.Elapsed.Milliseconds));
        }
Esempio n. 17
0
        protected RestSearchDocument PopulateRestSearchDocument(string code, string language)
        {
            var contentLink = _referenceConverter.GetContentLink(code);

            if (ContentReference.IsNullOrEmpty(contentLink))
            {
                return(null);
            }
            var document       = new RestSearchDocument();
            var entryContent   = _contentLoader.Get <EntryContentBase>(contentLink);
            var fashionProduct = entryContent as FashionProduct;
            var fashionPackage = entryContent as FashionPackage;

            if (fashionProduct != null)
            {
                var variants = _contentLoader.GetItems(fashionProduct.GetVariants(_relationRepository), CultureInfo.GetCultureInfo(language)).OfType <FashionVariant>().ToList();
                AddPrices(document, variants.Select(v => new CatalogKey(v.Code)));
                AddColors(document, variants);
                AddSizes(document, variants);
                AddCodes(document, variants);
                document.Fields.Add(new RestSearchField("brand", fashionProduct.Brand));
            }
            else if (fashionPackage != null)
            {
                AddPrices(document, new [] { new CatalogKey(fashionPackage.Code) });
            }
            document.Fields.Add(new RestSearchField("code", entryContent.Code, new[] { SearchField.Store.YES, SearchField.IncludeInDefaultSearch.YES }));
            document.Fields.Add(new RestSearchField("displayname", entryContent.DisplayName));
            document.Fields.Add(new RestSearchField("image_url", _assetUrlResolver.GetAssetUrl <IContentImage>(entryContent)));
            document.Fields.Add(new RestSearchField("content_link", entryContent.ContentLink.ToString()));
            document.Fields.Add(new RestSearchField("created", entryContent.Created.ToString("yyyyMMddhhmmss")));
            document.Fields.Add(new RestSearchField("top_category_name", GetTopCategoryName(entryContent)));

            return(document);
        }
Esempio n. 18
0
        public ActionResult CreateDefaultEntry(FashionNode currentContent, NewBlouseObject model)
        {
            var parentReference = _referenceConverter.GetContentLink(model.Code);

            var product = _contentRepository.GetDefault <BlouseProduct>(parentReference);

            product.Name = model.NewName;
            product.Code = model.NewCode;

            var productContentReference = _contentRepository.Save(product, SaveAction.Publish, AccessLevel.NoAccess);

            var sizes = model.Sizes.Split(';');

            foreach (var size in sizes)
            {
                var sku = _contentRepository.GetDefault <ShirtVariation>(productContentReference);
                sku.Name  = $"{model.NewName} {model.Color} {size}";
                sku.Code  = $"{model.NewCode}{model.Color}{size}";
                sku.Color = model.Color;
                sku.Size  = size;
                _contentRepository.Save(sku, SaveAction.Publish, AccessLevel.NoAccess);
            }


            return(new RedirectResult(GetUrl(currentContent.ContentLink)));
        }
Esempio n. 19
0
        public IEnumerable <ContentReference> AllCategories()
        {
            List <ContentReference> localList = new List <ContentReference>();
            List <int> nodeIds = new List <int>();

            CatalogEntryDto dto = CatalogContext.Current.GetCatalogEntriesDto("Fashion");

            CatalogRelationDto relDto = CatalogContext.Current.GetCatalogRelationDto(1, 0, 0, null,
                                                                                     new CatalogRelationResponseGroup(CatalogRelationResponseGroup.ResponseGroup.NodeEntry));


            foreach (CatalogRelationDto.NodeEntryRelationRow item in relDto.NodeEntryRelation)
            {
                if (!nodeIds.Contains(item.CatalogNodeId))
                {
                    nodeIds.Add(item.CatalogNodeId);
                }
            }

            ReferenceConverter refConv = ServiceLocator.Current.GetInstance <ReferenceConverter>();

            foreach (int item in nodeIds)
            {
                localList.Add(refConv.GetContentLink(item, CatalogContentType.CatalogNode, 0));
            }

            return(localList);
        }
Esempio n. 20
0
        public IRecommendations GetRecommendedProducts(EntryContentBase catalogEntry, string userId, int maxCount)
        {
            if (catalogEntry == null)
            {
                throw new ArgumentNullException("catalogEntry");
            }

            var    client       = SearchClient.Instance;
            string language     = catalogEntry.Language.Name;
            string mainCategory = catalogEntry.GetMainCategory(language);
            string category     = catalogEntry.GetCategoryName(language);

            var result = client.Search <FindProduct>()
                         .Filter(x => x.CategoryName.Match(category))
                         .Filter(x => x.MainCategoryName.Match(mainCategory))
                         .Filter(x => !x.Code.Match(catalogEntry.Code))
                         .Filter(x => x.Language.Match(language))
                         .StaticallyCacheFor(TimeSpan.FromMinutes(1))
                         .Take(maxCount)
                         .GetResult();

            List <ContentReference> links = new List <ContentReference>();

            foreach (FindProduct product in result)
            {
                links.Add(_referenceConverter.GetContentLink(product.Id, CatalogContentType.CatalogEntry, 0));
            }

            IRecommendations recommendations = new Recommendations("RecForProduct", _contentRepository.GetItems(links, catalogEntry.Language));

            return(recommendations);
        }
Esempio n. 21
0
        private CartActionResult AddToCart(string name, LineItem lineItem)
        {
            string code = lineItem.Code;

            if (lineItem.Quantity < 1)
            {
                lineItem.Quantity = 1;
            }

            string messages = string.Empty;
            ICart  cart     = LoadOrCreateCart(DefaultCartName);
            var    result   = AddToCart(cart, code, lineItem.Quantity, out messages);

            // Populate with additional fields before saving
            ILineItem addedLineItem = cart.GetAllLineItems().FirstOrDefault(x => x.Code == code);

            if (addedLineItem != null)
            {
                // Need content for easier access to more information
                ContentReference itemLink     = _referenceConverter.GetContentLink(code);
                EntryContentBase entryContent = _contentLoader.Get <EntryContentBase>(itemLink);

                AddPropertiesToLineItem(addedLineItem, lineItem, entryContent);

                AddCustomProperties(lineItem, addedLineItem);
            }

            _orderRepository.Save(cart);

            // TODO: Always returns success, if we get warnings, we need to show them
            return(new CartActionResult {
                Success = true, Message = messages
            });
        }
        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);
        }
Esempio n. 23
0
        public IEnumerable <CartItem> GetCartItems()
        {
            if (_cardhelper.IsEmpty)
            {
                return(Enumerable.Empty <CartItem>());
            }

            var cartItems = new List <CartItem>();
            var lineItems = _cardhelper.Cart.GetAllLineItems();

            //// In order to show the images for the items in the cart, we need to load the variants
            var variants = _contentLoader.GetItems(lineItems.Select(x => _referenceConverter.GetContentLink(x.Code)),
                                                   _preferredCulture).OfType <VariationContent>();

            foreach (var lineItem in lineItems)
            {
                VariationContent variant = variants.FirstOrDefault(x => x.Code == lineItem.Code);
                ProductContent   product = _contentLoader.Get <ProductContent>(variant.GetParentProducts().FirstOrDefault());
                CartItem         item    = new CartItem
                {
                    Code        = lineItem.Code,
                    DisplayName = lineItem.DisplayName,
                    ImageUrl    = variant.GetAssets <IContentImage>(_contentLoader, _urlResolver).FirstOrDefault() ?? "",
                    Quantity    = lineItem.Quantity,
                    Url         = lineItem.GetUrl(),
                    Variant     = variant,
                    Price       = variant.GetPrices().FirstOrDefault().UnitPrice
                };
                cartItems.Add(item);
            }

            return(cartItems);
        }
Esempio n. 24
0
        public async Task <CartAddResponce> Handle(CartAddRequest request, CancellationToken cancellationToken)
        {
            var cart             = _cartFactory.LoadOrCreateCart();
            var variantReference = _referenceConverter.GetContentLink(request.Code);

            if (variantReference == null)
            {
                return(new CartAddResponce()
                {
                    Code = request.Code, ErrorMessages = "Code dos not excist", VariantAdded = false
                });
            }
            var content = _contentLoader.Get <MovieVariant>(variantReference);

            if (content == null)
            {
                return(new CartAddResponce()
                {
                    Code = request.Code, ErrorMessages = "Can't load variant", VariantAdded = false
                });
            }

            cart.InsertOrUpdate(request.Code, request.Quantity, content.DisplayName);
            cart.ValidateCart();
            _cartFactory.Save(cart);
            return(await Task.FromResult(new CartAddResponce()
            {
                Code = request.Code, VariantAdded = true, QuantityAdded = request.Quantity
            }));
        }
Esempio n. 25
0
 private IEnumerable <EntryContentBase> GetEntries(IEnumerable <IPriceValue> prices)
 {
     return(prices.GroupBy(x => x.CatalogKey.CatalogEntryCode)
            .Select(x => x.First())
            .Select(x => _contentLoader.Get <EntryContentBase>(
                        _referenceConverter.GetContentLink(x.CatalogKey.CatalogEntryCode, CatalogContentType.CatalogEntry))));
 }
Esempio n. 26
0
        public void DoReIndexProducts(IEnumerable <string> catalogEntryCodes)
        {
            var productsToIndex = new List <ProductContent>();

            foreach (var variationCode in catalogEntryCodes)
            {
                var variationRef = _referenceConverter.GetContentLink(variationCode);
                if (variationRef != null)
                {
                    var variation = _contentRepository.Get <IContent>(variationRef) as VariationContent;
                    if (variation != null)
                    {
                        var productRefs = variation.GetParentProducts();
                        var products    = _contentRepository.GetItems(productRefs, new LoaderOptions()).OfType <ProductContent>();
                        if (products != null && products.Any())
                        {
                            productsToIndex.AddRange(products);
                        }
                    }
                }
            }
            if (productsToIndex.Any())
            {
                SearchClient.Instance.Index(productsToIndex.DistinctBy(p => p.Code));
            }
        }
Esempio n. 27
0
        private void GetProductStuff(AdminPage currentPage)
        {
            // added using EPiServer.Commerce.Catalog.ContentTypes;
            // so we get all the nice extension methods
            string code        = "Long-Sleeve-Shirt_1";
            var    theThingRef = _referenceConverter.GetContentLink(code);

            var    theThing = _contentLoader.Get <ShirtProduct>(theThingRef);
            string assetUrl = _assetUrlResolver.GetAssetUrl(theThing);

            CommerceMedia x = theThing.CommerceMediaCollection.First();
            ItemCollection <CommerceMedia> col = theThing.CommerceMediaCollection;

            Categories y = theThing.Categories;
            IEnumerable <ContentReference> z = theThing.GetCategories();
        }
Esempio n. 28
0
        public void ModelFiller(InventoryDemoViewModel viewModel)
        {
            var shirtRef = _referenceConverter.GetContentLink("Long Sleeve Shirt White Small_1");

            viewModel.Shirt    = _contentLoader.Get <ShirtVariation>(shirtRef);
            viewModel.ImageUrl = _assetUrlResolver.GetAssetUrl(viewModel.Shirt);
        }
        protected List <KeyValuePair <string, string> > GetBreadCrumb(string catalogCode)
        {
            var model = new List <KeyValuePair <string, string> >();

            model.Add(new KeyValuePair <string, string>("Home", "/"));
            var entryLink = _referenceConverter.GetContentLink(catalogCode);

            if (entryLink != null)
            {
                var entry   = _contentLoader.Get <CatalogContentBase>(entryLink);
                var product = entry;
                if (entry is VariationContent)
                {
                    var parentLink = (entry as VariationContent).GetParentProducts().FirstOrDefault();
                    if (!ContentReference.IsNullOrEmpty(parentLink))
                    {
                        product = _contentLoader.Get <CatalogContentBase>(parentLink);
                    }
                }
                var ancestors = _contentLoader.GetAncestors(product.ContentLink);
                foreach (var anc in ancestors.Reverse())
                {
                    if (anc is NodeContent)
                    {
                        model.Add(new KeyValuePair <string, string>(anc.Name, anc.PublicUrl(_urlResolver)));
                    }
                }
            }

            return(model);
        }
        protected void GetEntry_Click(object sender, EventArgs e)
        {
            try
            {
                this.ResetPanels();

                _repo = ServiceLocator.Current.GetInstance <IContentRepository>();
                _referenceConverter = ServiceLocator.Current.GetInstance <ReferenceConverter>();

                var content = _repo.Get <CatalogContentBase>(_referenceConverter.GetContentLink(Code.Value));

                ErrorMessage.Text = (content is PackageContent).ToString();

                string code  = Code.Value;
                var    entry = CatalogContext.Current.GetCatalogEntry(
                    code, new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.Children));

                if (entry == null)
                {
                    throw new Exception(string.Format("No style or variant found with code {0}", code));
                }

                DisplayVariant(entry);
            }
            catch (Exception ex)
            {
                ErrorMessage.Text  = ex.Message;
                ErrorPanel.Visible = true;
            }
        }
        protected void GetEntry_Click(object sender, EventArgs e)
        {
            try
            {
                this.ResetPanels();

                _repo = ServiceLocator.Current.GetInstance<IContentRepository>();
                _referenceConverter = ServiceLocator.Current.GetInstance<ReferenceConverter>();

                var content = _repo.Get<CatalogContentBase>(_referenceConverter.GetContentLink(Code.Value));

                ErrorMessage.Text = (content is PackageContent).ToString();

                string code = Code.Value;
                var entry = CatalogContext.Current.GetCatalogEntry(
                    code, new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.Children));

                if (entry == null)
                    throw new Exception(string.Format("No style or variant found with code {0}", code));

                DisplayVariant(entry);

            }
            catch (Exception ex)
            {
                ErrorMessage.Text = ex.Message;
                ErrorPanel.Visible = true;
            }
        }