protected override void ProcessPlaceholderSettings(Item item, LayoutDefinition layout, DeviceDefinition device,
                                                           List <PlaceholderDefinition> placeholders)
        {
            if (placeholders.Any())
            {
                if (!ShouldProcess(item.GetProviderPath(),
                                   $"Remove placeholder setting(s) '{placeholders.Select(r => r.MetaDataItemId.ToString()).Aggregate((seed, curr) => seed + ", " + curr)}' from device {Device.Name}")
                    )
                {
                    return;
                }

                foreach (
                    var placeholderSetting in
                    placeholders.Select(rendering => device.Placeholders.Cast <PlaceholderDefinition>()
                                        .FirstOrDefault(r => r.UniqueId == rendering.UniqueId))
                    .Where(placeholder => placeholder != null)
                    .Reverse())
                {
                    device.Placeholders.Remove(placeholderSetting);
                }

                item.Edit(p =>
                {
                    var outputXml = layout.ToXml();
                    LayoutField.SetFieldValue(Item.Fields[LayoutFieldId], outputXml);
                });
            }
            else
            {
                WriteError(typeof(ObjectNotFoundException), "Cannot find a placeholder setting to remove",
                           ErrorIds.PlaceholderSettingNotFound, ErrorCategory.ObjectNotFound, null);
            }
        }
示例#2
0
        protected override void ProcessItem(Item item)
        {
            if (!ShouldProcess(item.GetProviderPath(),
                               $"Merging layout from '{item.Language.Name}' to shared layout."))
            {
                return;
            }

            var shared = new LayoutField(item.Fields[Sitecore.FieldIDs.LayoutField]);

            var final = new LayoutField(item.Fields[Sitecore.FieldIDs.FinalLayoutField]);

            //If we don't have a final layout delta, we're good!
            if (string.IsNullOrWhiteSpace(final.Value))
            {
                WriteVerbose("No final layout - nothing to do.");
                return;
            }

            var finalLayoutDefinition = LayoutDefinition.Parse(final.Value);

            item.Edit(p =>
            {
                LayoutField.SetFieldValue(item.Fields[Sitecore.FieldIDs.LayoutField],
                                          finalLayoutDefinition.ToXml());
                shared.Value = finalLayoutDefinition.ToXml();
                final.InnerField.Reset();
            });
        }
        protected override void ProcessRenderings(Item item, LayoutDefinition layout, DeviceDefinition device,
                                                  List <RenderingDefinition> renderings)
        {
            if (renderings.Any())
            {
                if (!ShouldProcess(item.GetProviderPath(),
                                   $"Switch rendering(s) '{renderings.Select(r => r.ItemID.ToString()).Aggregate((seed, curr) => seed + ", " + curr)}' for device {Device.Name}"))
                {
                    return;
                }

                foreach (
                    var instanceRendering in
                    renderings.Select(rendering => device.Renderings.Cast <RenderingDefinition>()
                                      .FirstOrDefault(r => r != null && r.UniqueId == rendering.UniqueId))
                    .Where(instanceRendering => instanceRendering != null)
                    .Reverse())
                {
                    DoReplaceRendering(instanceRendering, NewRendering, device);
                }

                item.Edit(p =>
                {
                    var outputXml = layout.ToXml();
                    LayoutField.SetFieldValue(item.Fields[LayoutFieldId], outputXml);
                });
            }
            else
            {
                WriteError(typeof(ObjectNotFoundException), "Cannot find a rendering to remove",
                           ErrorIds.RenderingNotFound, ErrorCategory.ObjectNotFound, null);
            }
        }
示例#4
0
        protected override void ProcessItem(Item item)
        {
            if (ShouldProcess(item.GetProviderPath(), string.Format("Set layout '{0}'", Layout.GetProviderPath())))
            {
                LayoutField layoutField = item.Fields[LayoutFieldId];
                if (layoutField == null)
                {
                    return;
                }

                var layout = LayoutDefinition.Parse(layoutField.Value);

                var device = layout.GetDevice(Device.ID.ToString());

                if (string.Equals(device.Layout, Layout.ID.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    //same layout as already set - no point in setting it again
                    return;
                }

                device.Layout = Layout.ID.ToString();

                item.Edit(p =>
                {
                    var outputXml = layout.ToXml();
                    LayoutField.SetFieldValue(item.Fields[LayoutFieldId], outputXml);
                });
            }
        }
示例#5
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);
                }
            }
        }
