Skip to content

Instantly share code, notes, and snippets.

@rcurlette
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcurlette/e0faf9fde0951cb29b40 to your computer and use it in GitHub Desktop.
Save rcurlette/e0faf9fde0951cb29b40 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Linq;
using Tridion.ContentManager.ContentManagement;
using Tridion.ContentManager.Extensibility;
using Tridion.ContentManager.Extensibility.Events;
namespace Tridion.EventSystem
{
[TcmExtension("ComponentSave")]
public class ComponentSave : TcmExtension
{
public ComponentSave()
{
EventSystem.Subscribe<Component, SaveEventArgs>( ComponentSaveInitiatedHandler, EventPhases.Initiated);
}
private void ComponentSaveInitiatedHandler(Component component, SaveEventArgs args, EventPhases phase)
{
PreventCircularReferences(component);
}
List<string> _metaFieldNames = new List<string>{"mobile", "mobile-alt"};
/// <summary>
/// Don't allow a Component to link to itself in the Metadata field
/// </summary>
/// <param name="component"></param>
private void PreventCircularReferences(Component component)
{
foreach (string fieldname in _metaFieldNames)
{
if ((component.Metadata != null) && (component.Metadata[fieldname] != null) && (component.Metadata[fieldname].Attributes["xlink:href"].Value != ""))
{
string linkedComponentUri = component.Metadata[fieldname].Attributes["xlink:href"].Value;
Component linkedComponent = (Component)component.Session.GetObject(linkedComponentUri);
if (linkedComponent.Id.ItemId == component.Id.ItemId)
{
throw new CircularReferenceException("The current Component is linked to itself in the Metadata fields. This is a problem. Please remove the Metadata Component Link to this Component. Thank you.");
}
}
}
}
[Serializable]
public class CircularReferenceException : Exception
{
public CircularReferenceException() { }
public CircularReferenceException(string message) : base(message) { }
public CircularReferenceException(string message, Exception inner) : base(message, inner) { }
protected CircularReferenceException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment