Exemple #1
0
        public override void Process(GetXmlBasedLayoutDefinitionArgs args)
        {
            if (args.Result != null)
            {
                return;
            }

            Item obj = args.ContextItem ?? PageContext.Current.Item;

            if (obj.TemplateID != ProductModelTemplateID &&
                obj.TemplateID != ProductTypeTemplateID)
            {
                return;
            }
            else
            {
                while (obj != null && obj.TemplateID != ProductItemTemplateID)
                {
                    obj = obj.Parent;
                }
                if (obj.TemplateID == ProductItemTemplateID)
                {
                    args.Result = this.GetFromField(obj);
                }
            }
        }
        /// <summary>
        /// Processes the placeholder replacements 
        /// </summary>
        /// <param name="args"></param>
        /// <param name="currentLayout"></param>
        /// <param name="placeholders"></param>
        private void FindPlaceholderReplacement(GetXmlBasedLayoutDefinitionArgs args,
            string[] placeholders,
            Func<Item, XDocument, string, bool> placeholderReplacementAction)
        {
            Item currentItem = args.ContextItem ?? Sitecore.Mvc.Presentation.PageContext.Current.Item;
            Item parentItem = currentItem.Parent;

            List<string> placeholdersToFind = new List<string>(placeholders);

            //Walk up parents
            while (parentItem != null && placeholdersToFind.Any())
            {
                XDocument layout = GetLayoutXml(parentItem);

                if (layout == null)
                {
                    break;
                }

                //Duplicate the list so we can remove placeholders we have found in parents
                List<string> currentPlaceholdersNeeded = new List<string>(placeholdersToFind);

                //Find any content in the placeholder
                foreach (string placeholder in currentPlaceholdersNeeded)
                {
                    if (placeholderReplacementAction(parentItem, layout, placeholder.Trim()))
                    {
                        //If something for the placeholder was found, remove it from the list of placeholders we are looking for
                        placeholdersToFind.Remove(placeholder);
                    }
                }

                parentItem = parentItem.Parent;
            }
        }
        protected virtual internal string CreateCompositesXmlCacheKey(GetXmlBasedLayoutDefinitionArgs args, Item currentItem, Item siteItem, IList <ID> renderingIds)
        {
            var pagePath = args.PageContext.RequestContext.HttpContext.Request.Path;

            //Cache the layout for each path if it's a wildcard page and there is a rules based snippet on the page
            if (currentItem.Name == "*" && renderingIds.Any(r => r == Renderings.RulesBasedSnippet.ID))
            {
                return($"SXA::{Constants.CompositesXmlPropertiesKey}::{siteItem.ID}::{Context.Database.Name}::{Context.Device.ID}::{Context.Language.Name}::{currentItem.ID}::{pagePath}");
            }
            else
            {
                return($"SXA::{Constants.CompositesXmlPropertiesKey}::{siteItem.ID}::{Context.Database.Name}::{Context.Device.ID}::{Context.Language.Name}::{currentItem.ID}");
            }
        }
        public override void Process(GetXmlBasedLayoutDefinitionArgs args)
        {
            if (args.Result == null)
            {
                return;
            }

            var item   = Sitecore.Mvc.Presentation.PageContext.Current.Item;
            var device = Sitecore.Mvc.Presentation.PageContext.Current.Device;

            if (item == null || item.Parent == null || device == null)
            {
                return;
            }

            var deviceId = ID.Parse(string.Format("{{{0}}}", device.Id.ToString().ToUpper()));

            args.Result = MergeWithCascadedRenderings(args.Result, item.Parent, deviceId);
        }
        public override void Process(GetXmlBasedLayoutDefinitionArgs args)
        {
            if (args.Result == null)
            {
                return;
            }

            var pageItem = Sitecore.Mvc.Presentation.PageContext.Current.Item;
            var device   = Sitecore.Mvc.Presentation.PageContext.Current.Device;

            if (device == null)
            {
                return;
            }

            var deviceId = ID.Parse(string.Format("{{{0}}}", device.Id.ToString().ToUpper()));

            args.Result = MergeWithFragmentRenderings(args.Result, deviceId, Sitecore.Mvc.Presentation.PageContext.Current.Database, pageItem);
        }