示例#6
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);
                }
            }
        }
        protected override void ProcessLayout(Item item, LayoutDefinition layout, DeviceDefinition device)
        {
            if (!ShouldProcess(item.GetProviderPath(), "Add rendering " + Instance.ItemID))
            {
                return;
            }
            var rendering = new RenderingDefinition
            {
                ItemID             = Instance.ItemID,
                Placeholder        = PlaceHolder ?? Instance.Placeholder,
                Datasource         = DataSource ?? Instance.Datasource,
                Cachable           = Instance.Cachable,
                ClearOnIndexUpdate = Instance.ClearOnIndexUpdate,
                VaryByData         = Instance.VaryByData,
                VaryByDevice       = Instance.VaryByDevice,
                VaryByLogin        = Instance.VaryByLogin,
                VaryByParameters   = Instance.VaryByParameters,
                VaryByQueryString  = Instance.VaryByQueryString,
                VaryByUser         = Instance.VaryByUser
            };

            if (Parameter != null)
            {
                var parameters = new UrlString(rendering.Parameters ?? string.Empty);
                foreach (string name in Parameter.Keys)
                {
                    if (parameters.Parameters.AllKeys.Contains(name))
                    {
                        parameters.Parameters[name] = Parameter[name].ToString();
                    }
                    else
                    {
                        parameters.Add(name, Parameter[name].ToString());
                    }
                }
                rendering.Parameters = parameters.ToString();
            }

            //todo: add support for conditions
            //renderingDefinition.Conditions
            //todo: add support for multivariate tests
            //rendering.MultiVariateTest

            if (Index > -1)
            {
                device.Insert(Index, rendering);
            }
            else
            {
                device.AddRendering(rendering);
            }

            item.Edit(p =>
            {
                var outputXml = layout.ToXml();
                LayoutField.SetFieldValue(item.Fields[LayoutFieldId], outputXml);
            });
        }
        /// <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);
                    }
                }
            }
        }
示例#9
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);
        }
        protected override void ProcessLayout(Item item, LayoutDefinition layout, DeviceDefinition device)
        {
            var key = Key ?? Instance.Key;

            if (string.IsNullOrWhiteSpace(key))
            {
                WriteError(typeof(ObjectNotFoundException), "A placeholder setting requires a key provided here or in the instance.",
                           ErrorIds.ValueNotFound, ErrorCategory.ObjectNotFound, key);

                return;
            }

            var metadataItemId = MetaDataItemId ?? Instance.MetaDataItemId;

            if (string.IsNullOrWhiteSpace(metadataItemId))
            {
                WriteError(typeof(ObjectNotFoundException), "A placeholder setting requires a MetaDataItemId provided here or in the instance.",
                           ErrorIds.ValueNotFound, ErrorCategory.ObjectNotFound, metadataItemId);

                return;
            }

            if (!ShouldProcess(item.GetProviderPath(), $"Add placeholder setting '{metadataItemId}'"))
            {
                return;
            }

            var placeholder = new PlaceholderDefinition
            {
                Key            = key,
                MetaDataItemId = metadataItemId,
                UniqueId       = ID.NewID.ToString()
            };

            if (!PlaceholderSettingExists(device, placeholder))
            {
                device.AddPlaceholder(placeholder);

                item.Edit(p =>
                {
                    var outputXml = layout.ToXml();
                    LayoutField.SetFieldValue(item.Fields[LayoutFieldId], outputXml);
                });
            }
            else
            {
                WriteError(typeof(DuplicateNameException), $"A placeholder setting with key '{key}' and metadata '{metadataItemId}' already exists.",
                           ErrorIds.PlaceholderSettingAlreadyExists, ErrorCategory.InvalidArgument, placeholder);
                return;
            }
        }
示例#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);
            }
        }
