public bool InsertEntity(string tableName, object obj) { try { TableServiceContext tableServiceContext = TableClient.GetDataServiceContext(); tableServiceContext.AddObject(tableName, obj); tableServiceContext.SaveChanges(); return(true); } catch (DataServiceRequestException) { return(false); } catch (StorageClientException ex) { if ((int)ex.StatusCode == 404) { return(false); } throw; } }
public List <T> GetEntries() { TableServiceContext ctx = tableClient.GetDataServiceContext(); var results = ctx.CreateQuery <T>(tableName); return(results.ToList()); }
private CloudTableQuery <EventTableServiceEntity> GetEntitiesQuery(string partitionKey, string minRowKey, string maxRowKey) { var context = tableClient.GetDataServiceContext(); var query = context .CreateQuery <EventTableServiceEntity>(tableName) .Where( x => x.PartitionKey == partitionKey && x.RowKey.CompareTo(minRowKey) >= 0 && x.RowKey.CompareTo(maxRowKey) <= 0); return(query.AsTableServiceQuery()); }
private static void InitializeTableSchemaFromEntity(CloudTableClient tableStorage, string entityName, TableServiceEntity entity) { TableServiceContext context = tableStorage.GetDataServiceContext(); DateTime now = DateTime.UtcNow; entity.PartitionKey = Guid.NewGuid().ToString(); entity.RowKey = Guid.NewGuid().ToString(); Array.ForEach( entity.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance), p => { if ((p.Name != "PartitionKey") && (p.Name != "RowKey") && (p.Name != "Timestamp")) { if (p.PropertyType == typeof(string)) { p.SetValue(entity, Guid.NewGuid().ToString(), null); } else if (p.PropertyType == typeof(DateTime)) { p.SetValue(entity, now, null); } } }); context.AddObject(entityName, entity); context.SaveChangesWithRetries(); context.DeleteObject(entity); context.SaveChangesWithRetries(); }
private void DeleteBook() { if (bookTree.SelectedNode == null) { return; } var bookNode = bookTree.SelectedNode as BookTreeNode; // Delete the book... CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); TableServiceContext tableContext = tableClient.GetDataServiceContext(); Book book = tableContext.CreateQuery <Book>("Book").Where(b => b.PartitionKey == bookNode.Book.PartitionKey && b.RowKey == bookNode.Book.RowKey).FirstOrDefault(); if (book == null) { throw new InvalidOperationException("The requested book was not found."); } tableContext.DeleteObject(book); tableContext.SaveChangesWithRetries(); CreateNewBook(); LoadAllBooks(); }
/// <summary> /// Creates tables from a DataServiceContext derived class. /// </summary> /// <param name="serviceContextType">A DataServiceContext derived class that defines the table schemas.</param> /// <param name="baseAddress">The baseAddress of the table storage endpoint.</param> /// <param name="credentials">Storage account credentials.</param> /// <remarks> /// For each table, the class exposes one or more IQueryable<T> properties, where T is a /// TableServiceEntity derived class with the required schema. /// </remarks> public static void CreateTablesFromModel(Type serviceContextType, string baseAddress, StorageCredentials credentials) { CloudTableClient.CreateTablesFromModel(serviceContextType, baseAddress, credentials); var tableStorage = new CloudTableClient(baseAddress, credentials); // Execute conditionally for development storage only if (tableStorage.BaseUri.IsLoopback) { TableServiceContext ctx = tableStorage.GetDataServiceContext(); PropertyInfo[] properties = serviceContextType.GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach ( PropertyInfo table in properties.Where( p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(IQueryable <>))) { var entity = Activator.CreateInstance(table.PropertyType.GetGenericArguments()[0]) as TableServiceEntity; if (entity != null) { InitializeTableSchemaFromEntity(tableStorage, table.Name, entity); } } } }
public bool SaveBtsAssemblyFilesMetadata(BtsAssemblyFilesMetadata btsAssemblyFilesMetadata) { this.tableClient = account.CreateCloudTableClient(); this.tableClient.CreateTableIfNotExist(MapFilesTableName); this.tableContext = tableClient.GetDataServiceContext(); btsAssemblyFilesMetadata.PartitionKey = btsAssemblyFilesMetadata.FileName; btsAssemblyFilesMetadata.RowKey = btsAssemblyFilesMetadata.FileName; btsAssemblyFilesMetadata.Timestamp = DateTime.UtcNow; if (MapFiles.FirstOrDefault(t => t.PartitionKey == btsAssemblyFilesMetadata.PartitionKey && t.RowKey == btsAssemblyFilesMetadata.RowKey) == null) { MapFiles.Add(btsAssemblyFilesMetadata); } // We need upsert functionality here, hence removing AddObject call and adding UpdateObject // this.tableContext.AddObject(MapFilesTableName, tradingPartnerSpecCert); // http://social.msdn.microsoft.com/Forums/windowsazure/en-US/892340f1-bfe1-4433-9246-b617abe6078c/upsert-operation-in-the-table // http://msdn.microsoft.com/en-us/library/windowsazure/hh452242.aspx // http://www.windowsazure.com/en-us/develop/net/how-to-guides/table-services/#replace-entity tableContext.AttachTo(MapFilesTableName, btsAssemblyFilesMetadata); tableContext.UpdateObject(btsAssemblyFilesMetadata); DataServiceResponse response = this.tableContext.SaveChangesWithRetries(SaveChangesOptions.Batch | SaveChangesOptions.ReplaceOnUpdate); return(response.BatchStatusCode == Http200 || response.BatchStatusCode == Http201 || response.BatchStatusCode == Http202); }
public IQueryable <T> CreateQuery() { var ctx = tableClient.GetDataServiceContext(); var q = from e in ctx.CreateQuery <T>(tableName) select e; return(q); }
private static TableServiceContext GetContext() { CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString"); CloudTableClient tableStorage = account.CreateCloudTableClient(); TableServiceContext context = tableStorage.GetDataServiceContext(); return(context); }
public BaseCommerceDal(IDalManager manager, CloudStorageAccount account, string tableName) { this.manager = manager; tableClient = account.CreateCloudTableClient(); tableClient.CreateTableIfNotExist(tableName); this.tableContext = tableClient.GetDataServiceContext(); }
/// <summary> /// Returns table service context /// </summary> /// <returns></returns> public TableServiceContext GetTableContext() { if (tableClient == null) { GetCloudTableClient(); } return(tableClient.GetDataServiceContext()); }
public void Insert(params TableServiceEntity[] entries) { foreach (var i in entries) { var serviceContext = tableClient.GetDataServiceContext(); serviceContext.AddObject(tableName, i); serviceContext.SaveChangesWithRetries(); } }
private List <TableColumnsMetadataEntity> GetColumnsMetadata() { CloudTableClient clientTable = new CloudTableClient(_Account.TableEndpoint.ToString(), _Account.Credentials); TableServiceContext serviceContextTable = clientTable.GetDataServiceContext(); string query = string.Format("TableColumnsMetadata?$filter=entityset eq '{0}'", EntitySet); List <TableColumnsMetadataEntity> resultsQuery = serviceContextTable.Execute <TableColumnsMetadataEntity>(new Uri(query, UriKind.Relative)).ToList(); return(resultsQuery); }
protected TableServiceContext GetUsersContext() { if (_storageAccount == null) { _storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString"); } if (_cloudTableClient == null) { _cloudTableClient = _storageAccount.CreateCloudTableClient(); } TableServiceContext tableServiceContext = _cloudTableClient.GetDataServiceContext(); tableServiceContext.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromMinutes(1)); tableServiceContext.ResolveType = (unused) => typeof(UserProfile); return(tableServiceContext); }
private void LoadAllBooks() { // Load all books... CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); TableServiceContext tableContext = tableClient.GetDataServiceContext(); tableClient.CreateTableIfNotExist("Book"); Refresh(tableContext.CreateQuery <Book>("Book").AsTableServiceQuery <Book>()); }
private void StoreInTable(string logmessage) { TableServiceContext context = tableClient.GetDataServiceContext(); LogEntity newVisitor = new LogEntity(DateTime.Now.ToString("MM-dd-yyyy")) { logMessage = logmessage }; context.AddObject(Constants.LogTable, newVisitor); context.SaveChanges(); }
private static TableServiceContext GetTableContext() { TableServiceContext tableContext; tableContext = _tableClient.GetDataServiceContext(); tableContext.RetryPolicy = RetryPolicies.RetryExponential(RetryPolicies.DefaultClientRetryCount, RetryPolicies.DefaultMaxBackoff); tableContext.IgnoreMissingProperties = true; tableContext.SaveChangesDefaultOptions = SaveChangesOptions.ReplaceOnUpdate; tableContext.IgnoreResourceNotFoundException = true; return(tableContext); }
private void LoadAllBooksInTheBiographyCategory() { // Load all books in the "Biography" category... CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); TableServiceContext tableContext = tableClient.GetDataServiceContext(); tableClient.CreateTableIfNotExist("Book"); Refresh( tableContext.CreateQuery <Book>("Book").Where(b => b.PartitionKey == "Biography").AsTableServiceQuery()); }
public static void Insert(string account, string key, string table, string data) { CloudTableClient tableClient = Client.GetTableClient(account, key); TableServiceContext context = tableClient.GetDataServiceContext(); context.WritingEntity += new EventHandler <ReadingWritingEntityEventArgs>(context_WritingEntity); TableEntity entity = TableEntity.Get(data); context.AddObject(table, entity); context.SaveChangesWithRetries(SaveChangesOptions.ReplaceOnUpdate); }
private List <BtsAssemblyFilesMetadata> GetAllBtsAssemblyFiles() { this.tableClient = account.CreateCloudTableClient(); this.tableClient.CreateTableIfNotExist(MapFilesTableName); this.tableContext = tableClient.GetDataServiceContext(); List <BtsAssemblyFilesMetadata> btsAssemblyFiles = (from mapFilesMetadata in tableContext.CreateQuery <BtsAssemblyFilesMetadata>(MapFilesTableName) select mapFilesMetadata).ToList(); return(btsAssemblyFiles); }
private List <TradingPartnerSpecCertMetadata> GetAllTradingPartnerSpecCert() { this.tableClient = account.CreateCloudTableClient(); this.tableClient.CreateTableIfNotExist(TradingPartnerSpecCertTableName); this.tableContext = tableClient.GetDataServiceContext(); List <TradingPartnerSpecCertMetadata> tradingPartnerSpecCerts = (from tradingPartnerSpecCertMetadata in tableContext.CreateQuery <TradingPartnerSpecCertMetadata>(TradingPartnerSpecCertTableName) select tradingPartnerSpecCertMetadata).ToList(); return(tradingPartnerSpecCerts); }
private List <BizRuleCertMetadata> GetAllBizRuleCert() { this.tableClient = account.CreateCloudTableClient(); this.tableClient.CreateTableIfNotExist(BizRuleCertTableName); this.tableContext = tableClient.GetDataServiceContext(); List <BizRuleCertMetadata> bizRuleCerts = (from bizRuleCertMetadata in tableContext.CreateQuery <BizRuleCertMetadata>(BizRuleCertTableName) select bizRuleCertMetadata).ToList(); return(bizRuleCerts); }
private void LoadAllBooksThatStartWithTheLetterC() { // Load all books that start with the letter "C" using a partition scan... CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); TableServiceContext tableContext = tableClient.GetDataServiceContext(); tableClient.CreateTableIfNotExist("Book"); Refresh( tableContext.CreateQuery <Book>("Book").Where( b => (b.RowKey.CompareTo("C") >= 0) && (b.RowKey.CompareTo("D") < 0)).AsTableServiceQuery()); }
/// <summary> /// Initializes static members of the PerformanceCountersDataSource class. /// </summary> static PerformanceCountersDataSource() { storageAccount = CloudStorageAccount.Parse( WebRole.GetConfigurationSettingValue(WebRole.WADConnectionString)); CloudTableClient cloudTableClient = new CloudTableClient( storageAccount.TableEndpoint.ToString(), storageAccount.Credentials); serviceContext = cloudTableClient.GetDataServiceContext(); serviceContext.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(1.0d)); roleId = RoleEnvironment.CurrentRoleInstance.Id; }
// Table will come back sorted by (parition, row key) // Integers don't sort nicely as strings. public static T[] ReadTable <T>(CloudStorageAccount account, string tableName) where T : TableServiceEntity { CloudTableClient tableClient = account.CreateCloudTableClient(); TableServiceContext ctx = tableClient.GetDataServiceContext(); var query = from row in ctx.CreateQuery <T>(tableName) select row; var query2 = query.AsTableServiceQuery <T>(); // Verify table matches source T[] result = query2.ToArray(); return(result); }
public static void DeleteEntity(string account, string key, string table, string partitionKey, string rowKey) { CloudTableClient tableClient = Client.GetTableClient(account, key); TableServiceContext context = tableClient.GetDataServiceContext(); TableEntity entity = new TableEntity() { PartitionKey = partitionKey, RowKey = rowKey }; context.AttachTo(table, entity, "*"); context.DeleteObject(entity); context.SaveChangesWithRetries(SaveChangesOptions.None); }
// Very similar to EventStore.cs private IEnumerable <EventTableServiceEntity> GetAllEventSourcingEntries(CloudTableClient tableClient, string tableName) { var context = tableClient.GetDataServiceContext(); var query = context .CreateQuery <EventTableServiceEntity>(tableName) .AsTableServiceQuery(); var result = new BlockingCollection <EventTableServiceEntity>(); var tokenSource = new CancellationTokenSource(); this.retryPolicy.ExecuteAction( ac => query.BeginExecuteSegmented(ac, null), ar => query.EndExecuteSegmented(ar), rs => { foreach (var key in rs.Results) { result.Add(key); } while (rs.HasMoreResults) { try { rs = this.retryPolicy.ExecuteAction(() => rs.GetNext()); foreach (var key in rs.Results) { result.Add(key); } } catch { // Cancel is to force an exception being thrown in the consuming enumeration thread // TODO: is there a better way to get the correct exception message instead of an OperationCancelledException in the consuming thread? tokenSource.Cancel(); throw; } } result.CompleteAdding(); }, ex => { tokenSource.Cancel(); throw ex; }); return(result.GetConsumingEnumerable(tokenSource.Token)); }
// Get contacts filtered by prefix. public static List <ContactEntity> GetContactsByPrefix(string prefix) { IQueryable <ContactEntity> query = tableClient.GetDataServiceContext().CreateQuery <ContactEntity>(tableName); if (prefix != null) { query = query.Where(c => c.PartitionKey == prefix.ToUpper()); } return(query.AsTableServiceQuery().ToList()); }
public void InitializeHostedServiceStatus(string serviceRegion, string serviceUrlPrefix) { try { CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString"); CloudTableClient tableStorage = account.CreateCloudTableClient(); TableServiceContext context = tableStorage.GetDataServiceContext(); tableStorage.CreateTableIfNotExist(ServiceStatusTableName); CloudServiceStatus status = context.CreateQuery <CloudServiceStatus>(ServiceStatusTableName) .Where(p => p.RowKey == serviceUrlPrefix) .AsTableServiceQuery() .SingleOrDefault(); if (status == null) { status = new CloudServiceStatus() { PartitionKey = string.Empty, RowKey = serviceUrlPrefix, Region = serviceRegion, IsOnline = true }; context.AddObject(ServiceStatusTableName, status); } else { status.Region = serviceRegion; status.IsOnline = true; context.UpdateObject(status); } context.SaveChangesWithRetries(); } catch (StorageClientException) { // A StorageClientException that returns the error message "Unexpected internal storage client error" may be retried. Other // errors are due to incorrect request parameters and should not be retried with the same parameters. // DiagnosticUtility.Trace.LogException(scex, "Error initializing storage due to a client-side error."); } catch (StorageServerException) { // These may be transient and requests resulting in such exceptions can be retried with the same parameters. // DiagnosticUtility.Trace.LogException(ssex, "Error initializing storage due to a server-side error."); } }
public static IEnumerable <TableEntity> Query(string account, string key, string table, string query) { //http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/481afa1b-03a9-42d9-ae79-9d5dc33b9297/ //http://stackoverflow.com/questions/2363399/problem-accesing-azure-table-entities/2370814#2370814 //http://azuretablequery.codeplex.com/ CloudTableClient tableClient = Client.GetTableClient(account, key); TableServiceContext context = tableClient.GetDataServiceContext(); context.ReadingEntity += new EventHandler <ReadingWritingEntityEventArgs>(context_ReadingEntity); StringBuilder builder = new StringBuilder(); Uri url = new Uri(string.Format("{0}{1}{2}", tableClient.BaseUri, table, string.IsNullOrEmpty(query) ? string.Empty : "?$filter=" + query)); return(context.Execute <TableEntity>(url)); }