Exemple #6
0
        public override void Process(GetXmlBasedLayoutDefinitionArgs args)
        {
            if (args.Result != null || PageContext.Current.Item == null)
            {
                return;
            }

            SiteContext siteInfo = SiteContext.Current;

            if (siteInfo == null)
            {
                return;
            }

            string key = string.Format("LayoutXml.{0}.{1}",
                                       Context.Language.Name,
                                       PageContext.Current.Item.ID);

            //TODO: Below commented code would enable caching of the results for performance.
            //TODO: Currently disabled, but should be validated once the actual header components are added.

            //XElement pageLayoutXml = (XElement)HttpContext.Current.Cache[key];
            //if (pageLayoutXml != null && Context.PageMode.IsNormal)
            //{
            //    args.Result = pageLayoutXml;
            //    return;
            //}

            XElement content = GetFromField(PageContext.Current.Item);

            if (content != null && (Context.PageMode.IsPreview || Context.PageMode.IsNormal))
            {
                Item item = PageContext.Current.Item;

                if (item != null &&
                    (item.DescendsFrom(Constants.Templates.HasGlobalStructure.ID)) &&
                    !item.TemplateID.Equals(Constants.Templates.HeaderPage.ID) &&
                    !item.TemplateID.Equals(Constants.Templates.FooterPage.ID))
                {
                    XElement currentPageDxElement = content.Element("d");
                    if (currentPageDxElement == null)
                    {
                        args.Result = content;
                        return;
                    }

                    //if item uses global page structure, pull settings from root item
                    Item rootItem = Context.Database.GetItem(siteInfo.RootPath);

                    //header
                    Item headerItem = MainUtil.GetBool(item[Constants.Templates.HasGlobalStructure.Fields.UseGlobalHeader], false)
                        ? rootItem
                        : item;

                    if (headerItem != null && headerItem.DescendsFrom(Constants.Templates.GlobalPageStructure.ID))
                    {
                        if (!string.IsNullOrEmpty(headerItem[Constants.Templates.GlobalPageStructure.Fields.HeaderItem]))
                        {
                            currentPageDxElement.Add(GetContent(headerItem[Constants.Templates.GlobalPageStructure.Fields.HeaderItem]));
                        }
                    }


                    //footer
                    Item footerItem = MainUtil.GetBool(item[Constants.Templates.HasGlobalStructure.Fields.UseGlobalFooter], false)
                       ? rootItem
                       : item;

                    if (footerItem != null && footerItem.DescendsFrom(Constants.Templates.GlobalPageStructure.ID))
                    {
                        if (!string.IsNullOrEmpty(footerItem[Constants.Templates.GlobalPageStructure.Fields.FooterItem]))
                        {
                            currentPageDxElement.Add(GetContent(footerItem[Constants.Templates.GlobalPageStructure.Fields.FooterItem]));
                        }
                    }
                }
            }

            try
            {
                if (Context.PageMode.IsPreview || Context.PageMode.IsNormal)
                {
                    HttpContext.Current.Cache.Add(
                        key,
                        content,
                        null,
                        DateTime.Now.AddMinutes(5),
                        Cache.NoSlidingExpiration,
                        CacheItemPriority.AboveNormal,
                        null);
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error in GetFromLayoutField processor", ex, this);
            }

            args.Result = content;
        }
 public override void Process(GetXmlBasedLayoutDefinitionArgs args)
 {
     ProcessFallbackRenderings(args);
 }
        /// <summary>
        /// Process fallback messages
        /// </summary>
        /// <param name="args"></param>
        private void ProcessFallbackRenderings(GetXmlBasedLayoutDefinitionArgs args)
        {
            XElement currentLayout = args.Result;

            XElement fallbackRendering = currentLayout.XPathSelectElement("d/r[@id='" + FALLBACK_RENDERING_ID + "' and not(@FallbackLocations)]");

            //Find the fallback rendering
            while (fallbackRendering != null)
            {
                XAttribute par = fallbackRendering.Attribute("par");

                if (par != null)
                {
                    string placeholdersParameter = HttpUtility.UrlDecode(StringUtil.ExtractParameter("FallbackPlaceholders", par.Value));

                    if (!string.IsNullOrEmpty(placeholdersParameter))
                    {
                        string[] placeholders = placeholdersParameter.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);

                        //If page editor, only store the parent path
                        if (Sitecore.Context.PageMode.IsPageEditor)
                        {
                            List<string> parents = new List<string>();

                            FindPlaceholderReplacement(args, placeholders, (parentItem, layout, placeholder) =>
                            {
                                if (GetFallbackRenderings(layout, placeholder).Any())
                                {
                                    parents.Add(parentItem.Paths.FullPath);

                                    return true;
                                }

                                return false;
                            });

                            //Add parent fallback locations for the content editor
                            string parentString = string.Join(", ", parents.Distinct());

                            fallbackRendering.Add(new XAttribute(FALLBACK_LOCATIONS_PROPERTY, parentString));
                        }
                        else
                        {
                            List<XElement> replacements = new List<XElement>();

                            FindPlaceholderReplacement(args, placeholders, (parentItem, layout, placeholder) =>
                            {
                                if (GetFallbackRenderings(layout, placeholder).Any())
                                {
                                    replacements.AddRange(GetFallbackRenderings(layout, placeholder));

                                    return true;
                                }

                                return false;
                            });

                            if (replacements.Any())
                            {
                                //Replace the contents with the renderings found in the parent
                                fallbackRendering.AddAfterSelf(replacements);
                            }

                            fallbackRendering.Remove();
                        }
                    }
                }

                fallbackRendering = currentLayout.XPathSelectElement("d/r[@id='" + FALLBACK_RENDERING_ID + "' and not(@FallbackLocations)]");
            }
        }
        public override void Process(GetXmlBasedLayoutDefinitionArgs args)
        {
            Item     currentItem = args.ContextItem ?? args.PageContext.Item ?? Sitecore.Mvc.Presentation.PageContext.Current.Item;
            XElement result      = args.Result;

            if (result == null || !currentItem.Paths.IsContentItem)
            {
                return;
            }

            Item siteItem = ServiceLocator.ServiceProvider.GetService <IMultisiteContext>().GetSiteItem(currentItem);

            if (siteItem == null)
            {
                return;
            }

            List <XElement> compositeComponents = GetCompositeComponents(result).ToList();

            if (!compositeComponents.Any())
            {
                return;
            }

            var renderingIds = compositeComponents.Select(c => c.ToXmlNode()).Select(n => ParseRenderingId(n)).ToList();
            DictionaryCacheValue dictionaryCacheValue = DictionaryCache.Get(CreateCompositesXmlCacheKey(args, currentItem, siteItem, renderingIds));

            if (PageMode.IsNormal && dictionaryCacheValue != null && dictionaryCacheValue.Properties.ContainsKey(Constants.CompositesXmlPropertiesKey))
            {
                args.Result = XElement.Parse(dictionaryCacheValue.Properties[Constants.CompositesXmlPropertiesKey].ToString());
            }
            else
            {
                if (!args.CustomData.ContainsKey(Constants.CompositeRecursionLevel))
                {
                    args.CustomData.Add(Constants.CompositeRecursionLevel, 1);
                }
                else
                {
                    args.CustomData[Constants.CompositeRecursionLevel] = (int)args.CustomData[Constants.CompositeRecursionLevel] + 1;
                }

                LayoutDefinition definition = null;
                bool             hasPersonalizedRenderings = false;
                if (ShouldMigratePersonalizationSettings())
                {
                    definition = GetLayoutDefinitionWithPersonalizationOnly(result, out hasPersonalizedRenderings);
                }

                foreach (XElement rendering in compositeComponents)
                {
                    ProcessCompositeComponent(args, rendering, result);
                }

                List <XElement> xelementList = result.Descendants("d").ToList();
                if (ShouldMigratePersonalizationSettings() & hasPersonalizedRenderings)
                {
                    xelementList = MigratePersonalizationSettings(result, definition);
                }

                args.Result.Descendants("d").Remove();
                args.Result.Add(xelementList);
                if (!PageMode.IsNormal || HasPersonalizationRules(args) || HasMVTests(args))
                {
                    return;
                }

                StoreValueInCache(CreateCompositesXmlCacheKey(args, currentItem, siteItem, renderingIds), args.Result.ToString());
            }
        }
        protected override void ProcessCompositeComponent(
            GetXmlBasedLayoutDefinitionArgs args,
            XElement rendering,
            XElement layoutXml)
        {
            var    xmlNode            = rendering.ToXmlNode();
            var    renderingModel     = new RenderingModel(xmlNode);
            var    contextItem        = args.PageContext.Item;
            var    renderingReference = new RenderingReference(xmlNode, contextItem.Language, contextItem.Database);
            string datasource         = renderingModel.DataSource;

            if (TestMVTestEnabled(renderingReference) && ContentTestingService != null && renderingModel.MultiVariateTestId != (ID)null)
            {
                args.CustomData.Add(Constants.MultivariateTestEnabled, true);
                var multivariateTestDatasource = ContentTestingService.GetMultivariateTestDatasource(renderingModel.MultiVariateTestId, args.PageContext.Item, args.PageContext.Device.DeviceItem.ID);
                if (multivariateTestDatasource != null)
                {
                    datasource = multivariateTestDatasource;
                }
            }

            if (TestPersonalizationEnabled(renderingReference))
            {
                datasource = GetCustomizedRenderingDataSource(renderingModel, contextItem);
            }

            if (string.IsNullOrEmpty(datasource))
            {
                Log.Warn("Composite component datasource is empty", rendering);
            }
            else
            {
                if (datasource.StartsWith("local:", StringComparison.OrdinalIgnoreCase))
                {
                    contextItem = SwitchContextItem(rendering, contextItem);
                }
                if (datasource.StartsWith("page:", StringComparison.OrdinalIgnoreCase))
                {
                    contextItem = Context.Item;
                }
                var datasourceItem = ResolveCompositeDatasource(datasource, contextItem) ?? ResolveCompositeDatasource(datasource, Context.Item);
                if (datasourceItem == null)
                {
                    Log.Error("Composite component has a reference to non-existing datasource : " + datasource, this);
                }
                else
                {
                    var dynamicPlaceholderId = ExtractDynamicPlaceholderId(args, rendering);
                    var sid = string.Empty;
                    if (rendering.Attribute("sid") != null)
                    {
                        sid = rendering.Attribute("sid").Value;
                    }

                    var placeholder = renderingModel.Placeholder;
                    if (!DetectDatasourceLoop(args, datasourceItem))
                    {
                        var composites = compositeService.GetCompositeItems(datasourceItem).Select((item, idx) => new KeyValuePair <int, Item>(idx + 1, item)).ToList();
                        foreach (KeyValuePair <int, Item> composite in composites)
                        {
                            if (!TryMergeComposites(args, rendering, layoutXml, composite, dynamicPlaceholderId, placeholder, sid))
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        AbortRecursivePipeline(args, rendering);
                    }

                    RollbackAntiLoopCollection(args, datasourceItem);
                }
            }
        }