示例#12
0
        private void addRenderings(Item item)
        {
            //var blogTemplateItem = _db.GetItem("{ECE28233-B82E-4B9B-9D6A-F5956C69E391}");

            var templateFinalLayout = _blogPostTemplateItem.Fields[Sitecore.FieldIDs.FinalLayoutField];

            var outputXml = updateDataPaths(templateFinalLayout, item);

            var finalLayoutField = item.Fields[Sitecore.FieldIDs.FinalLayoutField];

            using (new SecurityDisabler())
            {
                item.Editing.BeginEdit();
                LayoutField.SetFieldValue(finalLayoutField, outputXml);
                item.Editing.EndEdit();
            }
        }
 protected void Run(ClientPipelineArgs args)
 {
     Assert.ArgumentNotNull(args, "args");
     if (args.IsPostBack)
     {
         if (args.HasResult)
         {
             Database database = Factory.GetDatabase(args.Parameters["database"]);
             Assert.IsNotNull(database, "Database \"" + args.Parameters["database"] + "\" not found.");
             Item item = database.Items[args.Parameters["id"], Language.Parse(args.Parameters["language"]), Version.Parse(args.Parameters["version"])];
             var  searchStringModel = ExtractSearchQuery(args.Parameters["searchString"]);
             var  hitsCount         = 0;
             var  listOfItems       = item.Search(searchStringModel, out hitsCount).ToList();
             Assert.IsNotNull(item, "item");
             var result = args.Result;
             foreach (var item1 in listOfItems.Select(sitecoreItem => sitecoreItem.GetItem()))
             {
                 item1.Editing.BeginEdit();
                 if (item1.Name != "__Standard Values")
                 {
                     LayoutField.SetFieldValue(item1.Fields[FieldIDs.LayoutField], result);
                 }
                 else
                 {
                     item1[FieldIDs.LayoutField] = result;
                 }
                 item1.Editing.EndEdit();
                 Log.Audit(this, "Set layout details: {0}, layout: {1}", new [] { AuditFormatter.FormatItem(item1), result });
             }
         }
     }
     else
     {
         var str2 = new UrlString(UIUtil.GetUri("control:LayoutDetails"));
         str2.Append("id", args.Parameters["id"]);
         str2.Append("la", args.Parameters["language"]);
         str2.Append("vs", args.Parameters["version"]);
         SheerResponse.ShowModalDialog(str2.ToString(), true);
         args.WaitForPostBack();
     }
 }
示例#14
0
        protected override void ProcessItem(Item item)
        {
            LayoutField layoutField = item.Fields[LayoutFieldId];

            if (string.IsNullOrEmpty(layoutField?.Value))
            {
                return;
            }

            var layout = LayoutDefinition.Parse(layoutField.Value);

            if (layout.Devices == null)
            {
                return;
            }

            var allDevices = layout.Devices;

            foreach (DeviceDefinition device in allDevices)
            {
                if (Device != null && !string.Equals(device.ID, Device.ID.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                layout.Devices.Remove(device);
                item.Edit(p =>
                {
                    var outputXml = layout.ToXml();
                    LayoutField.SetFieldValue(item.Fields[LayoutFieldId], outputXml);
                });
                return;
            }
            if (Device != null)
            {
                WriteError(
                    new ErrorRecord(
                        new ObjectNotFoundException(
                            $"Item \"{item.Name}\" has no layout defined for device \"{Device.Name}\""), "sitecore_layout_for_device_not_found", ErrorCategory.ObjectNotFound,
                        Device));
            }
        }
        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);
                }
        }
