Skip to content

Instantly share code, notes, and snippets.

@marciogoularte
Created October 29, 2016 02:11
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 marciogoularte/aa36bf9db618ec05fec76e856e693f84 to your computer and use it in GitHub Desktop.
Save marciogoularte/aa36bf9db618ec05fec76e856e693f84 to your computer and use it in GitHub Desktop.
Checking duplicates umbracoUrlName Umbraco 7
public class RegisterDuplicateUrlNameDetector : ApplicationEventHandler
{
protected override void ApplicationStarting
(UmbracoApplicationBase umbracoApplication,
ApplicationContext applicationContext)
{
ContentService.Publishing += ContentServicePublishing;
}
static void ContentServicePublishing(IPublishingStrategy sender,
PublishEventArgs<IContent> e)
{
foreach (var content in e.PublishedEntities){
// get content items UrlName - (more than one content item could be being published, hence the foreach)
var contentUrlName = content.HasProperty("umbracoUrlName") &&
!String.IsNullOrEmpty(content.GetValue<string>("umbracoUrlName"))
? content.GetValue<string>("umbracoUrlName")
: content.Name;
//get sibling content, eg published nodes at the same level in the tree that could contain a clashing url
if (content.Parent().Children().Any(f=>f.Id != content.Id && f.Published))
{
foreach (var sibling in content.Parent().Children().Where(f => f.Id != content.Id && f.Published))
{
// get each sibling UrlName
var siblingUrlName = sibling.HasProperty("umbracoUrlName") &&
!String.IsNullOrEmpty(sibling.GetValue<string>("umbracoUrlName"))
? sibling.GetValue<string>("umbracoUrlName")
: sibling.Name;
// check for clash
if (siblingUrlName.ToUrlSegment() == contentUrlName.ToUrlSegment())
{
// cancel publishing
e.Cancel = true;
// bubble up a message to the UI (umbraco 7.3 only)
e.Messages.Add(new EventMessage("Save Cancelled", "Clash of UrlNames: " + sibling.Id + "-" + sibling.Name + " and " + content.Id + "-" + content.Name, EventMessageType.Error));
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment