Ejemplo n.º 1
0
        private static void ApplyActionToAllRenderings(Item item, ID fieldId, Func <RenderingDefinition, RenderingActionResult> action)
        {
            var currentLayoutXml = LayoutField.GetFieldValue(item.Fields[fieldId]);

            if (string.IsNullOrEmpty(currentLayoutXml))
            {
                return;
            }

            var newXml = ApplyActionToLayoutXml(currentLayoutXml, action);

            if (newXml == null)
            {
                return;
            }

            // save a modified layout value
            using (new SecurityDisabler())
            {
                using (new EditContext(item))
                {
                    LayoutField.SetFieldValue(item.Fields[fieldId], newXml);
                }
            }
        }
Ejemplo n.º 2
0
        public void ShouldBeAbleToSetLayoutFieldValue()
        {
            ID itemId = ID.NewID;

            using (var db = new Db
            {
                new DbItem("page", itemId)
                {
                    new DbField(FieldIDs.LayoutField)
                    {
                        Value = "<r/>"
                    }
                }
            })
            {
                DbItem fakeItem = db.DataStorage.GetFakeItem(itemId);
                Assert.Equal("<r/>", fakeItem.Fields[FieldIDs.LayoutField].Value);

                var item = db.GetItem("/sitecore/content/page");

                var layoutField = item.Fields[FieldIDs.LayoutField];
                Assert.Equal("<r/>", layoutField.Value);

                Assert.Equal("<r/>", item[FieldIDs.LayoutField]);
                Assert.Equal("<r/>", item["__Renderings"]);

                Assert.Equal("<r/>", LayoutField.GetFieldValue(item.Fields[FieldIDs.LayoutField]));
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        ///     Invokes Action on all Final Renderings on item
        /// </summary>
        private static void ApplyActionToLayoutField(Item item, ID fieldId, Action <RenderingDefinition> action)
        {
            var currentLayoutXml = LayoutField.GetFieldValue(item.Fields[fieldId]);

            if (string.IsNullOrEmpty(currentLayoutXml))
            {
                return;
            }

            var newXml = ApplyActionToLayoutXml(currentLayoutXml, action);

            if (newXml == null)
            {
                return;
            }

            using (new SecurityDisabler())
            {
                using (new EditContext(item))
                {
                    // NOTE: when dealing with layouts its important to get and set the field value with LayoutField.Get/SetFieldValue()
                    // if you fail to do this you will not process layout deltas correctly and may instead override all fields (breaking full inheritance),
                    // or attempt to get the layout definition for a delta value, which will result in your wiping the layout details when they get saved.
                    LayoutField.SetFieldValue(item.Fields[fieldId], newXml);
                }
            }
        }
Ejemplo n.º 4
0
        protected override void OnLoad(EventArgs e)
        {
            Assert.CanRunApplication("Content Editor/Ribbons/Chunks/Layout");
            Assert.ArgumentNotNull(e, "e");
            base.OnLoad(e);
            this.Tabs.OnChange += (sender, args) => this.Refresh();
            if (!Context.ClientPage.IsEvent)
            {
                Item currentItem = GetCurrentItem();
                Assert.IsNotNull(currentItem, "Item not found");
                this.Layout = LayoutField.GetFieldValue(currentItem.Fields[FieldIDs.LayoutField]);
                Field field = currentItem.Fields[FieldIDs.FinalLayoutField];
                if (currentItem.Name != "__Standard Values")
                {
                    this.LayoutDelta = field.GetValue(false, false) ?? field.GetInheritedValue(false);
                }
                else
                {
                    this.LayoutDelta = field.GetStandardValue();
                }
                this.ToggleVisibilityOfControlsOnFinalLayoutTab(currentItem);
                this.Refresh();
            }
            SiteContext site = Context.Site;

            if (site != null)
            {
                site.Notifications.ItemSaved += new ItemSavedDelegate(this.ItemSavedNotification);
            }
        }
        public void Process(ExtractRenderingsDatasourceArgs args)
        {
            if (string.IsNullOrWhiteSpace(FieldId) || !ID.IsID(FieldId))
            {
                return;
            }

            var fieldId = new ID(FieldId);

            var layoutField = args.IndexedItem.Fields[fieldId];

            var layoutXml = LayoutField.GetFieldValue(layoutField);

            if (string.IsNullOrEmpty(layoutXml))
            {
                return;
            }

            var renderings = args.IndexedItem.Visualization.GetRenderings(args.DeviceItem, false);

            if (renderings == null || renderings.Length == 0)
            {
                return;
            }

            for (var renderingIndex = renderings.Length - 1; renderingIndex >= 0; renderingIndex--)
            {
                var rendering = renderings[renderingIndex];

                if (rendering == null || rendering.Database != args.IndexedItem.Database)
                {
                    continue;
                }

                if (!args.IndexableRenderingIds.Contains(rendering.RenderingID))
                {
                    continue;
                }

                var datasourceId = rendering.Settings.DataSource;

                if (!ID.IsID(datasourceId))
                {
                    continue;
                }

                var datasourceItem = GetDatasourceWithFallback(args.IndexedItem.Database, new ID(datasourceId), args.IndexedItem.Language);

                if (datasourceItem == null || datasourceItem.Versions.Count == 0)
                {
                    continue;
                }

                args.DatasourceItems.Add(datasourceItem);
            }
        }
Ejemplo n.º 6
0
        public void ShouldWorkWithLayoutDeltas()
        {
            ID templateId = ID.NewID;

            string templateLayout =
                @"<r xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
            <d id=""{FE5D7FDF-89C0-4D99-9AA3-B5FBD009C9F3}"" l=""{4CA7478E-6184-4890-9072-1156DB468A1B}"" />
            <d id=""{EF7176AE-2502-401A-96C0-1E9918A982F7}"" l=""{4CA7478E-6184-4890-9072-1156DB468A1B}"" /> 
            <d id=""{5A6E7DC3-987F-4E74-AF78-AC0E544975F2}"" l=""{4CA7478E-6184-4890-9072-1156DB468A1B}"" />
          </r>";

            string itemDelta =
                @"<r xmlns:p=""p"" xmlns:s=""s"" p:p=""1"">
              <d id=""{FE5D7FDF-89C0-4D99-9AA3-B5FBD009C9F3}"">
                  <r uid=""{BC2FDEAE-A971-420B-A874-BA5C767C42FE}"" s:id=""{B5BFA387-74C8-416B-98AF-01C9230C24B2}"" s:ph=""Score Content Main"" />
              </d>
          </r>";

            string merged = XmlDeltas.ApplyDelta(templateLayout, itemDelta);

            using (var db = new Db()
            {
                new DbTemplate("main", templateId)
                {
                    { FieldIDs.LayoutField, templateLayout }
                },
                new DbItem("page", ID.NewID, templateId),
                new DbItem("page2", ID.NewID, templateId)
                {
                    new DbField(FieldIDs.LayoutField)
                    {
                        Value = itemDelta
                    }
                }
            })
            {
                Item item = db.GetItem("/sitecore/content/page");

#pragma warning disable 618
                Assert.Equal(templateLayout, StandardValuesManager.Provider.GetStandardValue(item.Fields[FieldIDs.LayoutField]));
#pragma warning restore 618

                Assert.Equal(templateLayout, LayoutField.GetFieldValue(item.Fields[FieldIDs.LayoutField]));
                // standard values
                Assert.Equal(templateLayout, item[FieldIDs.LayoutField]);

                var item2 = db.GetItem("/sitecore/content/page2");
                Assert.Equal(templateLayout, item2.Fields[FieldIDs.LayoutField].GetStandardValue());

                // just checking
                Assert.True(XmlPatchUtils.IsXmlPatch(itemDelta));

                Assert.Equal(merged, LayoutField.GetFieldValue(item2.Fields[FieldIDs.LayoutField]));
            }
        }
Ejemplo n.º 7
0
        public static LayoutDefinition GetFinalLayoutDefinition(this Item item)
        {
            var layoutField = item.Fields[FieldIDs.FinalLayoutField];
            var fieldValue  = LayoutField.GetFieldValue(layoutField);

            if (string.IsNullOrEmpty(fieldValue))
            {
                return(null);
            }

            return(LayoutDefinition.Parse(fieldValue));
        }
Ejemplo n.º 8
0
        private List <KeyValuePair <string, string> > ChangeLayoutFieldForItem(Item currentItem, Field field)
        {
            var result = new List <KeyValuePair <string, string> >();

            string xml = LayoutField.GetFieldValue(field);

            if (!string.IsNullOrWhiteSpace(xml))
            {
                var details = LayoutDefinition.Parse(xml);

                var device     = details.GetDevice(DefaultDeviceId);
                var deviceItem = currentItem.Database.Resources.Devices["Default"];

                var renderings = currentItem.Visualization.GetRenderings(deviceItem, false);

                if (device?.Renderings != null)
                {
                    bool requiresUpdate = false;

                    foreach (RenderingDefinition rendering in device.Renderings)
                    {
                        if (!string.IsNullOrWhiteSpace(rendering.Placeholder))
                        {
                            var newPlaceholder = rendering.Placeholder;
                            foreach (Match match in Regex.Matches(newPlaceholder, PlaceholderRegex, RegexOptions.IgnoreCase))
                            {
                                var renderingId    = match.Value;
                                var newRenderingId = "-{" + renderingId.ToUpper().Substring(1) + "}-0";

                                newPlaceholder = newPlaceholder.Replace(match.Value, newRenderingId);

                                requiresUpdate = true;
                            }

                            result.Add(new KeyValuePair <string, string>(rendering.Placeholder, newPlaceholder));
                            rendering.Placeholder = newPlaceholder;
                        }
                    }

                    if (requiresUpdate)
                    {
                        string newXml = details.ToXml();

                        using (new EditContext(currentItem))
                        {
                            LayoutField.SetFieldValue(field, newXml);
                        }
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Assume convention that rendering name matches prefab name
        /// Lookup item from defined global repository
        /// </summary>
        /// <param name="args"></param>
        public override void Process(CreatePrefabArgs args)
        {
            Assert.IsNotNull(args, "args");
            Assert.IsNotNull(args.Result, "args.Result");
            Assert.IsNotNullOrEmpty(args.Name, "args.Name");
            Assert.IsNotNull(args.DeviceId, "args.DeviceId");
            Assert.IsNotNull(args.LayoutId, "args.LayoutId");

            var prefab = args.Result;

            using (new SecurityDisabler())
            {
                using (new EventDisabler())
                {
                    // Fill Prefab
                    prefab.Editing.BeginEdit();
                    try
                    {
                        // Display Name (if input wasn't valid name)
                        if (prefab.Name != args.Name)
                        {
                            prefab[FieldIDs.DisplayName] = args.Name;
                        }

                        var prefabSharedLayoutField   = prefab.Fields[FieldIDs.LayoutField];
                        var prefabSharedLayout        = LayoutDefinition.Parse(LayoutField.GetFieldValue(prefabSharedLayoutField));
                        DeviceDefinition prefabDevice = prefabSharedLayout.GetDevice(args.DeviceId); // match device

                        // Set Layout
                        prefabDevice.Layout = args.LayoutId;

                        // Add Renderings
                        foreach (var r in args.Renderings)
                        {
                            prefabDevice.AddRendering(r);
                        }

                        LayoutField.SetFieldValue(prefabSharedLayoutField, prefabSharedLayout.ToXml());

                        prefab.Editing.EndEdit(true, true); // Must be silent as to not break content editor context item

                        // Manually clear the cache (because we are in silent mode)
                        prefab.Database.Caches.DataCache.RemoveItemInformation(prefab.ID);
                        prefab.Database.Caches.ItemCache.RemoveItem(prefab.ID);
                    }
                    catch (Exception ex)
                    {
                        prefab.Editing.CancelEdit();
                        Log.Error($"{nameof(FillPrefab)}::{nameof(Process)} - Unable to fill prefab, {args.Result.ID}, {args.Name}", ex, this);
                    }
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Finds all renderings on an item's layout details with valid custom data sources set and returns the data source items.
        /// </summary>
        protected virtual IEnumerable <Item> ExtractRenderingDataSourceItems(Item baseItem)
        {
            string currentLayoutXml = LayoutField.GetFieldValue(baseItem.Fields[FieldIDs.LayoutField]);

            if (string.IsNullOrEmpty(currentLayoutXml))
            {
                yield break;
            }

            LayoutDefinition layout = LayoutDefinition.Parse(currentLayoutXml);

            // loop over devices in the rendering
            for (int deviceIndex = layout.Devices.Count - 1; deviceIndex >= 0; deviceIndex--)
            {
                var device = layout.Devices[deviceIndex] as DeviceDefinition;

                if (device == null)
                {
                    continue;
                }

                // loop over renderings within the device
                for (int renderingIndex = device.Renderings.Count - 1; renderingIndex >= 0; renderingIndex--)
                {
                    var rendering = device.Renderings[renderingIndex] as RenderingDefinition;

                    if (rendering == null)
                    {
                        continue;
                    }

                    // Only renderings on specific placeholders will be considered
                    if (!SitecoreSettings.PlaceholdersToSearch.ToLower().Contains(rendering.Placeholder.ToLower()))
                    {
                        continue;
                    }

                    // if the rendering has a custom data source, we resolve the data source item and place its text fields into the content to add
                    if (!string.IsNullOrWhiteSpace(rendering.Datasource))
                    {
                        var dataSource = baseItem.Database.GetItem(rendering.Datasource, baseItem.Language);


                        if (dataSource != null && dataSource != baseItem)
                        {
                            yield return(dataSource);
                        }
                    }
                }
            }
        }
Ejemplo n.º 11
0
        private void ProcessField(Field field, EqualItems[] matchingItemMap)
        {
            string initialValue;

            if (field.ID == Sitecore.FieldIDs.LayoutField || field.ID == Sitecore.FieldIDs.FinalLayoutField)
            {
                initialValue = LayoutField.GetFieldValue(field);
            }
            else
            {
                initialValue = field.GetValue(true, true);
            }

            if (string.IsNullOrEmpty(initialValue))
            {
                return;
            }

            var value = new StringBuilder(initialValue);

            foreach (var r in matchingItemMap)
            {
                value = value.Replace(r.Source.ID.Guid.ToString("D").ToUpper(), r.Dest.ID.Guid.ToString("D").ToUpper());
                value = value.Replace(r.Source.ID.Guid.ToString("D").ToLower(), r.Dest.ID.Guid.ToString("D").ToLower());
                value = value.Replace(r.Source.ID.Guid.ToString("N").ToUpper(), r.Dest.ID.Guid.ToString("N").ToUpper());
                value = value.Replace(r.Source.ID.Guid.ToString("N").ToLower(), r.Dest.ID.Guid.ToString("N").ToLower());
                value = value.Replace(r.Source.Paths.Path, r.Dest.Paths.Path);
                value = value.Replace(r.Source.Paths.Path.ToLower(), r.Dest.Paths.Path.ToLower(), true);
                if (!r.Source.Paths.IsContentItem)
                {
                    continue;
                }

                value.Replace(r.Source.Paths.ContentPath, r.Dest.Paths.ContentPath);
                value.Replace(r.Source.Paths.ContentPath.ToLower(), r.Dest.Paths.ContentPath.ToLower(), true);
            }

            if (field.ID == FieldIDs.LayoutField || field.ID == FieldIDs.FinalLayoutField)
            {
                using (new Sitecore.Data.Events.EventDisabler())
                    using (new EditContext(field.Item, SecurityCheck.Disable))
                    {
                        LayoutField.SetFieldValue(field, value.ToString());
                    }
            }

            else
            {
                UpdateFieldValue(field, initialValue, value);
            }
        }
Ejemplo n.º 12
0
        protected string UpdateRenderingDataSourses(Item originalItem, Item destinationItem, ID layoutFieldId)
        {
            var layoutString     = destinationItem[layoutFieldId];
            var currentLayoutXml = LayoutField.GetFieldValue(destinationItem.Fields[layoutFieldId]);

            if (string.IsNullOrEmpty(currentLayoutXml) || string.IsNullOrEmpty(layoutString))
            {
                return(string.Empty);
            }

            var layout       = LayoutDefinition.Parse(currentLayoutXml);
            var replacememts = new Dictionary <string, string>();

            // loop over devices in the rendering
            for (var deviceIndex = layout.Devices.Count - 1; deviceIndex >= 0; deviceIndex--)
            {
                var device = layout.Devices[deviceIndex] as DeviceDefinition;

                if (device == null)
                {
                    continue;
                }

                // loop over renderings within the device
                for (var renderingIndex = device.Renderings.Count - 1; renderingIndex >= 0; renderingIndex--)
                {
                    var rendering = device.Renderings[renderingIndex] as RenderingDefinition;

                    if (!string.IsNullOrWhiteSpace(rendering?.Datasource))
                    {
                        ID dataSource;
                        if (ID.TryParse(rendering.Datasource, out dataSource))
                        {
                            if (!replacememts.ContainsKey(rendering.Datasource))
                            {
                                replacememts.Add(rendering.Datasource, this.EnsureRelativeDatasourse(originalItem, destinationItem, dataSource));
                            }
                        }
                    }
                }
            }

            foreach (var replacement in replacememts)
            {
                layoutString = layoutString.Replace(replacement.Key, replacement.Value);
            }

            return(layoutString);
        }
        public override void Process(InsertRenderingsArgs args)
        {
            //Get the merged item layout field value
            Field layoutField = args.ContextItem.Fields[FieldIDs.LayoutField];

            if (layoutField == null)
            {
                return;
            }

            string fieldValue = LayoutField.GetFieldValue(layoutField);

            if (string.IsNullOrEmpty(fieldValue))
            {
                return;
            }

            //Parse it for easier processing
            XDocument layout = XDocument.Parse(fieldValue);

            XmlBasedRenderingParser parser = new XmlBasedRenderingParser();

            //Build a shared page context
            Sitecore.Mvc.Presentation.PageContext pageCtx = new Sitecore.Mvc.Presentation.PageContext();

            HttpContextWrapper httpCtxWrapper = new HttpContextWrapper(HttpContext.Current);
            RouteData          routeData      = CreateRouteData();

            pageCtx.RequestContext = CreateRequestContext(httpCtxWrapper, routeData);

            string deviceId = Sitecore.Context.Device.ID.ToString();

            //Loop through the renderings
            foreach (RenderingReference renderingReference in args.Renderings)
            {
                string templateName = renderingReference.RenderingItem.InnerItem.TemplateName;

                //Only do the replacement for MVC renderings
                if (templateName == "View rendering" || templateName == "Controller rendering" || templateName == "Item rendering")
                {
                    XElement  renderingXml = layout.XPathSelectElement("/r/d[@id='" + deviceId + "']/r[@id='" + renderingReference.RenderingID + "']");
                    Rendering rendering    = parser.Parse(renderingXml, false);

                    renderingReference.SetControl(new RenderingWrapper(rendering, pageCtx));
                }
            }
        }
Ejemplo n.º 14
0
        public DesignBotRuleContext(Item item)
        {
            Item = item;

            var sharedLayoutField = item.Fields[FieldIDs.LayoutField];
            var finalLayoutField  = item.Fields[FieldIDs.FinalLayoutField];

            SharedLayout = LayoutDefinition.Parse(LayoutField.GetFieldValue(sharedLayoutField));
            FinalLayout  = LayoutDefinition.Parse(LayoutField.GetFieldValue(finalLayoutField));

            // These can be filled with rule actions
            // SelectedDatasources = new List<Item>();

            // This can be overrided with the rule action SetDevice
            SelectedDevice     = FinalLayout.GetDevice(Constants.Items.Device.DefaultId);
            SelectedRenderings = new List <RenderingDefinition>(); // SelectedDevice.Renderings.Cast<RenderingDefinition>().ToList();
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Gets the layout XML from the item
        /// </summary>
        /// <returns>xml of the layout definition</returns>
        protected virtual XElement GetLayoutFromItem()
        {
            Field innerField = new LayoutField(Item).InnerField;

            if (innerField == null)
            {
                return(null);
            }

            string fieldValue = LayoutField.GetFieldValue(innerField);

            if (fieldValue.IsWhiteSpaceOrNull())
            {
                return(null);
            }

            return(XDocument.Parse(fieldValue).Root);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Assume convention that rendering name matches prefab name
        /// Lookup item from defined global repository
        /// Pull from single placeholder, set by rendering defn item or by config default
        /// </summary>
        /// <param name="args"></param>
        public override void Process(PrefabGetRenderingsArgs args)
        {
            if (args.Handled)
            {
                return;
            }

            Assert.IsNotNull(args.Prefab, "args.Prefab");

            var prefab = args.Prefab;

            // Warn if xml exists in FinalLayoutField
            if (!string.IsNullOrWhiteSpace(prefab[FieldIDs.FinalLayoutField]))
            {
                Log.Warn($"Prefab item, {prefab.Name} - {prefab.ID}, has FinalLayout details that will not be used. Move to Shared Layout to apply.", this);
            }

            var prefabSharedLayout        = LayoutDefinition.Parse(LayoutField.GetFieldValue(prefab.Fields[FieldIDs.LayoutField]));
            DeviceDefinition prefabDevice = prefabSharedLayout.GetDevice(args.DeviceLayout.ID); // match device

            // Get placeholder name
            var prefabPlaceholder = args.PrefabProxy.Placeholder;

            if (string.IsNullOrWhiteSpace(prefabPlaceholder))
            {
                prefabPlaceholder = Helper.NormalizePath(Config.Prefab.Placeholder);
            }

            // Get all renderings under this placeholder
            foreach (RenderingDefinition rendering in prefabDevice.Renderings)
            {
                var match = Helper.NormalizePath(rendering.Placeholder);
                if (match.StartsWith(prefabPlaceholder))
                {
                    args.AddResult(rendering, prefabPlaceholder);
                }
            }

            if (args.Handled)
            {
                args.AbortPipeline();
            }
        }
Ejemplo n.º 17
0
        private string updateDataPaths(Field templateFinalLayout, Item newPost)
        {
            string finalXml     = LayoutField.GetFieldValue(templateFinalLayout);
            var    finalDetails = Sitecore.Layouts.LayoutDefinition.Parse(finalXml);
            string templateXml  = finalDetails.ToXml();

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(templateXml);

            XmlNode renderingContainer = xmlDoc.DocumentElement.SelectSingleNode("/r/d");

            foreach (XmlNode node in renderingContainer.ChildNodes)
            {
                var newPh1Item = _db.GetItem(newPost.Paths.Path + "/Data/flex-placeholder_2");
                var newPh2Item = _db.GetItem(newPost.Paths.Path + "/Data/flex-placeholder_2/drop-zone-multi_1/flex-layout_2");
                var newPh3Item = _db.GetItem(newPost.Paths.Path + "/Data/flex-placeholder_2/drop-zone-multi_1/flex-layout_3");

                string ds = node.Attributes["ds"]?.InnerText;
                if (!string.IsNullOrWhiteSpace(ds))
                {
                    var templateItem = _db.GetItem(ds);
                    if (templateItem?.Paths.Path.Contains("/sitecore/content/Home/Insights/Blogs/mdTest/") == true)
                    {
                        var newLeft    = newPost.Paths.Path;
                        var newPath    = templateItem.Paths.Path.Replace("/sitecore/content/Home/Insights/Blogs/mdTest", newLeft);
                        var newItemsId = _db.GetItem(newPath);

                        node.Attributes["ds"].InnerText = newItemsId.ID.ToString();
                    }
                }

                if (node.Attributes["ph"].InnerText != null)
                {
                    node.Attributes["ph"].InnerText = node.Attributes["ph"].InnerText.Replace("{600CFC59-A345-44B8-A1AC-6A9BA64ED529}", newPh1Item.ID.ToString());
                    node.Attributes["ph"].InnerText = node.Attributes["ph"].InnerText.Replace("{FDBCA015-5B4B-4667-B084-6CDF6C4F28B7}", newPh2Item.ID.ToString());
                    node.Attributes["ph"].InnerText = node.Attributes["ph"].InnerText.Replace("{9E135461-3687-44A7-9F63-78D530CD5EE9}", newPh3Item.ID.ToString());
                }
            }

            return(xmlDoc.OuterXml);
        }
Ejemplo n.º 18
0
        protected override XElement GetFromField(Item item)
        {
            string key        = String.Format("{0}_{1}_{2}", item.ID, item.Language.Name, item.Version.Number);
            string fieldValue = BoostContext.PublishAwareCache.Get <string>(key);

            if (fieldValue != null)
            {
                return(GetFieldXml(fieldValue));
            }

            Field innerField = new LayoutField(item).InnerField;

            if (innerField == null)
            {
                return(null);
            }

            // This line is slow
            fieldValue = LayoutField.GetFieldValue(innerField);
            BoostContext.PublishAwareCache.Add(key, !String.IsNullOrEmpty(fieldValue) ? fieldValue : String.Empty);

            return(GetFieldXml(fieldValue));
        }
        private static void ApplyActionToAllRenderings(Item item, ID fieldId, string branchBasePath)
        {
            var currentLayoutXml = LayoutField.GetFieldValue(item.Fields[fieldId]);

            if (string.IsNullOrEmpty(currentLayoutXml))
            {
                return;
            }

            var newXml = ApplyActionToLayoutXml(item, currentLayoutXml, branchBasePath);

            // save a modified layout value if necessary
            if (newXml == null)
            {
                return;
            }

            using (new SecurityDisabler())
                using (new EditContext(item))
                {
                    LayoutField.SetFieldValue(item.Fields[fieldId], newXml);
                }
        }
        /// <summary>
        /// Create version in the target language and copy all fields from default en language
        /// </summary>
        /// <param name="language"></param>
        /// <param name="rootItem"></param>
        /// <param name="database"></param>
        private void AddItemVersions(Language language, Item rootItem, Database database)
        {
            List <Item> itemAndDescendants = rootItem.Axes.GetDescendants().ToList();

            itemAndDescendants.Add(rootItem);

            foreach (var item in itemAndDescendants)
            {
                Item targetItem = database.Items[item.ID, language];
                Item sourceItem = database.Items[item.ID, Context.Language];

                if (targetItem == null || sourceItem == null || sourceItem.Versions.Count == 0)
                {
                    return;
                }

                using (new SecurityDisabler())
                {
                    try
                    {
                        if (targetItem.Versions.Count == 0)
                        {
                            //add the version if none exist
                            targetItem = targetItem.Versions.AddVersion();
                        }

                        //start editing mode in target language
                        targetItem.Editing.BeginEdit();
                        sourceItem.Fields.ReadAll();

                        foreach (Field field in sourceItem.Fields)
                        {
                            if (field.ID == FieldIDs.FinalLayoutField || (!field.Shared && !field.Name.StartsWith("__") && field.Name.Trim() != string.Empty))
                            {
                                if (field.ID == FieldIDs.FinalLayoutField)
                                {
                                    var finalLayout = LayoutField.GetFieldValue(sourceItem.Fields[FieldIDs.FinalLayoutField]);
                                    LayoutField.SetFieldValue(targetItem.Fields[FieldIDs.FinalLayoutField], finalLayout);
                                }
                                else
                                {
                                    targetItem.Fields[field.Name].SetValue(field.Value, true);
                                }
                            }
                        }

                        //end editing mode
                        targetItem.Editing.EndEdit();
                        targetItem.Editing.AcceptChanges();
                    }
                    catch (Exception e)
                    {
                        targetItem.Editing.CancelEdit();
                        Log.Error(string.Format("There was an exception while editing the Item {0} in {1} language. Message: {2}, More Details: {3}",
                                                targetItem,
                                                language,
                                                e.Message,
                                                e.StackTrace), this);
                    }
                }
            }
        }
        private List <KeyValuePair <string, string> > ChangeLayoutFieldForItem(Item currentItem, Field field)
        {
            var result = new List <KeyValuePair <string, string> >();

            string xml = LayoutField.GetFieldValue(field);

            try
            {
                if (!string.IsNullOrWhiteSpace(xml))
                {
                    LayoutDefinition details = LayoutDefinition.Parse(xml);

                    var        device     = details.GetDevice(DefaultDeviceId);
                    DeviceItem deviceItem = currentItem.Database.Resources.Devices["Default"];

                    RenderingReference[] renderings = currentItem.Visualization.GetRenderings(deviceItem, false);

                    bool needUpdate = false;
                    foreach (RenderingDefinition rendering in device.Renderings)
                    {
                        if (!string.IsNullOrWhiteSpace(rendering.Placeholder))
                        {
                            var    newPlaceholder   = rendering.Placeholder;
                            string placeHolderRegex = "([0-9a-f]{8}[-][0-9a-f]{4}[-][0-9a-f]{4}[-][0-9a-f]{4}[-][0-9a-f]{12})$";
                            foreach (Match match in Regex.Matches(newPlaceholder, placeHolderRegex, RegexOptions.IgnoreCase))
                            {
                                var renderingId    = match.Value;
                                var newRenderingId = "-{" + renderingId.Substring(0) + "}-0";
                                newPlaceholder = newPlaceholder.Replace("_" + match.Value, newRenderingId);
                                needUpdate     = true;
                            }
                            if (newPlaceholder.Contains("_-{"))
                            {
                                newPlaceholder = newPlaceholder.Replace("_-{", "-{");
                                needUpdate     = true;
                            }
                            //newPlaceholder = newPlaceholder.Replace("_-", "-");
                            rendering.Placeholder = newPlaceholder;
                        }
                    }

                    if (needUpdate)
                    {
                        string newXml = details.ToXml();

                        using (new EditContext(currentItem))
                        {
                            LayoutField.SetFieldValue(field, newXml);
                        }
                        result.Add(new KeyValuePair <string, string>(currentItem.ID.ToString(), currentItem.Name));
                        //write it to log
                        _log.Info("Updated placeholder for " + currentItem.ID + " - Name - " + currentItem.Name);
                    }
                }
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error("UpcomingEventsandWebinarsController.Default", ex);
            }
            return(result);
        }
Ejemplo n.º 22
0
        // update datasource references on target page item
        private void UpdateDatasourcePaths(Item target)
        {
            try
            {
                if (target != null)
                {
                    //Log.Info("target: " + target.ID + " - " + target.Name, this);

                    // get all target's renderings
                    RenderingReference[] renderings = target.Visualization.GetRenderings(Context.Device, true);
                    //Log.Info("Total # target's renderings: " + renderings.Length + ".", this);

                    Item   targetResourceFolder = GetResourceFolder(target.Paths.Path);
                    string targetDatasourceID   = string.Empty;

                    // Get the layout definitions and the device
                    LayoutDefinition sharedLayout = LayoutDefinition.Parse(LayoutField.GetFieldValue(target.Fields[FieldIDs.LayoutField]));
                    LayoutDefinition finalLayout  = LayoutDefinition.Parse(LayoutField.GetFieldValue(target.Fields[FieldIDs.FinalLayoutField]));
                    DeviceDefinition device       = finalLayout.Devices[0] as DeviceDefinition;

                    //int count = 1;
                    foreach (RenderingReference rend in renderings)
                    {
                        string renderingDatasourceID = rend.Settings.DataSource;
                        if (!String.IsNullOrEmpty(renderingDatasourceID))
                        {
                            //Log.Info("rend[" + count + "] = " + rend.RenderingItem.Name + " = " + rend.RenderingID.ToString(), this);

                            string renderingUID = rend.UniqueId;
                            //Log.Info("rend.UniqueId = " + renderingUID, this);


                            // get target datasource ID
                            if (targetResourceFolder != null && targetResourceFolder.HasChildren)
                            {
                                //Log.Info("targetResourceFolder has " + targetResourceFolder.Children.Count + " children.", this);
                                targetDatasourceID = GetTargetDatasourceID(targetResourceFolder.Paths.Path, renderingDatasourceID);
                            }
                            else
                            {
                                if (ItemIsSourceRootChild(renderingDatasourceID))
                                {
                                    targetDatasourceID = GetTargetDatasourceID(renderingDatasourceID);
                                }
                                else
                                {
                                    return;
                                }                // datasource exists in area of content tree that was not copied, do not update
                            }
                            //Log.Info("targetDatasourceID: " + targetDatasourceID, this);

                            // Update rendering datasource value accordingly and verify
                            if (!String.IsNullOrEmpty(targetDatasourceID))
                            {
                                //Log.Info("Datasource should be pointing to : " + targetDatasourceID + " | but it is pointing to: " + renderingDatasourceID, this);
                                device.GetRenderingByUniqueId(renderingUID).Datasource = targetDatasourceID;
                                VerifyReferenceUpdate(target, device.GetRenderingByUniqueId(renderingUID).Datasource);

                                // Save the layout changes
                                target.Editing.BeginEdit();
                                ItemUtil.SetLayoutDetails(target, sharedLayout.ToXml(), finalLayout.ToXml());
                                target.Editing.EndEdit();
                            }
                        }
                        //count++;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Failed to update item references after CopyTo - " + target.ID.ToString() + " - " + ex.Message, ex, this);
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Computed field for page url
        /// </summary>
        /// <param name="indexable">IIndexable</param>
        /// <returns>object.</returns>
        public object ComputeFieldValue(IIndexable indexable)
        {
            Item item = null;

            try
            {
                item = indexable as SitecoreIndexableItem;
                if (item == null)
                {
                    return(null);
                }


                // Events - Get URL from Navigation URL field if available
                if (SearchHelper.FormatGuid(item.TemplateID.ToString()).Equals(SearchHelper.FormatGuid(CommonConstants.EventsTemplateID)) &&
                    (CheckboxField)item.Fields[CommonConstants.IsEventsPage] != null)
                {
                    // Navigation URL field wil have prioroty
                    if (item.Fields[CommonConstants.NavigationURL] != null && !string.IsNullOrWhiteSpace(item.Fields[CommonConstants.NavigationURL].Value))
                    {
                        LinkField navigationUrl = item.Fields[CommonConstants.NavigationURL];
                        if (navigationUrl != null)
                        {
                            if (!string.IsNullOrEmpty(navigationUrl.Url))
                            {
                                return(navigationUrl.Url);
                            }
                            else if (navigationUrl.TargetItem != null)
                            {
                                return(SearchHelper.GetURL(navigationUrl.TargetItem));
                            }
                        }
                    }
                    else if (((CheckboxField)item.Fields[CommonConstants.IsEventsPage]).Checked)
                    {
                        return(SearchHelper.GetURL(item));
                    }
                    else
                    {
                        return(null);
                    }
                }
                // Downloads - Get URL from Download Link field if available
                if (SearchHelper.FormatGuid(item.TemplateID.ToString()).Equals(SearchHelper.FormatGuid(CommonConstants.DownloadItemTemplateID)) &&
                    item.Fields["Download Link"] != null && !string.IsNullOrWhiteSpace(item.Fields["Download Link"].Value))
                {
                    LinkField downloadLink = item.Fields["Download Link"];
                    if (downloadLink != null)
                    {
                        if (!string.IsNullOrEmpty(downloadLink.Url))
                        {
                            return(downloadLink.Url);
                        }
                        else if (downloadLink.TargetItem != null)
                        {
                            return(SearchHelper.GetURL(downloadLink.TargetItem));
                        }
                    }
                }
                // Video - Get Youtube URL
                if (SearchHelper.FormatGuid(item.TemplateID.ToString()).Equals(SearchHelper.FormatGuid(CommonConstants.VideoItemTemplateID)) && item.Fields["Video"] != null)
                {
                    LinkField videoField = item.Fields["Video"];
                    if (videoField != null && !string.IsNullOrEmpty(videoField.Url))
                    {
                        string youtubeUrl = SearchHelper.GetYoutubeEmbedUrl(videoField.Url);
                        return(youtubeUrl ?? null);
                    }
                }
                string currentLayoutXml = LayoutField.GetFieldValue(item.Fields[FieldIDs.LayoutField]);
                if (string.IsNullOrEmpty(currentLayoutXml))
                {
                    return(null);
                }

                LayoutDefinition layout = LayoutDefinition.Parse(currentLayoutXml);
                if (layout.Devices.Count >= 1)
                {
                    return(SearchHelper.GetURL(item));
                }
            }


            catch (Exception ex)
            {
                string itemId = string.Empty;
                if (item != null)
                {
                    itemId = item.ID.ToString();
                }
                Sitecore.Diagnostics.Log.Error(this.GetType().Name + " - Item ID: " + itemId, ex, this);
            }

            return(null);
        }
Ejemplo n.º 24
0
        internal static LayoutDefinition GetLayoutDefinition(this Item item, ID layoutFieldId)
        {
            var layoutField = LayoutField.GetFieldValue(item.Fields[layoutFieldId]);

            return(LayoutDefinition.Parse(layoutField));
        }
Ejemplo n.º 25
0
        protected virtual string FormatJsonLayout([NotNull] Field field)
        {
            var layoutString = LayoutField.GetFieldValue(field);

            if (string.IsNullOrEmpty(layoutString))
            {
                return(string.Empty);
            }

            var layout = XDocument.Parse(layoutString);

            if (layout.Root == null)
            {
                return(string.Empty);
            }

            var writer = new StringWriter();
            var output = new JsonTextWriter(writer);

            output.WriteStartObject();

            output.WritePropertyString("$schema", "http://sitecore.net/contentdelivery/jsonlayout");
            output.WritePropertyString("version", "1.0.0");

            output.WriteStartArray("devices");
            foreach (var deviceElement in layout.Root.Elements())
            {
                output.WriteStartObject();

                var deviceId = deviceElement.GetAttributeValue("id");
                var layoutId = deviceElement.GetAttributeValue("l");

                output.WritePropertyString("deviceId", deviceId);
                output.WritePropertyString("layoutId", layoutId);

                var deviceItem = field.Database.GetItem(deviceId);
                if (deviceItem != null)
                {
                    output.WritePropertyString("deviceName", deviceItem.Name);
                    output.WritePropertyString("deviceItemPath", deviceItem.Paths.Path);
                }

                var layoutItem = field.Database.GetItem(layoutId);
                if (layoutItem != null)
                {
                    output.WritePropertyString("layoutName", layoutItem.Name);
                    output.WritePropertyString("layoutItemPath", layoutItem.Paths.Path);
                }

                output.WriteStartArray("renderings");

                foreach (var renderingElement in deviceElement.Elements())
                {
                    output.WriteStartObject();

                    var renderingId       = renderingElement.GetAttributeValue("id");
                    var uniqueId          = renderingElement.GetAttributeValue("uid");
                    var placeholderName   = renderingElement.GetAttributeValue("ph");
                    var dataSource        = renderingElement.GetAttributeValue("ds");
                    var parameters        = new UrlString(renderingElement.GetAttributeValue("par"));
                    var cacheable         = renderingElement.GetAttributeValue("cac") == "1";
                    var varyByData        = renderingElement.GetAttributeValue("vbd") == "1";
                    var varyByDevice      = renderingElement.GetAttributeValue("vbdev") == "1";
                    var varyByLogin       = renderingElement.GetAttributeValue("vbl") == "1";
                    var varyByParameters  = renderingElement.GetAttributeValue("vbp") == "1";
                    var varyByQueryString = renderingElement.GetAttributeValue("vbqs") == "1";
                    var varyByUser        = renderingElement.GetAttributeValue("vbu") == "1";

                    output.WritePropertyString("renderingId", renderingId);
                    var renderingItem = field.Database.GetItem(renderingId);
                    if (renderingItem != null)
                    {
                        output.WritePropertyString("renderingName", renderingItem.Name);
                        output.WritePropertyString("renderingItemPath", renderingItem.Paths.Path);
                    }

                    output.WritePropertyStringIf("uniqueId", uniqueId);
                    output.WritePropertyStringIf("placeholder", placeholderName);
                    output.WritePropertyStringIf("datasource", dataSource);
                    output.WritePropertyStringIf("cacheable", cacheable);
                    output.WritePropertyStringIf("varyByData", varyByData);
                    output.WritePropertyStringIf("varyByDevice", varyByDevice);
                    output.WritePropertyStringIf("varyByLogin", varyByLogin);
                    output.WritePropertyStringIf("varyByParameters", varyByParameters);
                    output.WritePropertyStringIf("varyByQueryString", varyByQueryString);
                    output.WritePropertyStringIf("varyByUser", varyByUser);

                    if (parameters.Parameters.Count > 0)
                    {
                        output.WriteStartArray("parameters");

                        foreach (var key in parameters.Parameters.AllKeys)
                        {
                            output.WriteStartObject();
                            output.WritePropertyString("key", key);
                            output.WritePropertyString("value", parameters.Parameters[key]);
                            output.WriteEndObject();
                        }

                        output.WriteEndArray();
                    }

                    output.WriteEndObject();
                }

                output.WriteEndArray();
                output.WriteEndObject();
            }

            output.WriteEndArray();
            output.WriteEndObject();

            return(writer.ToString());
        }
Ejemplo n.º 26
0
        public static LayoutDefinition GetLayoutDefinition(this Item item)
        {
            var layoutField = item.Fields[SitecoreIDs.LayoutFieldId];

            return(LayoutDefinition.Parse(LayoutField.GetFieldValue(layoutField)));
        }
Ejemplo n.º 27
0
        private string GetField([NotNull] GetFieldValuePipeline pipeline)
        {
            Debug.ArgumentNotNull(pipeline, nameof(pipeline));

            return(LayoutField.GetFieldValue(pipeline.Field));
        }