示例#16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="template"></param>
        /// <param name="delta"></param>
        /// <param name="language"></param>
        /// <param name="version"></param>
        /// <param name="database"></param>
        private void ApplyDeltaToStandardValues(Template template, string delta, Language language, Sitecore.Data.Version version, Database database)
        {
            if (Sitecore.Context.User.IsAdministrator)
            {
                if (template != null)
                {
                    if (!Sitecore.Data.ID.IsNullOrEmpty(template.StandardValueHolderId))
                    {
                        Item item = ItemManager.GetItem(template.StandardValueHolderId, language, version, database, SecurityCheck.Disable);

                        if (item != null)
                        {
                            Field field = item.Fields[FieldIDs.LayoutField];

                            if (!field.ContainsStandardValue)
                            {
                                try
                                {
                                    string newFieldValue = XmlDeltas.ApplyDelta(field.Value, delta);

                                    if (newFieldValue != field.Value)
                                    {
                                        item.Editing.BeginEdit();
                                        LayoutField.SetFieldValue(field, newFieldValue);
                                        item.Editing.EndEdit();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Sitecore.Diagnostics.Log.Error(ex.Message, this);
                                }
                            }
                        }
                    }
                }
            }
        }
        public static void UpdateLayoutDefinition(this Item item, LayoutDefinition layoutDefinition)
        {
            var layoutField = item.Fields[SitecoreIDs.LayoutFieldId];

            LayoutField.SetFieldValue(layoutField, layoutDefinition.ToXml());
        }
示例#18
0
        protected override void ProcessItem(Item item)
        {
            if (ShouldProcess(item.GetProviderPath(),
                              $"Set '{Instance.UniqueId}' rendering parameters. Rendering is of type: {Instance.ItemID}"))
            {
                LayoutField layoutField = item.Fields[LayoutFieldId];
                if (layoutField == null || string.IsNullOrEmpty(layoutField.Value))
                {
                    return;
                }

                var layout = LayoutDefinition.Parse(layoutField.Value);

                DeviceDefinition    device;
                RenderingDefinition rendering;

                foreach (DeviceDefinition aDevice in layout.Devices)
                {
                    foreach (
                        RenderingDefinition aRendering in
                        aDevice.Renderings.Cast <RenderingDefinition>()
                        .Where(aRendering => aRendering.UniqueId == Instance.UniqueId))
                    {
                        device    = aDevice;
                        rendering = aRendering;
                        goto Renderingfound;
                    }
                }

                return;

Renderingfound: //goto label
                rendering.ItemID      = Instance.ItemID;
                rendering.Placeholder = MyInvocation.BoundParameters.ContainsKey("PlaceHolder")
                    ? PlaceHolder
                    : Instance.Placeholder ?? rendering.Placeholder;
                rendering.Datasource =
                    !string.IsNullOrEmpty(DataSource)
                        ? DataSource
                        : Instance.Datasource;
                rendering.Cachable          = Instance.Cachable;
                rendering.VaryByData        = Instance.VaryByData;
                rendering.VaryByDevice      = Instance.VaryByDevice;
                rendering.VaryByLogin       = Instance.VaryByLogin;
                rendering.VaryByParameters  = Instance.VaryByParameters;
                rendering.VaryByQueryString = Instance.VaryByQueryString;
                rendering.VaryByUser        = Instance.VaryByUser;
                rendering.Parameters        = Instance.Parameters;
                rendering.MultiVariateTest  = Instance.MultiVariateTest;
                rendering.Rules             = Instance.Rules;
                rendering.Conditions        = Instance.Conditions;

                if (Parameter != null)
                {
                    var parameters = new UrlString(rendering.Parameters ?? string.Empty);
                    foreach (string name in Parameter.Keys)
                    {
                        if (parameters.Parameters.AllKeys.Contains(name))
                        {
                            parameters.Parameters[name] = Parameter[name].ToString();
                        }
                        else
                        {
                            parameters.Add(name, Parameter[name].ToString());
                        }
                    }
                    rendering.Parameters = parameters.ToString();
                }

                if (Index > -1)
                {
                    device.Renderings.Remove(rendering);
                    device.Insert(index, rendering);
                }

                item.Edit(p =>
                {
                    var outputXml = layout.ToXml();
                    LayoutField.SetFieldValue(item.Fields[LayoutFieldId], outputXml);
                });
            }
        }
        /// <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);
                    }
                }
            }
        }
示例#20
0
        protected override void ProcessLayout(Item item, LayoutDefinition layout, DeviceDefinition device)
        {
            if (!ShouldProcess(item.GetProviderPath(), "Add rendering " + Instance.ItemID))
            {
                return;
            }
            var rendering = new RenderingDefinition
            {
                ItemID             = Instance.ItemID,
                Placeholder        = PlaceHolder ?? Instance.Placeholder,
                Datasource         = DataSource ?? Instance.Datasource,
                Cachable           = Instance.Cachable,
                ClearOnIndexUpdate = Instance.ClearOnIndexUpdate,
                VaryByData         = Instance.VaryByData,
                VaryByDevice       = Instance.VaryByDevice,
                VaryByLogin        = Instance.VaryByLogin,
                VaryByParameters   = Instance.VaryByParameters,
                VaryByQueryString  = Instance.VaryByQueryString,
                VaryByUser         = Instance.VaryByUser
            };

            if (Parameter != null && Parameter.Keys.Count > 0)
            {
                var parameters    = new UrlString(rendering.Parameters ?? string.Empty);
                var renderingItem = Sitecore.Client.ContentDatabase.GetItem(Instance.ItemID);
                if (renderingItem == null)
                {
                    WriteError(new ItemNotFoundException($"The rendering with Id {Instance.ItemID} could not be found in the ContentDatabase."), ErrorIds.ItemNotFound, ErrorCategory.ObjectNotFound, this);
                    return;
                }

                var standardValuesItem = RenderingItem.GetStandardValuesItemFromParametersTemplate(renderingItem);
                var excludedFields     = new List <string> {
                    "additional parameters", "placeholder", "data source", "caching", "personalization", "test"
                };
                foreach (Field standardValueField in standardValuesItem.Fields)
                {
                    var fieldName      = standardValueField.Name;
                    var lowerInvariant = fieldName.ToLowerInvariant();
                    if (excludedFields.Contains(lowerInvariant))
                    {
                        continue;
                    }
                    if (!RenderingItem.IsRenderingParameterField(standardValueField))
                    {
                        continue;
                    }

                    var fieldValue = standardValueField.Value ?? string.Empty;
                    if (parameters.Parameters.AllKeys.Contains(fieldName))
                    {
                        parameters.Parameters[fieldName] = fieldValue;
                    }
                    else
                    {
                        parameters.Add(fieldName, fieldValue);
                    }
                }
                foreach (string name in Parameter.Keys)
                {
                    if (parameters.Parameters.AllKeys.Contains(name))
                    {
                        parameters.Parameters[name] = Parameter[name].ToString();
                    }
                    else
                    {
                        parameters.Add(name, Parameter[name].ToString());
                    }
                }
                rendering.Parameters = parameters.ToString();
            }

            //todo: add support for conditions
            //renderingDefinition.Conditions
            //todo: add support for multivariate tests
            //rendering.MultiVariateTest

            if (Index > -1)
            {
                device.Insert(Index, rendering);
            }
            else
            {
                device.AddRendering(rendering);
            }

            item.Edit(p =>
            {
                var outputXml = layout.ToXml();
                LayoutField.SetFieldValue(item.Fields[LayoutFieldId], outputXml);
            });

            if (PassThru)
            {
                WriteObject(rendering);
            }
        }
