Monday, February 20, 2012

Fixing Default Date issues in Azure Table Storage

In newer versions of Azure, the minimum acceptable date in Table Storage is far further in the future than the minimum date in .NET. This means that if you have a DateTime property and you don't explicitly initialize it you will get a "One of the request inputs is out of range" error. Personally, I'd rather not have to explicitly initialize every value. I liked in previous versions of Azure, when it would just default to the DateTime.MinDate and everything was fine.

An easy way to manage this is to reset the default date for any DateTime properties before writing to Azure Table Storage. The way I chose to do this was to add a function to the WritingEntity event in the table context. See the code below:


public class SafeDateContext : TableServiceContext
{
private static MinAzureUtcDate = new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc);

public SafeDateContext(CloudStorageAccount account)
: base(account.TableEndpoint.ToString(), account.Credentials)
{
WritingEntity += new EventHandler(FixDates);
}

private void FixDates(ReadingWritingEntityEventArgs e)
{
// The XML of the properties already being sent to Azure
XElement properties = e.Data.Descendants(Meta + "properties").First();

foreach (var p in properties.Elements())
{
string type = p.Attribute(Meta + "type") == null ? null : p.Attribute(Meta + "type").Value;
bool isNull = string.Equals("true", p.Attribute(Meta + "null") == null ? null : p.Attribute(Meta + "null").Value, StringComparison.OrdinalIgnoreCase);
if (!isNull && type == "Edm.DateTime")
{
string value = p.Value;
DateTime dateValue = (DateTime)ConvertType(type, value, isNull);
if (dateValue < MinAzureUtcDate)
{
p.SetValue(MinAzureUtcDate);
}
}
}
}

No comments:

Post a Comment