Skip to content

Instantly share code, notes, and snippets.

@euyuil
Created September 8, 2014 04:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save euyuil/1a26caa1e44eaedd30f8 to your computer and use it in GitHub Desktop.
Save euyuil/1a26caa1e44eaedd30f8 to your computer and use it in GitHub Desktop.
Azure: support more types in azure table entities.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
/// <summary>
/// The table entities that extend from this type will have rich support in property types.
/// </summary>
public class RichTypeTableEntity : TableEntity
{
/// <inheritdoc/>
public override void ReadEntity(IDictionary<string, EntityProperty> properties, OperationContext operationContext)
{
base.ReadEntity(properties, operationContext);
foreach (var thisProperty in
GetType().GetProperties().Where(thisProperty =>
thisProperty.GetType() != typeof(string) &&
properties.ContainsKey(thisProperty.Name) &&
properties[thisProperty.Name].PropertyType == EdmType.String))
{
var parse = thisProperty.PropertyType.GetMethods().SingleOrDefault(m =>
m.Name == "Parse" &&
m.GetParameters().Length == 1 &&
m.GetParameters()[0].ParameterType == typeof(string));
var value = parse != null ?
parse.Invoke(thisProperty, new object[] { properties[thisProperty.Name].StringValue }) :
Convert.ChangeType(properties[thisProperty.Name].PropertyAsObject, thisProperty.PropertyType);
thisProperty.SetValue(this, value);
}
}
/// <inheritdoc/>
public override IDictionary<string, EntityProperty> WriteEntity(OperationContext operationContext)
{
var properties = base.WriteEntity(operationContext);
foreach (var thisProperty in
GetType().GetProperties().Where(thisProperty =>
!properties.ContainsKey(thisProperty.Name) &&
typeof(TableEntity).GetProperties().All(p => p.Name != thisProperty.Name)))
{
var value = thisProperty.GetValue(this);
if (value != null)
{
properties.Add(thisProperty.Name, new EntityProperty(value.ToString()));
}
}
return properties;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment