Пример #1
0
        public object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            //if you want to access the datasource item
            var datasource = !string.IsNullOrEmpty(rendering.DataSource)
                ? rendering.RenderingItem?.Database.GetItem(rendering.DataSource)
                : null;

            dynamic jsonObject = new JObject();

            jsonObject.Description = datasource.GetFieldValue("Description");
            jsonObject.Copyright   = datasource.GetFieldValue("Copyright");
            jsonObject.LogoLink    = datasource.GetLinkFieldValue("LogoLink");
            jsonObject.Logo        = datasource.GetImageFieldURL("Logo");
            var socialLinks      = new List <SocialLink>();
            var socialLinkFolder = datasource.GetChildren().Where(x => x.TemplateID == ID.Parse("{94FD0EF6-0BDC-49C3-9379-880899C5412E}")).FirstOrDefault();

            if (socialLinkFolder != null)
            {
                foreach (var item in socialLinkFolder.GetChildren().Where(x => x.TemplateID.ToString() == "{77529C37-A686-4E39-B64D-F5262BA37487}"))
                {
                    socialLinks.Add(new SocialLink()
                    {
                        Link     = item.GetLinkFieldValue("Link"),
                        CSSClass = item.GetFieldValue("CSS Class")
                    });
                }
            }
            jsonObject.SocialLinks = JsonConvert.SerializeObject(socialLinks);
            return(jsonObject);
        }
        public override object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            var productsRoot = GetContextItem(rendering, renderingConfig);
            var products     = ProductRepository.GetProducts(productsRoot);

            return(new
            {
                // Use the inherited method to get the JSON serialized item, then reduce the returned fields
                Products = products.Select(item => new
                {
                    Item = item,
                    Serialized = base.ProcessItem(item, rendering, renderingConfig)
                })
                           .Select(product => new
                {
                    // Create object shape expected by ItemLinkField
                    Url = LinkManager.GetItemUrl(product.Item),
                    Id = product.Item.ID,
                    Fields = new
                    {
                        Title = product.Serialized[product.Item.Fields[Templates.Product.Fields.Title].Name],
                        ShortDescription = product.Serialized[product.Item.Fields[Templates.Product.Fields.ShortDescription].Name],
                        Image = product.Serialized[product.Item.Fields[Templates.Product.Fields.Image].Name]
                    }
                })
            });
        }
        protected override JObject ProcessItem(Item item,
                                               Sitecore.Mvc.Presentation.Rendering rendering,
                                               IRenderingConfiguration renderingConfig)
        {
            var processedItem = base.ProcessItem(item, rendering, renderingConfig);

            if (!item.DescendsFrom(new ID(CheckoutNavigation.TemplateId)))
            {
                return(processedItem);
            }

            var checkoutNavigation = this.sitecoreContext.Cast <ICheckoutNavigation>(item);
            var checkoutSteps      = checkoutNavigation?.CheckoutSteps;

            if (checkoutSteps == null || !checkoutSteps.Any())
            {
                return(processedItem);
            }

            var firstStep = this.sitecoreContext.GetItem <ICheckoutStep>(checkoutSteps.ElementAt(0));

            processedItem.Add("url", firstStep.Url);

            return(processedItem);
        }
Пример #4
0
 public override RenderedItem Render(
     Item item,
     IRenderingConfiguration renderingConfiguration,
     RenderOptions renderOptions = null)
 {
     return(CustomRenderedItem(item, renderingConfiguration, renderOptions: renderOptions));
 }
Пример #5
0
        private RenderedItem GetRenderedElement(IRenderingConfiguration renderingConfiguration, Item item)
        {
            var pageContextItem = PageContext.Current.Item;

            PageContext.Current.Item           = item;
            PageContext.Current.PageDefinition = null;

            var rootRendering = new Rendering
            {
                Item              = item,
                DeviceId          = new Guid(Constants.DefaultDeviceId),
                RenderingItemPath = Constants.DefaultDeviceId,
                RenderingType     = Constants.SnippetRenderingType,
                Items             = new[] { item },
                LayoutId          = Constants.SnippetLayoutId
            };

            var options = new RenderOptions(
                rootRendering);
            var renderedElement = base.Render(
                item,
                renderingConfiguration,
                options);

            PageContext.Current.Item           = pageContextItem;
            PageContext.Current.PageDefinition = null;
            return(renderedElement);
        }
        public object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            IEnumerable <ICountryRegionModel> model =
                this.storefrontContext.CurrentStorefront.CountriesRegionsConfiguration.CountriesRegionsModel;

            return(new { Countries = this.mapper.MapToCountryRegionModel(model) });
        }
