Skip to content

Instantly share code, notes, and snippets.

@jstemerdink
Created September 12, 2018 15:58
  • 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
Embed
What would you like to do?
using EPiServer.Core;
using EPiServer.Find;
using EPiServer.Find.Cms;
using EPiServer.Find.Framework;
using EPiServer.Find.Helpers;
using EPiServer.Find.Json;
using EPiServer.Reference.Commerce.Site.Features.Product.Models;
using EPiServer.Validation;
using Newtonsoft.Json;
public class SerializationValidator : IValidate<IContent>
{
IEnumerable<ValidationError> IValidate<IContent>.Validate(IContent content)
{
JsonSerializer jsonSerializer = Serializer.CreateDefault();
Action<JsonSerializer> customizeSerializer = SearchClient.Instance.CustomizeSerializer;
customizeSerializer(obj: jsonSerializer);
IClientConventions defaultConventions = SearchClient.Instance.Conventions;
if (defaultConventions.ContractResolver.IsNotNull())
{
jsonSerializer.ContractResolver = defaultConventions.ContractResolver;
}
if (defaultConventions.CustomizeSerializer.IsNotNull())
{
defaultConventions.CustomizeSerializer(obj: jsonSerializer);
}
try
{
jsonSerializer.Serialize(value: content);
}
catch (SelfReferencingLoopException selfReferencingLoopException)
{
string message = selfReferencingLoopException.ExplainIndexException();
return new[]
{
new ValidationError
{
ErrorMessage = message,
PropertyName = selfReferencingLoopException.GetType().Name,
Severity = ValidationErrorSeverity.Warning,
ValidationType = ValidationErrorType.Unspecified
}
};
}
catch (MaxSerializationDepthExceededException maxSerializationDepthExceededException)
{
return new[]
{
new ValidationError
{
ErrorMessage =
maxSerializationDepthExceededException
.ExplainIndexException(),
PropertyName =
maxSerializationDepthExceededException.GetType().Name,
Severity = ValidationErrorSeverity.Warning,
ValidationType = ValidationErrorType.Unspecified
}
};
}
catch (Serializer.JsonItemSerializationException jsonItemSerializationException)
{
return new[]
{
new ValidationError
{
ErrorMessage =
jsonItemSerializationException.ExplainIndexException(),
PropertyName = jsonItemSerializationException.GetType().Name,
Severity = ValidationErrorSeverity.Warning,
ValidationType = ValidationErrorType.Unspecified
}
};
}
catch (JsonSerializationException jsonSerializationException)
{
return new[]
{
new ValidationError
{
ErrorMessage =
jsonSerializationException.ExplainIndexException(),
PropertyName = jsonSerializationException.GetType().Name,
Severity = ValidationErrorSeverity.Warning,
ValidationType = ValidationErrorType.Unspecified
}
};
}
return new ValidationError[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment