Skip to content

Instantly share code, notes, and snippets.

@jstemerdink
Created January 4, 2019 12:52
Show Gist options
  • Save jstemerdink/c5094b894dbbdd8178b618d10fe262c7 to your computer and use it in GitHub Desktop.
Save jstemerdink/c5094b894dbbdd8178b618d10fe262c7 to your computer and use it in GitHub Desktop.

Validate if a shortcut references a shortcut

Read my blog here

Powered by ReSharper image

using System.Collections.Generic;
using System.Linq;
using EPiServer;
using EPiServer.Core;
using EPiServer.Framework.Localization;
using EPiServer.ServiceLocation;
using EPiServer.Validation;
/// <summary>
/// Validates that when a shortcut (e.g. Shortcut or Fetchdata) is used that the property
/// <see cref="F:EPiServer.DataAbstraction.MetaDataProperties.PageShortcutLink" /> is not referencing a page that is a shortcut.
/// </summary>
/// <exclude />
[ServiceConfiguration]
public class PageShortcutLoopValidator : IValidate<PageData>
{
/// <summary>
/// The localization service
/// </summary>
private readonly LocalizationService localizationService;
/// <summary>
/// The content loader
/// </summary>
private readonly IContentLoader contentLoader;
/// <summary>
/// Initializes a new instance of the <see cref="PageShortcutLoopValidator"/> class.
/// </summary>
/// <param name="localizationService">The localization service.</param>
/// <param name="contentLoader">The content loader.</param>
public PageShortcutLoopValidator(LocalizationService localizationService, IContentLoader contentLoader)
{
this.localizationService = localizationService;
this.contentLoader = contentLoader;
}
/// <summary>
/// Validates the specified page.
/// </summary>
/// <param name="instance">The page.</param>
/// <returns>
/// </returns>
/// <exclude />
public IEnumerable<ValidationError> Validate(PageData instance)
{
ValidationError validationError = null;
ContentReference shortcutLink = ((ContentReference)instance["PageShortcutLink"]).ToPageReference();
switch (instance.LinkType)
{
case PageShortcutType.Shortcut:
PageData linkedContent = this.contentLoader.Get<PageData>(contentLink: shortcutLink);
if (linkedContent.LinkType == PageShortcutType.Shortcut)
{
string str = this.localizationService.GetString(
"/validation/pagelinksettings/shortcutpagereferenceshortcut", FallbackBehaviors.None);
validationError = new ValidationError
{
Severity = ValidationErrorSeverity.Error,
PropertyName = "PageShortcutType",
RelatedProperties = new[] { "PageShortcutLink" },
ErrorMessage =
string.IsNullOrEmpty(value: str)
? "When shortcut is set, the shortcut cannot reference a page that is a shortcut"
: str
};
}
break;
}
return validationError == null ? Enumerable.Empty<ValidationError>() : new[] { validationError };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment