Skip to content

Instantly share code, notes, and snippets.

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save johnligt/b731987dc99ec8a511f27edb34f92033 to your computer and use it in GitHub Desktop.
using EPiServer;
using EPiServer.DataAnnotations;
using EPiServer.SpecializedProperties;
using EPiServer.Web.Routing;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.ModelBinding;
namespace LinkItemAllowedTypes.Business.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class LinkItemAllowedTypesAttribute : ValidationAttribute, IMetadataAware
{
public Type[] AllowedTypes { get; set; }
public LinkItemAllowedTypesAttribute(Type[] allowedTypes)
{
AllowedTypes = allowedTypes;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
{
return null;
}
if (!(value is LinkItemCollection))
{
return ValidationResult.Success;
}
if (((LinkItemCollection)value).Count <= 0)
{
return ValidationResult.Success;
}
foreach (var linkItem in (LinkItemCollection)value)
{
var linkItemValidated = false;
var content = UrlResolver.Current.Route(new UrlBuilder(linkItem.Href));
if (content == null)
{
continue;
}
var originalType = content.GetOriginalType();
foreach (var allowedPageType in AllowedTypes)
{
if (!allowedPageType.IsAssignableFrom(originalType))
{
continue;
}
linkItemValidated = true;
break;
}
if (linkItemValidated)
{
continue;
}
var validationErrorResult = new ValidationResult
(ErrorMessage = string.Format(
App_GlobalResources.ValidationMessagesResources.LinkItemTypeNotAllowedErrorMessage,
GetDisplayName(originalType), validationContext.DisplayName));
return !string.IsNullOrEmpty(ErrorMessage) ?
new ValidationResult(ErrorMessage) : validationErrorResult;
}
return ValidationResult.Success;
}
public void OnMetadataCreated(ModelMetadata metadata)
{
//throw new NotImplementedException();
}
public override bool RequiresValidationContext
{
get
{
return true;
}
}
private static string GetDisplayName(Type type)
{
var contentTypeAttribute = type.GetCustomAttributes(typeof(ContentTypeAttribute), true)
.FirstOrDefault() as ContentTypeAttribute;
var displayName = contentTypeAttribute?.DisplayName;
return !string.IsNullOrEmpty(displayName) ? displayName : "";
}
}
}
@johnligt
Copy link
Author

johnligt commented Sep 18, 2020

This version of the LinkItemAllowedTypesAttribute supports inherited types.
The implementation depends on the existence of App_GlobalResources.ValidationMessagesResources.LinkItemTypeNotAllowedErrorMessage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment