using System; using System.Collections.Generic; using System.Linq; using System.Text; using Sitecore.Data; using Sitecore.Data.Events; using Sitecore.Data.Items; using Sitecore.Events; using Sitecore.Layouts; namespace ParTech.Library.Events { public class CreateDataSource { public void OnItemCreated(object sender, EventArgs e) { // Get the created item ItemCreatedEventArgs args = Event.ExtractParameter(e, 0) as ItemCreatedEventArgs; if (args == null) { return; } // Get the components (renderings) that are set on this item var item = args.Item; string renderingsXml = item.Fields[Sitecore.FieldIDs.LayoutField].Value; if (String.IsNullOrEmpty(renderingsXml)) { return; } // Parse the rendering Xml to get the LayoutDefinition which we can then read and modify var presentation = LayoutDefinition.Parse(renderingsXml); foreach (DeviceDefinition device in presentation.Devices) { foreach (RenderingDefinition rendering in device.Renderings) { // Retrieve the Rendering item to access its settings Item renderingItem = item.Database.GetItem(new ID(rendering.ItemID)); // Only create a datasource item if this is required if (renderingItem["Requires datasource"] == "1") { // Retrieve the datasource target folder and template/branch string folderPath = renderingItem["Datasource location"]; string templatePath = renderingItem["Datasource template"]; string itemName = String.Format("{0} {1} datasource", item.Name, renderingItem.Name); Item folder = item.Database.GetItem(folderPath); Item templateOrBranch = item.Database.GetItem(templatePath); Item datasource = null; if (templateOrBranch.TemplateID.Equals(Sitecore.TemplateIDs.BranchTemplate)) { // Create the datasource item based on a branch datasource = folder.Add(itemName, (BranchItem)templateOrBranch); } else { // Create the datasource item based on a template datasource = folder.Add(itemName, (TemplateItem)templateOrBranch); } // Store the datasource path in the presentation details rendering.Datasource = datasource.Paths.FullPath; } } } // Update the item if its presentation was modified string updatedXml = presentation.ToXml(); if (!renderingsXml.Equals(updatedXml)) { item.Editing.BeginEdit(); item.Fields[Sitecore.FieldIDs.LayoutField].Value = updatedXml; item.Editing.EndEdit(); } } } }