Пример #7
0
        public override object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            JObject obj = (JObject)base.ResolveContents(rendering, renderingConfig);

            obj["feedItems"] = RssBuilder.GetFeedItemsAsJson(this.GetContextItem(rendering, renderingConfig));

            return(obj);
        }
        public override object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            var root = RootResolver.GetNavigationRoot(this.GetContextItem(rendering, renderingConfig));

            return(new
            {
                FooterText = root[Templates.NavigationRoot.Fields.FooterCopyright]
            });
        }
Пример #9
0
        public override object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            var topLinks = _topLinksBuilder.GetTopLinks(GetContextItem(rendering, renderingConfig), rendering);

            return(new
            {
                links = topLinks
            });
        }
Пример #10
0
        //Function to return rendering placeholder
        private JObject addPlaceHolderPath(Sitecore.Mvc.Presentation.Rendering rendering,
                                           IRenderingConfiguration renderingConfig)
        {
            var result     = base.ResolveContents(rendering, renderingConfig) ?? new JObject();
            var jsonResult = (JObject)result;

            jsonResult[PlaceholderPathKey] = rendering.Placeholder;
            return(jsonResult);
        }
Пример #11
0
        public override object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            var contextItem = GetContextItem(rendering, renderingConfig);

            return(new
            {
                Links = navigationBuilder.GetNavigationLinks(contextItem, rendering)
            });
        }
        public object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            var settings = this.storefrontContext.StorefrontConfiguration.CountriesRegionsSettings.CountryRegionsValues;

            return(new
            {
                Countries = this.mapper.Map <IEnumerable <CountryRegionModel>, IEnumerable <CountryRegion> >(settings)
            });
        }
        public object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            IWeatherService WeatherService = DependencyResolver.Current.GetService <IWeatherService>();

            return(new
            {
                country = WeatherService.GetLocationCountry(),
                city = WeatherService.GetLocationCity(),
            });
        }
Пример #14
0
        public override object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            var rootItem = GetNavigationRootItem(GetContextItem(rendering, renderingConfig));

            Assert.IsNotNull(rootItem, "Could not locate a navigation root item.");
            return(new
            {
                LogoSvgPath = rootItem[Templates.NavigationRootItem.Fields.LogoSvgPath],
                Links = _navigationBuilder.GetNavigationLinks(rootItem)
            });
        }
Пример #15
0
        public override object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            var contentList = __contentListBuilder.GetContentList(GetContextItem(rendering, renderingConfig), rendering);

            return(new
            {
                title = contentList.Title,
                items = contentList.Items,
                listType = GetContentListType(rendering.Parameters, Constants.RenderingParameters.ListType),
                limit = GetContentListLimit(rendering.Parameters, Constants.RenderingParameters.Limit)
            });
        }
