In a similar vein to my post on storing complex properties of a TableEntity in Azure Table Storage it’s also possible to store Enum text values by using custom attributes to control serialization/deserialization.
public class ReceiptRequestEntity : TableEntity
{
public ReceiptRequestEntity(string emailAddress, string functionInvocationId)
{
this.PartitionKey = emailAddress;
this.RowKey = functionInvocationId;
}
public bool? OptIn { get; set; }
public string Type { get; set; }
[EntityEnumPropertyConverter]
public ActionType? ActionType { get; set; }
public int? SequenceId { get; set; }
[EntityJsonPropertyConverter]
public Dictionary<int, string> Products { get; set; }
public string RedirectUri { get; set; }
[EntityJsonPropertyConverter]
public bool IsValid
{
get
{
bool _isValid = true;
if (string.IsNullOrEmpty(PartitionKey) || string.IsNullOrEmpty(Type) || string.IsNullOrEmpty(ActionType) || OptIn == null || SequenceId == null || Products.Count == 0)
{
_isValid = false;
}
return _isValid;
}
}
public override IDictionary<string, EntityProperty> WriteEntity(OperationContext operationContext)
{
var results = base.WriteEntity(operationContext);
EntityJsonPropertyConverter.Serialize(this, results);
EntityEnumPropertyConverter.Serialize(this, results);
return results;
}
public override void ReadEntity(IDictionary<string, EntityProperty> properties, OperationContext operationContext)
{
base.ReadEntity(properties, operationContext);
EntityJsonPropertyConverter.Deserialize(this, properties);
EntityEnumPropertyConverter.Deserialize(this, properties);
}
}
[AttributeUsage(AttributeTargets.Property)]
public class EntityEnumPropertyConverterAttribute : Attribute
{
public EntityEnumPropertyConverterAttribute()
{
}
}
public class EntityEnumPropertyConverter
{
public static void Serialize<TEntity>(TEntity entity, IDictionary<string, EntityProperty> results)
{
entity.GetType().GetProperties()
.Where(x => x.GetCustomAttributes(typeof(EntityEnumPropertyConverterAttribute), false).Count() > 0)
.ToList()
.ForEach(x => results.Add(x.Name, new EntityProperty(x.GetValue(entity) != null ? x.GetValue(entity).ToString() : null)));
}
public static void Deserialize<TEntity>(TEntity entity, IDictionary<string, EntityProperty> properties)
{
entity.GetType().GetProperties()
.Where(x => x.GetCustomAttributes(typeof(EntityEnumPropertyConverterAttribute), false).Count() > 0)
.ToList()
.ForEach(x => x.SetValue(entity, Enum.Parse(x.PropertyType, properties[x.Name].StringValue)));
}
}
0 Comments