示例#21
0
        public override ActionResult SaveItems(RequestParameters requestParameters, Dictionary <string, string> fields)
        {
            var output = new JsonContentResultWriter(new StringWriter());

            WriteMetaData(output);

            var fieldList = new List <FieldEditorField>();

            foreach (var pair in fields)
            {
                var key   = pair.Key;
                var value = HttpUtility.UrlDecode(pair.Value) ?? string.Empty;

                var parts = key.Split('/');
                if (parts.Length != 5)
                {
                    output.WriteError("Invalid Field Uri: " + key);
                    continue;
                }

                var languageName = parts[2];
                if (languageName == "-")
                {
                    languageName = LanguageManager.DefaultLanguage.Name;
                }

                var versionNumber = parts[3];
                if (versionNumber == "-")
                {
                    versionNumber = "0";
                }

                var databaseName = parts[0];
                var itemId       = parts[1];
                var language     = Language.Parse(languageName);
                var version      = Version.Parse(versionNumber);
                var fieldId      = parts[4];

                var field = new FieldEditorField(databaseName, itemId, language, version, fieldId, value);

                fieldList.Add(field);
            }

            var items = new Dictionary <string, Item>();

            foreach (var field in fieldList)
            {
                var key = field.DatabaseName + "/" + field.ItemId + "/" + field.Language + "/" + field.Version;
                if (!items.TryGetValue(key, out var item))
                {
                    var database = Factory.GetDatabase(field.DatabaseName);

                    item = database.GetItem(field.ItemId, field.Language, field.Version);
                    if (item == null)
                    {
                        output.WriteError("Item not found: " + field.ItemId + "/" + field.Language.Name + "/" + field.Version.Number);
                        continue;
                    }

                    if (!item.Security.CanWrite(Context.User))
                    {
                        output.WriteError("You do not have permission to write to this item: " + item.Paths.Path);
                        continue;
                    }

                    items[key] = item;

                    try
                    {
                        item.Editing.BeginEdit();
                    }
                    catch (System.Exception ex)
                    {
                        output.WriteError("An exception occured while saving item: " + item.Paths.Path + "; " + ex.Message);
                        continue;
                    }
                }

                var itemField = item.Fields[field.FieldId];
                if (itemField != null && string.Equals(itemField.Type, "layout", System.StringComparison.OrdinalIgnoreCase))
                {
                    // layout field needs special handling because of layout deltas
                    var layoutFieldValue = GetLayoutFieldValue(item, field);
                    LayoutField.SetFieldValue(itemField, layoutFieldValue);
                    continue;
                }

                item[field.FieldId] = field.Value;
            }

            foreach (var pair in items)
            {
                pair.Value.Editing.EndEdit();
            }

            return(output.ToContentResult());
        }
        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);
        }
        private void SetField([NotNull] SetFieldValuePipeline pipeline)
        {
            Debug.ArgumentNotNull(pipeline, nameof(pipeline));

            LayoutField.SetFieldValue(pipeline.Field, pipeline.Value);
        }