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 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); }); } }
public string Execute([NotNull] string databaseName, [NotNull] string layout) { var database = Factory.GetDatabase(databaseName); if (database == null) { throw new Exception("Database not found"); } var writer = new StringWriter(); var output = new XmlTextWriter(writer); output.WriteStartElement("steps"); var layoutDefinition = LayoutDefinition.Parse(layout); var placeHolders = GetPlaceHolders(database, layoutDefinition); foreach (var path in GetRenderings.RootPaths) { var item = database.GetItem(path); if (item != null) { ProcessRenderings(output, placeHolders, item); } } output.WriteEndElement(); return(writer.ToString()); }
///<summary> /// When working with the Presentation Layer for Sitecore, you can specify a Datasource as a property /// for a control. However, accessing the item that is set brings a bit of a challenge. Hopefully this fixes that. ///</summary> ///<param name = "database">Sitecore Database to Use. Usually From Context.</param> ///<param name = "device">Sitecore Device to Use. Usually from Context.</param> ///<param name = "item">Item to get the Layout Renderings from.</param> ///<param name = "sublayoutItem"> /// Item reference to the Sublayout or Webcontrol that you would like to use for getting the datasource from. ///</param> ///<returns>Datasource Item. If no Datasource Item is listed in the layout properties, returns Null.</returns> ///<exception cref = "ItemNotFoundException">Thrown when Sitecore can't find a specified datasource item entry.</exception> public static Item GetDatasourceFromControl(Database database, DeviceItem device, Item item, Item sublayoutItem) { Item datasourceItem = null; // Get the Layout definition from the current item string rend = item.Fields["__renderings"].Value; LayoutDefinition layout = LayoutDefinition.Parse(rend); // Get the current device definition DeviceDefinition deviceDef = layout.GetDevice(device.ID.ToString()); // Get the sublayout to find Item mySublayout = database.GetItem(sublayoutItem.ID); // Get the definition for the sublayout RenderingDefinition rendering = deviceDef.GetRendering(mySublayout.ID.ToString()); if (!String.IsNullOrEmpty(rendering.Datasource)) { datasourceItem = database.GetItem(rendering.Datasource); if (datasourceItem == null) { throw new ItemNotFoundException("Could not find datasource item at " + rendering.Datasource); } } return(datasourceItem); }
private static void UpdateFinalRenderings(Item sourcePageItem, Item targetPageItem, Field sourceFinalRenderingsField, Field targetFinalRenderingsField) { // get source renderings var sourceDefaultDevice = sourcePageItem.Database.Resources.Devices.GetAll().First(d => d.IsDefault); var sourceLayoutField = new LayoutField(sourceFinalRenderingsField); var sourceLayoutDefinition = LayoutDefinition.Parse(sourceLayoutField.Value); var sourceDeviceDefinition = sourceLayoutDefinition.GetDevice(sourceDefaultDevice.ID.ToString()); // get target renderings var targetDefaultDevice = targetPageItem.Database.Resources.Devices.GetAll().First(d => d.IsDefault); var targetLayoutField = new LayoutField(targetFinalRenderingsField); var targetLayoutDefinition = LayoutDefinition.Parse(targetLayoutField.Value); var targetDeviceDefinition = targetLayoutDefinition.GetDevice(targetDefaultDevice.ID.ToString()); foreach (RenderingDefinition sourceRendering in sourceDeviceDefinition.Renderings) { var duplicateRendering = targetDeviceDefinition.Renderings.Cast <RenderingDefinition>() .FirstOrDefault(r => r.UniqueId.Equals(sourceRendering.UniqueId)); // Rendering isn't already on target renderings if (duplicateRendering == null) { targetDeviceDefinition.Renderings.Add(sourceRendering); } } // save changes using (new EditContext(targetPageItem)) { targetFinalRenderingsField.Value = targetLayoutDefinition.ToXml(); } }
private static string ApplyActionToLayoutXml(string xml, Action <RenderingDefinition> action) { var layout = LayoutDefinition.Parse(xml); // normalize the output in case of any minor XML differences (spaces, etc) xml = layout.ToXml(); // 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 (rendering == null) { continue; } // run the action on the rendering action(rendering); } } var layoutXml = layout.ToXml(); // save a modified layout value if necessary return(layoutXml != xml ? layoutXml : null); }
/// <summary> /// Gets the layout definition. /// </summary> /// <returns> /// The layout definition. /// </returns> /// <contract><ensures condition="not null" /></contract> private static LayoutDefinition GetLayoutDefinition() { string sessionString = WebUtil.GetSessionString(DeviceEditorForm.GetSessionHandle()); Assert.IsNotNull(sessionString, "layout definition"); return(LayoutDefinition.Parse(sessionString)); }
private static string ApplyActionToLayoutXml(Item item, string xml, string branchBasePath) { var layout = LayoutDefinition.Parse(xml); xml = layout.ToXml(); for (var deviceIndex = layout.Devices.Count - 1; deviceIndex >= 0; deviceIndex--) { var device = layout.Devices[deviceIndex] as DeviceDefinition; if (device == null) { continue; } for (var renderingIndex = device.Renderings.Count - 1; renderingIndex >= 0; renderingIndex--) { var rendering = device.Renderings[renderingIndex]; if (rendering is RenderingDefinition) { var renderingdefn = rendering as RenderingDefinition; RelinkRenderingDatasource(item, renderingdefn, branchBasePath); } } } var layoutXml = layout.ToXml(); return(layoutXml != xml ? layoutXml : null); }
private LayoutDefinition GetLayoutDefinition() { var xml = WebEditUtil.ConvertJSONLayoutToXML(WebUtil.GetFormValue("scLayout")); var layoutDefinition = LayoutDefinition.Parse(xml); return(layoutDefinition); }
public void CleanRenderings(Item item, string renderingID, string placeholder) { LayoutField layoutField = new LayoutField(item.Fields[FieldIDs.FinalLayoutField]); LayoutDefinition layoutDefinition = LayoutDefinition.Parse(layoutField.Value); DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(GetDefaultDeviceItem(item.Database).ID.ToString()); List <string> placeholders = new List <string>(); foreach (RenderingDefinition rendering in deviceDefinition.Renderings) { if (rendering.ItemID.ToLower() == "{C1624533-ED68-41AC-B03C-BFDE4D9B1F2A}".ToLower()) { placeholders.Add(StringUtil.EnsurePrefix('/', rendering.Placeholder + "/" + placeholder + "_" + new Guid(rendering.UniqueId).ToString("D").ToLower())); } } List <RenderingDefinition> renderingsToRemove = new List <RenderingDefinition>(); foreach (RenderingDefinition rendering in deviceDefinition.Renderings) { if (rendering.ItemID.ToLower() == renderingID.ToLower() && placeholders.Contains(rendering.Placeholder)) { renderingsToRemove.Add(rendering); } } foreach (var rendering in renderingsToRemove) { deviceDefinition.Renderings.Remove(rendering); } using (new SecurityDisabler()) { item.Editing.BeginEdit(); layoutField.Value = layoutDefinition.ToXml(); item.Editing.EndEdit(); } }
public void AddRendering(Item item, string renderingID, string placeholder, Item datasource) { LayoutField layoutField = new LayoutField(item.Fields[FieldIDs.FinalLayoutField]); LayoutDefinition layoutDefinition = LayoutDefinition.Parse(layoutField.Value); DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(GetDefaultDeviceItem(item.Database).ID.ToString()); foreach (RenderingDefinition rendering in deviceDefinition.Renderings) { if (rendering.ItemID.ToLower() == "{C1624533-ED68-41AC-B03C-BFDE4D9B1F2A}".ToLower()) { placeholder = StringUtil.EnsurePrefix('/', rendering.Placeholder + "/" + placeholder + "_" + new Guid(rendering.UniqueId).ToString("D").ToLower()); break; } } var newRendering = new RenderingDefinition { Placeholder = placeholder, ItemID = renderingID, Datasource = datasource.ID.ToString() }; deviceDefinition.AddRendering(newRendering); using (new SecurityDisabler()) { item.Editing.BeginEdit(); layoutField.Value = layoutDefinition.ToXml(); item.Editing.EndEdit(); } }
public void Write([NotNull] XmlTextWriter output, [NotNull] Database database, [NotNull] string layout) { Assert.ArgumentNotNull(output, nameof(output)); Assert.ArgumentNotNull(database, nameof(database)); Assert.ArgumentNotNull(layout, nameof(layout)); output.WriteStartElement("layout"); WriteDevices(output, database); if (!string.IsNullOrEmpty(layout)) { var layoutDefinition = LayoutDefinition.Parse(layout); var doc = XDocument.Parse(layout); var layoutRoot = doc.Root; if (layoutRoot == null) { throw new InvalidOperationException("Invalid layout definition"); } WriteLayout(output, database, layoutDefinition, layoutRoot); } output.WriteEndElement(); }
public DeviceDefinition FindDeviceDefinition(Item item, string deviceId) { var layoutField = item.Fields[FieldIDs.LayoutField]; var finalLayoutField = item.Fields[FieldIDs.FinalLayoutField]; if (layoutField == null && finalLayoutField == null) { Logger.Log($"The layout field is null", item.Paths.FullPath, LogType.FieldError); return(null); } var finalLayout = LayoutDefinition.Parse(finalLayoutField.Value); var deviceItem = finalLayout.GetDevice(deviceId); if (deviceItem != null) { Logger.Log($"The final layout field is null", item.Paths.FullPath, LogType.FieldError); return(deviceItem); } var layout = LayoutDefinition.Parse(layoutField.Value); deviceItem = layout.GetDevice(deviceId); return(deviceItem); }
/// <summary> /// Identify the items with a presentation detail /// </summary> /// <param name="item">Item to check</param> /// <returns></returns> private bool IsPage(Item item) { var result = false; var layoutField = new LayoutField(item.Fields[FieldIDs.LayoutField]); if (!layoutField.InnerField.HasValue || string.IsNullOrEmpty(layoutField.Value)) { return(false); } var layout = LayoutDefinition.Parse(layoutField.Value); foreach (var deviceObj in layout.Devices) { var device = deviceObj as DeviceDefinition; if (device == null) { return(false); } if (device.Renderings.Count > 0) { result = true; } } return(result); }
/// <summary> /// Gets the device definition for a given item and device. /// </summary> /// <param name = "theItem">The item.</param> /// <param name = "device">The device.</param> /// <returns>The device definition if it was found, null otherwise</returns> public static DeviceDefinition GetDeviceDefinition(Item theItem, DeviceItem device) { if (theItem == null || device == null) { return(null); } //Make sure there is a renderings string string renderingString = theItem.Fields["__renderings"].Value; if (string.IsNullOrEmpty(renderingString)) { return(null); } //Try and retrieve the layout definition by parsing the rendering string LayoutDefinition layout = LayoutDefinition.Parse(renderingString); if (layout == null) { return(null); } //Try and get the device definition from the layout definition return(layout.GetDevice(device.ID.ToString())); }
public static void MergeLayouts([NotNull] this Item item) { //Grab the field that contains the layout var layoutField = new LayoutField(item.Fields[Sitecore.FieldIDs.LayoutField]); //Grab the field that contains the final layout var finalLayoutField = new LayoutField(item.Fields[Sitecore.FieldIDs.FinalLayoutField]); if (layoutField == null) { throw new Exception("Couldn't find layout on: {0}".FormatWith(item.Name)); } if (finalLayoutField == null) { throw new Exception("Couldn't find final layout on: {0}".FormatWith(item.Name)); } //If we don't have a final layout delta, we're good! if (string.IsNullOrWhiteSpace(finalLayoutField.Value)) { return; } var finalLayoutDefinition = LayoutDefinition.Parse(finalLayoutField.Value); using (new EditContext(item)) { layoutField.Value = finalLayoutDefinition.ToXml(); item.Fields["__Final Renderings"].Reset(); item.Editing.AcceptChanges(); } }
/* * EXPOSE PRIVATE METHODS * - These are methods we need to call but can't because the are marked private, so ported over the source code and renamed with "_exposed" suffix. */ protected static LayoutDefinition GetLayoutDefinition_exposed() { string sessionString = WebUtil.GetSessionString(GetSessionHandle_exposed()); Assert.IsNotNull(sessionString, "layout definition"); return(LayoutDefinition.Parse(sessionString)); }
private static string ApplyActionToLayoutXml(Item item, string xml, string branchBasePath) { var layout = LayoutDefinition.Parse(xml); xml = layout.ToXml(); // normalize the output in case of any minor XML differences (spaces, etc) // loop over devices in the rendering for (var deviceIndex = layout.Devices.Count - 1; deviceIndex >= 0; deviceIndex--) { // ReSharper disable once UsePatternMatching 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--) { if (device.Renderings[renderingIndex] is RenderingDefinition rendering) { RelinkRenderingDatasource(item, rendering, branchBasePath); } } } var layoutXml = layout.ToXml(); // save a modified layout value if necessary return(layoutXml != xml ? layoutXml : null); }
protected override void ProcessItem(Item item) { LayoutField layoutField = item.Fields[LayoutFieldId]; if (string.IsNullOrEmpty(layoutField?.Value)) { return; } var layout = LayoutDefinition.Parse(layoutField.Value); if (Device == null) { Device = CurrentDatabase.Resources.Devices.GetAll().FirstOrDefault(d => d.IsDefault); } if (Device == null) { WriteError( new ErrorRecord( new ObjectNotFoundException( "Device not provided and no default device in the system is defined."), "sitecore_device_not_found", ErrorCategory.InvalidData, null)); return; } var device = layout.GetDevice(Device.ID.ToString()); if (device != null) { ProcessLayout(item, layout, device); } }
protected override bool Execute(T ruleContext) { if (string.IsNullOrWhiteSpace(RenderingItemId) || !ID.IsID(RenderingItemId)) { return(false); } var enhancedContext = ruleContext as PlaceholderSettingsRuleContext; if (enhancedContext == null) { return(false); } var layoutDefinition = LayoutDefinition.Parse(enhancedContext.Args.LayoutDefinition); var renderings = layoutDefinition.Devices.Cast <DeviceDefinition>() .Where(x => x != null) .SelectMany(x => x.Renderings.Cast <RenderingDefinition>()) .ToArray(); if (!renderings.Any()) { return(false); } var isNested = renderings.Any(x => x.ItemID.Equals(RenderingItemId, StringComparison.InvariantCultureIgnoreCase) && enhancedContext.PlaceholderKeyPath.TrimStart('/').StartsWith(x.Placeholder.TrimStart('/'))); return(isNested); }
/// <summary> /// Gets the list of placeholder definitions from a Layout field. /// </summary> /// <param name="definition">The raw value of the Layout field.</param> /// <param name="placeholderKey">The placeholder key.</param> /// <returns>The list of placeholder definitions.</returns> public static IEnumerable <PlaceholderDefinition> GetPlaceholderDefinitionList(string definition, string placeholderKey) { Assert.ArgumentNotNull(definition, nameof(definition)); Assert.ArgumentNotNull(placeholderKey, nameof(placeholderKey)); return(GetPlaceholderDefinitionList(LayoutDefinition.Parse(definition), placeholderKey, Context.IsUnitTesting ? new ID("{FE5D7FDF-89C0-4D99-9AA3-B5FBD009C9F3}") : Context.Device.ID)); }
protected void Run(ClientPipelineArgs args) { Assert.ArgumentNotNull(args, "args"); string id = args.Parameters["id"]; Language sourceLang = Language.Parse(args.Parameters["sourceLang"]); Language targetLang = Language.Parse(args.Parameters["targetLang"]); LinkSet = new HashSet <ID>(); Item item = Context.ContentDatabase.GetItem(id, targetLang); if (item == null) { return; } if (Context.IsAdministrator || (item.Access.CanWrite() && (item.Locking.CanLock() || item.Locking.HasLock()))) { if (SheerResponse.CheckModified()) { AddAllReferences(item); LayoutField layoutField = item.Fields[FieldIDs.LayoutField]; if (!string.IsNullOrEmpty(layoutField.Value)) { LayoutDefinition layout = LayoutDefinition.Parse(layoutField.Value); foreach (DeviceDefinition device in layout.Devices) { foreach (RenderingDefinition rendering in device.Renderings) { Item datasourceItem = Context.ContentDatabase.GetItem(rendering.Datasource ?? string.Empty, targetLang); if (datasourceItem == null) { continue; } AddAllReferences(datasourceItem); if (ChildrenGroupingTemplates.Contains(datasourceItem.TemplateName)) { foreach (Item childItem in datasourceItem.Children) { AddAllReferences(childItem); } } } } } foreach (ID linkId in LinkSet) { CopyVersion(linkId, sourceLang, targetLang); } } } }
/// <summary> /// Gets the definition. /// </summary> /// <returns> /// The definition. /// </returns> private LayoutDefinition GetLayoutDefinition() { if (layoutDefinition == null) { string sessionString = WebUtil.GetSessionString(HandleName); Assert.IsNotNull(sessionString, "sessionValue"); layoutDefinition = LayoutDefinition.Parse(sessionString); } return(layoutDefinition); }
/// <summary> /// Get Rendering /// </summary> /// <param name="renderingId"> /// The rendering Id. /// </param> /// <returns> /// returns Rendering as RenderingDefinition /// </returns> private static RenderingDefinition GetRendering(string renderingId) { var formValue = WebUtil.GetFormValue("scLayout"); var id = ShortID.Decode(WebUtil.GetFormValue("scDeviceID")); var layoutDefinition = WebEditUtil.ConvertJSONLayoutToXML(formValue); var parsedLayout = LayoutDefinition.Parse(layoutDefinition); var device = parsedLayout.GetDevice(id); var index = device.GetIndex(renderingId); return((RenderingDefinition)device.Renderings[index]); }
private List <RenderingDefinition> GetRenderingDefinitions(SafeDictionary <string> data) { var device = data["deviceId"]; var renderingFieldId = WebUtility.IsEditAllVersionsTicked() ? FieldIDs.LayoutField : FieldIDs.FinalLayoutField; var field = item.Fields[renderingFieldId]; var layoutXml = Sitecore.Data.Fields.LayoutField.GetFieldValue(field); var layout = LayoutDefinition.Parse(layoutXml); var deviceLayout = string.IsNullOrEmpty(device) ? layout.Devices[0] as DeviceDefinition : layout.GetDevice(device); return(deviceLayout?.Renderings.ToArray().Select(r => r as RenderingDefinition).ToList()); }
/// <summary> /// Intercepts item:saved event on sitecore item save. Checks if datasource values have been removed for each sublayout of the item. /// /// </summary> /// <param name="sender"></param> /// <param name="args"></param> public void OnRenderingDeleteDeleteDatasource(object sender, EventArgs args) { var args1 = (SitecoreEventArgs)args; var itemChanges = (ItemChanges)args1.Parameters[1]; if (itemChanges.HasFieldsChanged) { var layoutField = itemChanges.FieldChanges.OfType <FieldChange>().SingleOrDefault(f => f.FieldID == FieldIDs.FinalLayoutField); if (layoutField == null) { return; // presentation hasn't changed } string originalLayoutFieldValue = layoutField.OriginalValue; string newLayoutFieldValue = layoutField.Value; var originalLayoutDefinition = LayoutDefinition.Parse(originalLayoutFieldValue); var newLayoutDefinition = LayoutDefinition.Parse(newLayoutFieldValue); var originalRenderings = originalLayoutDefinition.GetDevice(Constants.Sitecore.LayoutDefinitionIDs.Default).Renderings.OfType <RenderingDefinition>().ToArray(); var newRenderings = newLayoutDefinition.GetDevice(Constants.Sitecore.LayoutDefinitionIDs.Default).Renderings.OfType <RenderingDefinition>().ToArray(); // find renderings in originalRenderings collection that do not exist in newRenderings var removedRenderings = originalRenderings.Where( candidateRendering => newRenderings.All(otherRendering => otherRendering.UniqueId != candidateRendering.UniqueId)).ToArray(); foreach (var removedRendering in removedRenderings) { var datasourceValue = removedRendering.Datasource; if (string.IsNullOrEmpty(datasourceValue)) { var property = removedRendering.DynamicProperties.SingleOrDefault(dp => dp.Name == Constants.Sitecore.DynamicPropertyNames.DataSource); if (property != null) { datasourceValue = property.Value; } } if (string.IsNullOrEmpty(datasourceValue)) { return; } var datasourceItem = Sitecore.Context.ContentDatabase.GetItem(datasourceValue); //check if item is references elsewhere var itemReferers = Globals.LinkDatabase.GetItemReferrers(datasourceItem, true); if (itemReferers.Any()) { return; //item is referenced return. DO NOT DELETE. } datasourceItem.Delete(); } } }
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)); }
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); } } } }
public override void Execute(CommandContext context) { string formValue = WebUtil.GetFormValue("scLayout"); string xml = WebEditUtil.ConvertJSONLayoutToXML(formValue); string id = ShortID.Decode(WebUtil.GetFormValue("scDeviceID")); LayoutDefinition layoutDefinition = LayoutDefinition.Parse(xml); if (layoutDefinition == null) { ReturnLayout(); return; } DeviceDefinition device = layoutDefinition.GetDevice(id); if (device == null) { ReturnLayout(); return; } string uniqueId = Guid.Parse(context.Parameters["renderingUid"]).ToString("B").ToUpperInvariant(); RenderingDefinition renderingByUniqueId = device.GetRenderingByUniqueId(uniqueId); if (renderingByUniqueId == null) { ReturnLayout(); return; } if (string.IsNullOrEmpty(renderingByUniqueId.Parameters)) { if (!string.IsNullOrEmpty(renderingByUniqueId.ItemID)) { RenderingItem renderingItem = Client.ContentDatabase.GetItem(renderingByUniqueId.ItemID); renderingByUniqueId.Parameters = ((renderingItem != null) ? renderingItem.Parameters : string.Empty); } else { renderingByUniqueId.Parameters = string.Empty; } } NameValueCollection nameValueCollection = WebUtil.ParseUrlParameters(renderingByUniqueId.Parameters); string input = nameValueCollection["FieldNames"]; string text = context.Parameters["variant"]; if (Guid.TryParse(input, out Guid result) && result == Guid.Parse(text)) { ReturnLayout(); return; } nameValueCollection["FieldNames"] = text; renderingByUniqueId.Parameters = new UrlString(nameValueCollection.EscapeDataValues()).GetUrl(); formValue = WebEditUtil.ConvertXMLLayoutToJSON(layoutDefinition.ToXml()); ReturnLayout(formValue); }