Esempio n. 1
0
        /// <summary>
        /// Gets the entity from the requested table, using the key identifier.
        /// </summary>
        /// <typeparam name="T">Type of object returned.</typeparam>
        /// <param name="tableName">Name of the table to search.</param>
        /// <param name="key">The key, used to find the entity.</param>
        /// <returns>Task of type T.</returns>
        /// <inheritdoc cref="ITableStorage.GetEntity{T}" />
        public async Task <T> GetEntity <T>(string tableName, string key) where T : class, ITableItem, new()
        {
            try
            {
                var parts = GetKeySegments(key);
                var table = CloudTableClient.GetTableReference(tableName);

                // Load the DynamicTableEntity object from Storage using the keys.
                var operation = TableOperation.Retrieve(parts[0], parts[1]);
                var result    = await table.ExecuteAsync(operation);

                if (result.Result == null)
                {
                    return(null);
                }

                // Return the converted generic object.
                return(TableEntityConvert.FromTableEntity <T>(result.Result));
            }
            catch (Exception e)
            {
                Logger?.LogError(e, $"Error {e.Message} occurred retrieving, table name: {tableName}, key: {key}");
                throw;
            }
        }
Esempio n. 2
0
        public async Task UpsertEntity <T>(string tableName, T data) where T : class, ITableItem
        {
            try
            {
                // Convert POCO to ITableEntity object using TableEntityConvert.ToTableEntity()
                var tableEntity = TableEntityConvert.ToTableEntity(data);

                // Save the new or updated entity in the Storage
                var operation = TableOperation.InsertOrReplace(tableEntity);

                var table  = CloudTableClient.GetTableReference(tableName);
                var result = await table.ExecuteAsync(operation);

                // Getting the HTTP result to detect if a conflict has occurred when trying to upsert the file to allow the client to specifically deal with this.
                if (result.HttpStatusCode == (int)HttpStatusCode.PreconditionFailed)
                {
                    Logger?.LogWarning("Warning: Conflict error while upserting entity.");
                    throw new ConflictException("conflict while trying to upsert entity");
                }
            }
            catch (StorageException st)
                when(st.RequestInformation.HttpStatusCode == 400)
                {
                    Logger?.LogError($"Bad Request to table storage ({tableName}) - check modal properties are all set: {JsonConvert.SerializeObject(data)}");
                    throw new InvalidOperationException("Upsert data is badly formed and resulted in a 400 Bad Request response from TableStorage");
                }
            catch (Exception e)
            {
                Logger?.LogError(e, $"Error: {e.Message} occurred, table name: {tableName} with generic data");
                throw;
            }
        }
        public void Test_TableEntityConvert_ConvertFailure()
        {
            // Arrange
            object tableEntity = default(DynamicTableEntity);

            // Act/Assert
            Assert.Throws <ArgumentException>(() => TableEntityConvert.FromTableEntity <SampleEntity>(tableEntity));
        }
Esempio n. 4
0
        public async Task UpsertEntities <T>(string tableName, List <T> data, int batchSize = 100) where T : class, ITableItem
        {
            try
            {
                var table          = CloudTableClient.GetTableReference(tableName);
                var batchOperation = new TableBatchOperation();
                batchSize = batchSize > 100 ? 100 : batchSize;

                var lastUsedPartitionKey = string.Empty;

                for (int i = 0; i < data.Count; i++)
                {
                    var entry    = TableEntityConvert.ToTableEntity(data[i]);
                    var newBatch = (lastUsedPartitionKey != entry.PartitionKey && lastUsedPartitionKey.Length > 0);

                    if (newBatch)
                    {
                        await table.ExecuteBatchAsync(batchOperation);

                        batchOperation.Clear();
                        batchOperation.InsertOrReplace(entry);
                    }
                    else
                    {
                        batchOperation.InsertOrReplace(entry);

                        // Execute the batch operation if we reach our batch limit or its the end of the list.
                        if (batchOperation.Count >= batchSize || i == data.Count - 1)
                        {
                            await table.ExecuteBatchAsync(batchOperation);

                            batchOperation.Clear();
                        }
                    }

                    lastUsedPartitionKey = entry.PartitionKey;
                }

                if (batchOperation.Count > 0)
                {
                    await table.ExecuteBatchAsync(batchOperation);

                    batchOperation.Clear();
                }
            }
            catch (StorageException st)
                when(st.RequestInformation.HttpStatusCode == 400)
                {
                    Logger?.LogError($"Bad Request to table storage ({tableName}) - check modal properties are all set: {JsonConvert.SerializeObject(data)}");
                    throw new InvalidOperationException("Upsert data is badly formed and resulted in a 400 Bad Request response from TableStorage");
                }
            catch (Exception e)
            {
                Logger?.LogError(e, $"Error {e.Message} occurred upserting multiple, table name: {tableName} with generic data");
                throw;
            }
        }
Esempio n. 5
0
        public async Task AddOrUpdateCustomer(Customer customer)
        {
            // Convert POCO to ITableEntity object using TableEntityConvert.ToTableEntity()
            var tableEntity = TableEntityConvert.ToTableEntity(customer);

            // Save the new or updated entity in the Storage
            var operation = TableOperation.InsertOrReplace(tableEntity);
            await _cloudTable.ExecuteAsync(operation);
        }
Esempio n. 6
0
        public async Task <Customer> GetCustomer(string lastName, string firstName)
        {
            // Load the DynamicTableEntity object from Storage using the keys
            var operation = TableOperation.Retrieve(lastName, firstName);
            var result    = await _cloudTable.ExecuteAsync(operation);

            // Convert into the POCO using TableEntityConvert.FromTableEntity<T>()
            var customer = TableEntityConvert.FromTableEntity <Customer>(result.Result);

            return(customer);
        }
Esempio n. 7
0
        /// <summary>
        /// Internal list all the entities within a given table, using the supplied query as an observable.
        /// </summary>
        /// <typeparam name="T">Type of object returned.</typeparam>
        /// <param name="tableName">Name of the table to search.</param>
        /// <param name="tblQuery">The query to use when finding items.</param>
        /// <param name="token">Cancellation token source.</param>
        /// <returns>IObservable&lt;T&gt;.</returns>
        private IObservable <T> ListEntitiesObservable <T>(string tableName, TableQuery <DynamicTableEntity> tblQuery, CancellationTokenSource token)
            where T : class, ITableItem, new()
        {
            try
            {
                var table = CloudTableClient.GetTableReference(tableName);

                return(Observable.Create <T>(async obs =>
                {
                    TableContinuationToken continuationToken = null;

                    do
                    {
                        // Stop when cancellation requested.
                        if (token != null && token.IsCancellationRequested)
                        {
                            continuationToken = null;
                        }
                        else
                        {
                            var response = await table.ExecuteQuerySegmentedAsync(tblQuery, continuationToken, new TableRequestOptions
                            {
                                RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(5), 5)
                            }, null);

                            continuationToken = response.ContinuationToken;

                            // Raise the observable OnNext for each result to be processed.
                            foreach (var item in response.Results)
                            {
                                obs.OnNext(TableEntityConvert.FromTableEntity <T>(item));
                            }
                        }
                    } while (continuationToken != null);

                    obs.OnCompleted();
                }));
            }
            catch (Exception e)
            {
                Logger?.LogError(e, $"Error {e.Message} occurred listing entities, tablename: {tableName}");
                throw;
            }
        }