Пример #16
0
        public override object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            //TODO Replace with correct path - Example of getting rendering field items to get path of card ID's
            string getCardPath = rendering.Item.Fields["sample1"].ToString();

            var             cardsToSerialize = new cardItems();
            List <aiqClass> cardList         = new List <aiqClass>();

            try
            {
                //TODO null check
                string   cardIDList = HttpContext.Current.Request.QueryString["cardIDList"];
                string[] cardIDs    = cardIDList.Split(',');
                foreach (var cardID in cardIDs)
                {
                    var item = Sitecore.Context.Database.GetItem(getCardPath + cardID);
                    if (item != null)
                    {
                        var associatedItem = Sitecore.Context.Database.GetItem(item["AssociatedItem"]);
                        if (associatedItem != null)
                        {
                            try
                            {
                                //TODO get subtext, mobile image, etc.
                                //var layoutInfo = Sitecore.Context.Database.GetItem(associatedItem["Layout"]);
                                Sitecore.Data.Fields.LinkField desktopImage = associatedItem.Fields["DesktopImage"];
                                aiqClass aiqItem = new aiqClass();
                                aiqItem.cardId       = item["CardID"];
                                aiqItem.heading      = associatedItem["Heading"];
                                aiqItem.desktopImage = desktopImage.Value;
                                aiqItem.layout       = associatedItem["Layout"];
                                cardList.Add(aiqItem);
                            }
                            catch (Exception ex)
                            {
                                //log error
                                //do nothing
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //Log error
                return(null);
            }
            JObject json = new JObject();

            json["cards"]            = JToken.FromObject(cardList);
            json[PlaceholderPathKey] = rendering.Placeholder;
            return(json);
        }
Пример #17
0
        private bool ContainsRecursiveRenderedRendering(
            Item item,
            RenderedPlaceholderElement renderedItemElement,
            IRenderingConfiguration renderingConfiguration,
            int nestingLevel  = 0,
            bool itemRendered = false)
        {
            if (!(renderedItemElement is RenderedJsonRendering rendering) ||
                string.IsNullOrEmpty(rendering.DataSource))
            {
                return(false);
            }

            var datasourceId = GetIdFromDataSource(item, rendering);

            if (datasourceId == item.ID && nestingLevel > 1 || nestingLevel > 15)
            {
                return(true);
            }

            nestingLevel++;

            if (!string.IsNullOrEmpty(rendering.DataSource) &&
                rendering.RenderingName == Constants.SnippetRenderingName &&
                item.TemplateID == Constants.SnippedItemTemplateId &&
                !itemRendered)
            {
                if (CheckSnippetsContainsRecursiveElements(item, renderingConfiguration, nestingLevel, rendering))
                {
                    return(true);
                }
            }

            if (rendering.Placeholders == null)
            {
                return(false);
            }

            foreach (var renderingPlaceholder in rendering.Placeholders)
            {
                if (renderingPlaceholder.Elements.Any(
                        renderingPlaceholderElement => ContainsRecursiveRenderedRendering(
                            item,
                            renderingPlaceholderElement,
                            renderingConfiguration,
                            nestingLevel)))
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #18
0
        protected override RenderedJsonRendering CreateResultInstance(RenderJsonRenderingArgs args)
        {
            _renderingConfiguration = args.RenderingConfiguration;

            //Note: the constructor below is different for Sitecore 9.x and 10. The below will only work in Headless Services for Sitecore 10.
            return(new RenderedJsonRendering()
            {
                Name = args.Rendering.RenderingItem.Name,
                DataSource = args.Rendering.DataSource,
                RenderingParams = SerializeRenderingParams(args.Rendering),
                Uid = args.Rendering.UniqueId
            });
        }
Пример #19
0
        public object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            //if you want to access the datasource item
            var datasource = !string.IsNullOrEmpty(rendering.DataSource)
                ? rendering.RenderingItem?.Database.GetItem(rendering.DataSource)
                : null;

            return(new
            {
                name = datasource.Name,
                date = DateTime.Now,
                hello = "world"
            });
        }
Пример #20
0
        private bool ContainsRecursiveSnippet(
            Item item,
            List <RenderedPlaceholderElement> renderedItemElements,
            IRenderingConfiguration renderingConfiguration)
        {
            foreach (var renderedItemElement in renderedItemElements)
            {
                if (ContainsRecursiveRenderedRendering(item, renderedItemElement, renderingConfiguration, default, true))
                {
                    return(true);
                }
            }

            return(false);
        }
        public override object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            var header   = HeaderBuilder.GetHeader(this.GetContextItem(rendering, renderingConfig));
            var contents = new
            {
                logoLink = this.ProcessItem(header.HomeItem, rendering, renderingConfig),
                navItems = header.NavigationItems.Select(x => new
                {
                    url      = x.Url,
                    isActive = x.IsActive,
                    title    = x.Item[Templates.NavigationItem.Fields.NavigationTitle]
                })
            };

            return(contents);
        }
        public object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            IWeatherService         WeatherService = DependencyResolver.Current.GetService <IWeatherService>();
            List <WeatherDataModel> listdata       = new List <WeatherDataModel>();
            var ret = WeatherService.GetWeathersFromSession();

            if (ret != null)
            {
                listdata = ret.Select(d => new WeatherDataModel(d)
                {
                    ImageUrl = GetWaterTypeImageUrl(d.Type)
                })
                           .ToList();
            }
            return(listdata);
        }
Пример #23
0
        private RenderedItem CustomRenderedItem(
            Item item,
            IRenderingConfiguration renderingConfiguration,
            Guid?parentItemId           = null,
            RenderOptions renderOptions = null)
        {
            var isSnippetItemRenders = item.TemplateID == Constants.SnippedItemTemplateId;
            var renderedItem         = isSnippetItemRenders
                ? GetRenderedElement(renderingConfiguration, item)
                : base.Render(item, renderingConfiguration, renderOptions);

            Assert.ArgumentNotNull(renderedItem, nameof(renderedItem));

            var snippetElements = renderedItem.Elements
                                  .Where(e => GetSnippetComponentCondition(item, e, parentItemId)).ToList();

            if (!snippetElements.Any())
            {
                return(renderedItem);
            }

            if (ContainsRecursiveSnippet(item, snippetElements, renderingConfiguration))
            {
                throw new InvalidOperationException($"The Snippet trying to render itself. Root Snippet ID {item.ID}");
            }

            foreach (var snippetElement in snippetElements)
            {
                var element = snippetElement as RenderedJsonRendering;

                if (element == null)
                {
                    continue;
                }

                var dataSourceItem = Context.Database.GetItem(element.DataSource);
                var rendered       = CustomRenderedItem(dataSourceItem, renderingConfiguration, renderedItem.ItemId);

                FillRenderedItemsForSnippets(rendered, element);
            }

            return(renderedItem);
        }
Пример #24
0
        private bool CheckSnippetsContainsRecursiveElements(
            Item item,
            IRenderingConfiguration renderingConfiguration,
            int nestingLevel,
            RenderedJsonRendering rendering)
        {
            var datasourceItem    = item.Database.GetItem(rendering.DataSource);
            var renderedRendering = GetRenderedElement(renderingConfiguration, datasourceItem);

            foreach (var renderedRenderingPlaceholder in renderedRendering.Placeholders)
            {
                if (renderedRenderingPlaceholder.Elements.Any(
                        renderingPlaceholderElement => ContainsRecursiveRenderedRendering(
                            item,
                            renderingPlaceholderElement,
                            renderingConfiguration,
                            nestingLevel)))
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #25
0
        public override object ResolveContents(
            Sitecore.Mvc.Presentation.Rendering rendering,
            IRenderingConfiguration renderingConfig)
        {
            RenderingItem renderingItem = rendering.RenderingItem;

            if (renderingItem == null)
            {
                return(addPlaceHolderPath(rendering, renderingConfig));
            }

            string str = renderingItem.InnerItem[Sitecore.JavaScriptServices.Core.FieldIDs.JsonRendering.GraphQLQuery];

            if (string.IsNullOrWhiteSpace(str))
            {
                return(addPlaceHolderPath(rendering, renderingConfig));
            }
            AppConfiguration appConfiguration = this._configurationResolver.ResolveForItem(Context.Item);

            if (appConfiguration == null)
            {
                this._log.Warn("[JSS] - Rendering " + renderingItem.InnerItem.Paths.FullPath + " defined a GraphQL query to resolve its data, but when rendered on item " + Context.Item.Paths.FullPath + " it was not within a known JSS app path. The GraphQL query will not be used.", (object)this);
                return(addPlaceHolderPath(rendering, renderingConfig));
            }
            if (string.IsNullOrWhiteSpace(appConfiguration.GraphQLEndpoint))
            {
                this._log.Error("[JSS] - The JSS app " + appConfiguration.Name + " did not have a graphQLEndpoint set, but rendering " + renderingItem.InnerItem.Paths.FullPath + " defined a GraphQL query to resolve its data. The GraphQL query will not be used until an endpoint is defined on the app config.", (object)this);
                return(addPlaceHolderPath(rendering, renderingConfig));
            }
            IGraphQLEndpoint graphQlEndpoint;

            if (!this._graphQLEndpoints.TryGetValue(appConfiguration.GraphQLEndpoint, out graphQlEndpoint))
            {
                this._log.Error("[JSS] - The JSS app " + appConfiguration.Name + " is set to use GraphQL endpoint " + appConfiguration.GraphQLEndpoint + ", but no GraphQL endpoint was registered with this URL. GraphQL resolution will not be used.", (object)this);
                return(addPlaceHolderPath(rendering, renderingConfig));
            }
            GraphQLAwareRenderingContentsResolver.LocalGraphQLRequest localGraphQlRequest1 = new GraphQLAwareRenderingContentsResolver.LocalGraphQLRequest();
            localGraphQlRequest1.Query = str;
            GraphQLAwareRenderingContentsResolver.LocalGraphQLRequest localGraphQlRequest2 = localGraphQlRequest1;
            localGraphQlRequest2.LocalVariables.Add("contextItem", (object)Context.Item.ID.Guid.ToString());
            localGraphQlRequest2.LocalVariables.Add("datasource", (object)rendering.DataSource);

            //TODO Replace with correct path - Example of getting rendering field items to get path of card ID's
            string getCardPath = rendering.Item.Fields["sample1"].ToString();

            try
            {
                string   cardIDList = HttpContext.Current.Request.QueryString["cardIDList"];
                string[] cardIDs    = cardIDList.Split(',');
                int      cardInt    = 1;
                foreach (var cardID in cardIDs)
                {
                    localGraphQlRequest2.LocalVariables.Add("cardID" + cardInt, getCardPath + cardID);
                    cardInt++;
                }
            }
            catch (Exception ex)
            {
                this._log.Error("[JSS] - Something went wrong parsing the comma delimited query string parameter for cardIDList - " + ex.Message.ToString(), (object)this);
            }

            IDocumentExecuter executor = graphQlEndpoint.CreateDocumentExecutor();
            ExecutionOptions  options  = graphQlEndpoint.CreateExecutionOptions((GraphQLRequest)localGraphQlRequest2, !HttpContext.Current.IsCustomErrorEnabled);

            if (options == null)
            {
                throw new ArgumentException("Endpoint returned null options.");
            }
            TransformationResult transformationResult = graphQlEndpoint.SchemaInfo.QueryTransformer.Transform((GraphQLRequest)localGraphQlRequest2);

            if (transformationResult.Errors != null)
            {
                return (object)new ExecutionResult()
                       {
                           Errors = transformationResult.Errors
                       }
            }
            ;
            options.Query    = transformationResult.Document.OriginalQuery;
            options.Document = transformationResult.Document;
            if (options.Document.Operations.Any <Operation>((Func <Operation, bool>)(op => (uint)op.OperationType > 0U)))
            {
                throw new InvalidOperationException("Cannot use mutations or subscriptions in a datasource query. Use queries only.");
            }
            using (QueryTracer queryTracer = graphQlEndpoint.Performance.TrackQuery((GraphQLRequest)localGraphQlRequest2, options))
            {
                ExecutionResult result = this._asyncHelpers.RunSyncWithThreadContext <ExecutionResult>((Func <Task <ExecutionResult> >)(() => executor.ExecuteAsync(options)));
                graphQlEndpoint.Performance.CollectMetrics(graphQlEndpoint.SchemaInfo.Schema, (IEnumerable <Operation>)options.Document.Operations, result);
                new QueryErrorLog((ILogger) new BaseLogAdapter(this._log)).RecordQueryErrors(result);
                queryTracer.Result = result;
                //return (object)this._documentWriter.ToJObject((object)result);
                var jsonResultToConvert = (object)this._documentWriter.ToJObject((object)result);
                var jsonResult          = (JObject)jsonResultToConvert;
                jsonResult[PlaceholderPathKey] = rendering.Placeholder;
                return(jsonResult);
            }
        }
        /// <summary>
        /// Resolver modification product list show best choosed items for actual session
        /// define:
        /// /sitecore/system/Modules/Layout Service/Rendering Contents Resolvers/TigWeatherResolver
        /// usage in rendering
        /// /sitecore/layout/Renderings/Project/traveler-last-hope/ProductsList
        /// field name 'Rendering Contents Resolver'
        ///
        /// </summary>
        /// <param name="rendering"></param>
        /// <param name="renderingConfig"></param>
        /// <returns></returns>
        public object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            var productFolder = rendering.Item.Database
                                .GetItem("/sitecore/content/traveler-last-hope/Content/Data/PMD/Products");
            IWeatherService WeatherService = DependencyResolver.Current.GetService <IWeatherService>();

            var weatherSessionList = WeatherService.GetWeathersFromSession();

            if (weatherSessionList == null)
            {
                weatherSessionList = new List <WeatherData>();
            }

            List <Sitecore.Data.Items.Item> productList = new List <Sitecore.Data.Items.Item>();
            Set <string> addedProducts = new Set <string>();

            foreach (var weather in weatherSessionList)
            {
                foreach (Sitecore.Data.Items.Item product in productFolder.GetChildren())
                {
                    string[] strArray = product
                                        .Fields[new ID(ProductModel.WeatherTypeFieldName)]
                                        .Value
                                        .Split(new char[1] {
                        '|'
                    }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (string key in strArray)
                    {
                        if (weather.Type == MapperHelper.WeatherTypeSet[key] && !addedProducts.Contains(product.ID.ToString()))
                        {
                            addedProducts.Add(product.ID.ToString());
                            productList.Add(product);
                        }
                    }
                }
            }

            // removing items that have already been bought
            var productBoughtList = WeatherService.GetProductsFromSession();

            if (productBoughtList != null)
            {
                foreach (var product in productBoughtList)
                {
                    if (addedProducts.Contains(product))
                    {
                        foreach (var productSitecore in productList)
                        {
                            if (productSitecore.ID.ToString() == product)
                            {
                                productList.Remove(productSitecore);
                                break;
                            }
                        }
                    }
                }
            }
            List <ProductModel> resultList = new List <ProductModel>();

            foreach (var productSitecore in productList)
            {
                ImageField imageField = productSitecore.Fields[new ID(ProductModel.ImageFieldName)];
                string     imageUrl   = "";
                if (imageField?.MediaItem != null)
                {
                    var image = new MediaItem(imageField.MediaItem);
                    imageUrl = StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(image));
                }

                resultList.Add(new ProductModel()
                {
                    Category    = productSitecore.Fields[new ID(ProductModel.CategoryFieldName)].Value,
                    Description = productSitecore.Fields[new ID(ProductModel.DescriptionFieldName)].Value,
                    Image       = imageUrl,
                    Name        = productSitecore.Fields[new ID(ProductModel.NameFieldName)].Value,
                    Price       = productSitecore.Fields[new ID(ProductModel.PriceFieldName)].Value,
                    WeatherType = productSitecore.Fields[new ID(ProductModel.WeatherTypeFieldName)].Value,
                });
            }

            return(resultList);
        }
Пример #27
0
        public override object ResolveContents(Sitecore.Mvc.Presentation.Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            var contextItem = GetContextItem(rendering, renderingConfig);

            var linkField          = (LookupField)contextItem.Fields[Templates.CategoryNavigation.StartingPoint];
            var categorySitecoreId = linkField.TargetID;
            var childCategories    = GetChildCategories(categorySitecoreId);

            return(new
            {
                Categories = childCategories?.Select(x => new
                {
                    x.ID,
                    Path = x.Paths.FullPath,
                    x.DisplayName,
                    Active = Sitecore.Context.Item.Paths.FullPath.Contains(x.Paths.FullPath)
                }).ToArray()
            });
        }
        public override object ResolveContents(Sitecore.Mvc.Presentation.Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            var contextItem = GetContextItem(rendering, renderingConfig);

            if (contextItem == null)
            {
                return(new { });
            }

            var selectionField = (DatasourceField)contextItem.Fields[Templates.Products.Selection];

            var query = selectionField.Value;

            if (String.IsNullOrEmpty(query))
            {
                return(new { });
            }

            var searchItems   = new List <CommerceSellableItemSearchResultItem>();
            var searchManager = CommerceTypeLoader.CreateInstance <ICommerceSearchManager>();

            using (var context = searchManager.GetIndex().CreateSearchContext())
            {
                var searchStringModels = SearchStringModel.ParseDatasourceString(query);

                searchItems = LinqHelper.CreateQuery <CommerceSellableItemSearchResultItem>(context, searchStringModels)
                              .Where(x => x.CommerceSearchItemType == CommerceSearchItemType.SellableItem)
                              .Where(x => x.Language == Sitecore.Context.Language.Name)
                              .ToList();
            }

            searchItems = searchItems
                          .GroupBy(x => x.ProductId)
                          .Select(x => x.First())
                          .ToList();

            // Create products from search result
            var products = new List <object>();

            foreach (var searchItem in searchItems)
            {
                var sitecoreItem = searchItem.GetItem();

                // Add variants
                if (sitecoreItem.HasChildren)
                {
                    foreach (Sitecore.Data.Items.Item child in sitecoreItem.GetChildren())
                    {
                        products.Add(GetProduct(searchItem, sitecoreItem, child.Name));
                    }
                }
                // No variants add single product
                else
                {
                    products.Add(GetProduct(searchItem, sitecoreItem));
                }
            }

            return(new
            {
                Heading = ((TextField)contextItem.Fields[Templates.Products.Heading]).Value,
                Products = products.ToArray()
            });
        }
Пример #29
0
        public override object ResolveContents(Sitecore.Mvc.Presentation.Rendering rendering, IRenderingConfiguration renderingConfig)
        {
            var childCategories = GetChildCategories(Sitecore.Context.Item);

            return(new
            {
                Categories = childCategories.Select(x => new
                {
                    x.ID,
                    Path = x.Paths.FullPath,
                    x.DisplayName,
                    Active = Sitecore.Context.Item.ID == x.ID
                }).ToArray()
            });
        }
Пример #30
0
 public override object ResolveContents(Rendering rendering, IRenderingConfiguration renderingConfig)
 {
     // return empty because we don't want to output data from the route for the configuration
     return(new { });
 }