using System.ComponentModel.DataAnnotations;
using System.Xml;
namespace CHR.API.Provisioning.ATT.BusinessLogic.DataValidation
{
/// <inheritdoc />
/// <summary>
/// Data annotation attribute to verify that string is a valid XML
/// </summary>
public class ValidXml : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!(value is string))
{
return new ValidationResult($"'{validationContext.MemberName}' property of '{validationContext.ObjectType.Name}' class is not a string property.");
}
var xmlString = (string) value;
try
{
// Check we actually have a value
if (string.IsNullOrEmpty(xmlString) == false)
{
// Try to load the value into a document
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);
// If we managed with no exception then this is valid XML!
return ValidationResult.Success;
}
// A blank value is not valid xml
return new ValidationResult($"'{validationContext.MemberName}' is an empty string.");
}
catch (XmlException)
{
return new ValidationResult($"'{validationContext.MemberName}' is not a valid XML.");
}
}
}
}