Skip to content

Instantly share code, notes, and snippets.

@sholfen
Last active February 14, 2016 07:39
Show Gist options
  • Save sholfen/653ab040871c41c2c109 to your computer and use it in GitHub Desktop.
Save sholfen/653ab040871c41c2c109 to your computer and use it in GitHub Desktop.
base class for Azure cloud table
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System;
namespace Models
{
public class BaseCloudTableModel
{
protected CloudTableClient cloudTableClient;
public BaseCloudTableModel()
{
CloudStorageAccount cloudAccount = CloudStorageAccount.DevelopmentStorageAccount;
CloudStorageAccount.TryParse(
System.Configuration.ConfigurationManager.AppSettings["blobStorage"],
out cloudAccount);
this.cloudTableClient = cloudAccount.CreateCloudTableClient();
}
private void HandleStorageException(Exception ex)
{
StorageException excep = ex as StorageException;
if (excep != null)
{
var extendedInformation = excep.RequestInformation.ExtendedErrorInformation;
var errorCode = extendedInformation.ErrorCode;
}
}
private string GetUniqueId(string input)
{
string result = string.Empty;
char[] chars = new char[]
{
'a','b','c','d','e','f','g','h',
'i','j','k','l','m','n','o','p',
'q','r','s','t','u','v','w','x',
'y','z','0','1','2','3','4','5',
'6','7','8','9','A','B','C','D',
'E','F','G','H','I','J','K','L',
'M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z'
};
byte[] bytes = Encoding.UTF8.GetBytes(input);
MD5 md5 = MD5.Create();
byte[] md5Bytes = md5.ComputeHash(bytes);
string strMd5Result = BitConverter.ToString(md5Bytes).Replace("-", string.Empty);
for (int i = 0; i < 1; i++)
{
int intMd5SubStr = Convert.ToInt32(strMd5Result.Substring(i * 8, 8), 16);
Console.WriteLine(intMd5SubStr);
for (int j = 0; j < 6; j++)
{
int intMask = 31; //0x001F
result += chars[intMask & intMd5SubStr];
intMd5SubStr >>= 5;
}
}
return result;
}
public void AddObjectToCloudTable(string tableName, string objId, TableEntity entity)
{
try
{
var cloudTable = this.cloudTableClient.GetTableReference(tableName);
bool blCreateTable = cloudTable.CreateIfNotExists();
string id = this.GetUniqueId(objId);
entity.RowKey = id;
// Create the TableOperation that inserts the customer entity.
TableOperation insertOperation = TableOperation.Insert(entity);
// Execute the insert operation.
cloudTable.Execute(insertOperation);
}
catch (Exception ex)
{
HandleStorageException(ex);
throw ex;
}
}
public T GetObject<T>(string tableName, string objId) where T : TableEntity
{
T obj = null;
var cloudTable = this.cloudTableClient.GetTableReference(tableName);
string rowKey = this.GetUniqueId(objId);
TableOperation operation = TableOperation.Retrieve<T>(tableName, rowKey);
TableResult result = cloudTable.Execute(operation);
if (result.Result != null)
{
obj = result.Result as T;
}
return obj;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment