Tuesday, January 4, 2011

generic TableStorage

TableStorage is an excellent and scalable way to store your tabular data in a cheap way. Working with tables is easy and straightforward but writing classes for every single one of them is not necessary by using generics.

public class DynamicDataContext : TableServiceContext where T : TableServiceEntity
{
private CloudStorageAccount _storageAccount;
private string _entitySetName;

public DynamicDataContext(CloudStorageAccount storageAccount)
: base(storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials)
{
_storageAccount = storageAccount;
_entitySetName = typeof(T).Name;
var tableStorage = new CloudTableClient(_storageAccount.TableEndpoint.AbsoluteUri, _storageAccount.Credentials);
}
public void Add(T entityToAdd)
{
AddObject(_entitySetName, entityToAdd);
SaveChanges();
}

public void Update(T entityToUpdate)
{
UpdateObject(entityToUpdate);
SaveChanges();
}

public void Delete(T entityToDelete)
{
DeleteObject(entityToDelete);
SaveChanges();
}

public IQueryable Load()
{
return CreateQuery(_entitySetName);
}
}

This is all you need for addressing your tables, adding, updating and deleting entities. And best of all, unleashing Linq at your entities!

See here how to use it for example with your performancecounter data (WADPerformanceCountersTable) in your storage account.

Microsoft.WindowsAzure.StorageCredentialsAccountAndKey sca = new Microsoft.WindowsAzure.StorageCredentialsAccountAndKey("performancecounters",
"blablablablabla");
Microsoft.WindowsAzure.CloudStorageAccount csa = new Microsoft.WindowsAzure.CloudStorageAccount(sca, true);

var PerformanceCountersContext = new DynamicDataContext(csa);

//fire your Linq
var performanceCounters = (from perfCounterEntry in PerformanceCountersContext.Load()

where (perfCounterEntry.EventTickCount >= fromTicks) &&
(perfCounterEntry.EventTickCount <= toTicks) &&
(perfCounterEntry.CounterName.CompareTo(PerformanceCounterName) == 0)
select perfCounterEntry).ToList();

No comments:

Post a Comment