public async Task CreateDeleteTableAsync()
        {
            string storageUri        = StorageUri;
            string accountName       = StorageAccountName;
            string storageAccountKey = PrimaryStorageAccountKey;
            string tableName         = "OfficeSupplies1p2a";

            // Construct a new <see cref="TableServiceClient" /> using a <see cref="TableSharedKeyCredential" />.
            var serviceClient = new TableServiceClient(
                new Uri(storageUri),
                new TableSharedKeyCredential(accountName, storageAccountKey));

            #region Snippet:TablesSample1CreateTableAsync
            // Create a new table. The <see cref="TableItem" /> class stores properties of the created table.
            TableItem table = await serviceClient.CreateTableAsync(tableName);

            Console.WriteLine($"The created table's name is {table.Name}.");
            #endregion

            #region Snippet:TablesSample1DeleteTableAsync
            // Deletes the table made previously.
            await serviceClient.DeleteTableAsync(tableName);

            #endregion
        }
        public async Task GetTablesReturnsTablesWithFilter()
        {
            string             tableName = $"testtable{Recording.GenerateId()}";
            bool               doCleanup = false;
            TableServiceClient service   = CreateTableServiceClient();

            try
            {
                var createdTable = await service.CreateTableAsync(tableName).ConfigureAwait(false);

                Assert.That(() => createdTable.TableName, Is.EqualTo(tableName), $"Created table should be '{tableName}'");
                doCleanup = true;

                // Query with a filter.

                var tableResponses = (await service.GetTablesAsync(filter: $"TableName eq '{tableName}'").ToEnumerableAsync().ConfigureAwait(false)).ToList();

                Assert.That(() => tableResponses, Is.Not.Empty);
                Assert.That(() => tableResponses.Select(r => r.TableName), Contains.Item(tableName));
            }
            finally
            {
                if (doCleanup)
                {
                    await service.DeleteTableAsync(tableName);
                }
            }
        }
        public async Task GetTablesReturnsTables()
        {
            string             tableName = $"testtable{Recording.GenerateId()}";
            bool               doCleanup = false;
            TableServiceClient service   = CreateTableServiceClient();

            try
            {
                var createdTable = await service.CreateTableAsync(tableName).ConfigureAwait(false);

                Assert.That(() => createdTable.TableName, Is.EqualTo(tableName), $"Created table should be {tableName}");
                doCleanup = true;

                List <TableResponseProperties> tableResponses = new List <TableResponseProperties>();

                await foreach (var table in service.GetTablesAsync())
                {
                    tableResponses.Add(table);
                }

                Assert.That(() => tableResponses, Is.Not.Empty);
                Assert.That(() => tableResponses.Select(r => r.TableName), Contains.Item(tableName));
            }
            finally
            {
                if (doCleanup)
                {
                    await service.DeleteTableAsync(tableName);
                }
            }
        }
        public async Task QueryTablesAsync()
        {
            string storageUri        = StorageUri;
            string accountName       = StorageAccountName;
            string storageAccountKey = PrimaryStorageAccountKey;
            string tableName         = "OfficeSupplies3p2";

            var serviceClient = new TableServiceClient(
                new Uri(storageUri),
                new TableSharedKeyCredential(accountName, storageAccountKey));

            await serviceClient.CreateTableAsync(tableName);

            #region Snippet:TablesSample3QueryTablesAsync
            // Use the <see cref="TableServiceClient"> to query the service. Passing in OData filter strings is optional.
            AsyncPageable <TableItem> queryTableResults = serviceClient.GetTablesAsync(filter: $"TableName eq '{tableName}'");

            Console.WriteLine("The following are the names of the tables in the query result:");
            // Iterate the <see cref="Pageable"> in order to access individual queried tables.
            await foreach (TableItem table in queryTableResults)
            {
                Console.WriteLine(table.TableName);
            }
            #endregion

            await serviceClient.DeleteTableAsync(tableName);
        }
        public async Task UpdateUpsertEntitiesAsync()
        {
            string storageUri        = StorageUri;
            string accountName       = StorageAccountName;
            string storageAccountKey = PrimaryStorageAccountKey;
            string tableName         = "OfficeSupplies5p2" + _random.Next();
            string partitionKey      = "Stationery";
            string rowKey            = "A1";

            var serviceClient = new TableServiceClient(
                new Uri(storageUri),
                new TableSharedKeyCredential(accountName, storageAccountKey));

            await serviceClient.CreateTableAsync(tableName);

            var tableClient = serviceClient.GetTableClient(tableName);

            #region Snippet:TablesSample5UpsertEntityAsync
            var entity = new TableEntity(partitionKey, rowKey)
            {
                { "Product", "Markers" },
                { "Price", 5.00 },
                { "Brand", "myCompany" }
            };

            // Entity doesn't exist in table, so invoking UpsertEntity will simply insert the entity.
            await tableClient.UpsertEntityAsync(entity);

            #endregion

            #region Snippet:TablesSample5UpsertWithReplaceAsync
            // Delete an entity property.
            entity.Remove("Brand");

            // Entity does exist in the table, so invoking UpsertEntity will update using the given UpdateMode, which defaults to Merge if not given.
            // Since UpdateMode.Replace was passed, the existing entity will be replaced and delete the "Brand" property.
            await tableClient.UpsertEntityAsync(entity, TableUpdateMode.Replace);

            #endregion

            #region Snippet:TablesSample5UpdateEntityAsync
            // Get the entity to update.
            TableEntity qEntity = await tableClient.GetEntityAsync <TableEntity>(partitionKey, rowKey);

            qEntity["Price"] = 7.00;

            // Since no UpdateMode was passed, the request will default to Merge.
            await tableClient.UpdateEntityAsync(qEntity, qEntity.ETag);

            TableEntity updatedEntity = await tableClient.GetEntityAsync <TableEntity>(partitionKey, rowKey);

            Console.WriteLine($"'Price' before updating: ${entity.GetDouble("Price")}");
            Console.WriteLine($"'Price' after updating: ${updatedEntity.GetDouble("Price")}");
            #endregion

            await serviceClient.DeleteTableAsync(tableName);
        }
Beispiel #6
0
        public async Task CreateTableAsync_RequiredArgsOnly_CreatesTable()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = GenerateSampleTableName();

            await client.CreateTableAsync(tableName);

            AssertTableExists(tableName);
        }
Beispiel #7
0
        public async Task CreateTableAsync_TableAlreadyExists_ReportsConflict()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = GenerateSampleTableName();

            CreateTable(tableName);

            await client.CreateTableAsync(tableName);

            // expects exception
        }
Beispiel #8
0
        public async Task EntitiyCanBeUpserted()
        {
            string             tableName         = $"testtable{Recording.GenerateId()}";
            const string       partitionKeyValue = "somPartition";
            const string       rowKeyValue       = "1";
            const string       propertyName      = "SomeStringProperty";
            const string       originalValue     = "This is the original";
            const string       updatedValue      = "This is new and improved!";
            bool               doCleanup         = false;
            TableServiceClient service           = CreateTableServiceClient();

            try
            {
                var createdTable = await service.CreateTableAsync(tableName).ConfigureAwait(false);

                TableClient client = InstrumentClient(service.GetTableClient(tableName));
                var         entity = new Dictionary <string, object>
                {
                    { "PartitionKey", partitionKeyValue },
                    { "RowKey", rowKeyValue },
                    { propertyName, originalValue }
                };

                // Insert the new entity.

                await client.UpsertAsync(entity).ConfigureAwait(false);

                // Fetch the created entity from the service.

                var entityToUpdate = (await client.QueryAsync(filter: $"PartitionKey eq '{partitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();

                entityToUpdate[propertyName] = updatedValue;
                await client.UpsertAsync(entityToUpdate).ConfigureAwait(false);

                // Fetch the updated entity from the service.

                var updatedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{partitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();

                Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}");
            }
            finally
            {
                if (doCleanup)
                {
                    await service.DeleteTableAsync(tableName);
                }
            }
        }
Beispiel #9
0
        public async Task InsertedEntitiesCanBeQueriedWithAndWithoutPagination(int?pageCount)
        {
            string             tableName         = $"testtable{Recording.GenerateId()}";
            const string       partitionKeyValue = "somPartition";
            bool               doCleanup         = false;
            TableServiceClient service           = CreateTableServiceClient();
            List <IDictionary <string, object> > entityResults = new List <IDictionary <string, object> >();

            try
            {
                var createdTable = await service.CreateTableAsync(tableName).ConfigureAwait(false);

                TableClient client = InstrumentClient(service.GetTableClient(tableName));
                List <Dictionary <string, object> > entitiesToInsert = CreateTableEntities(partitionKeyValue, 20);

                // Insert the new entities.

                foreach (var entity in entitiesToInsert)
                {
                    await client.InsertAsync(entity).ConfigureAwait(false);
                }

                // Query the entities.

                entityResults = (await client.QueryAsync(top: pageCount).ToEnumerableAsync().ConfigureAwait(false)).ToList();

                Assert.That(entityResults.Count, Is.EqualTo(entitiesToInsert.Count), "The entity result count should match the inserted count");
                entityResults.Clear();
            }
            finally
            {
                if (doCleanup)
                {
                    await service.DeleteTableAsync(tableName);
                }
            }
        }
Beispiel #10
0
        public async Task InsertedEntitiesCanBeQueriedWithFilters()
        {
            string             tableName         = $"testtable{Recording.GenerateId()}";
            const string       partitionKeyValue = "somPartition";
            bool               doCleanup         = false;
            TableServiceClient service           = CreateTableServiceClient();
            List <IDictionary <string, object> > entityResults = new List <IDictionary <string, object> >();

            try
            {
                var createdTable = await service.CreateTableAsync(tableName).ConfigureAwait(false);

                TableClient client = InstrumentClient(service.GetTableClient(tableName));
                List <Dictionary <string, object> > entitiesToInsert = CreateTableEntities(partitionKeyValue, 20);

                // Insert the new entities.

                foreach (var entity in entitiesToInsert)
                {
                    await client.InsertAsync(entity).ConfigureAwait(false);
                }

                // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'.

                entityResults = (await client.QueryAsync(filter: $"PartitionKey eq '{partitionKeyValue}' and RowKey gt '10'").ToEnumerableAsync().ConfigureAwait(false)).ToList();

                Assert.That(entityResults.Count, Is.EqualTo(10), "The entity result count should be 10");
            }
            finally
            {
                if (doCleanup)
                {
                    await service.DeleteTableAsync(tableName);
                }
            }
        }
        public async Task QueryEntitiesAsync()
        {
            string storageUri        = StorageUri;
            string accountName       = StorageAccountName;
            string storageAccountKey = PrimaryStorageAccountKey;
            string tableName         = "OfficeSupplies4p2" + _random.Next();
            string partitionKey      = "somePartition";
            string rowKey            = "1";
            string rowKey2           = "2";

            var serviceClient = new TableServiceClient(
                new Uri(storageUri),
                new TableSharedKeyCredential(accountName, storageAccountKey));

            await serviceClient.CreateTableAsync(tableName);

            var tableClient = serviceClient.GetTableClient(tableName);

            var entity = new TableEntity(partitionKey, rowKey)
            {
                { "Product", "Markers" },
                { "Price", 5.00 },
            };
            await tableClient.AddEntityAsync(entity);

            var entity2 = new TableEntity(partitionKey, rowKey2)
            {
                { "Product", "Chair" },
                { "Price", 7.00 },
            };
            await tableClient.AddEntityAsync(entity2);

            #region Snippet:TablesSample4QueryEntitiesAsync
            // Use the <see cref="TableClient"> to query the table. Passing in OData filter strings is optional.
            AsyncPageable <TableEntity> queryResults = tableClient.QueryAsync <TableEntity>(filter: $"PartitionKey eq '{partitionKey}'");
            int count = 0;

            // Iterate the list in order to access individual queried entities.
            await foreach (TableEntity qEntity in queryResults)
            {
                Console.WriteLine($"{qEntity.GetString("Product")}: {qEntity.GetDouble("Price")}");
                count++;
            }

            Console.WriteLine($"The query returned {count} entities.");
            #endregion

            #region Snippet:TablesSample4QueryEntitiesExpressionAsync
            // Use the <see cref="TableClient"> to query the table using a filter expression.
            double priceCutOff = 6.00;
            AsyncPageable <OfficeSupplyEntity> queryResultsLINQ = tableClient.QueryAsync <OfficeSupplyEntity>(ent => ent.Price >= priceCutOff);
            #endregion

            #region Snippet:TablesSample4QueryEntitiesSelectAsync
            AsyncPageable <TableEntity> queryResultsSelect = tableClient.QueryAsync <TableEntity>(select: new List <string>()
            {
                "Product", "Price"
            });
            #endregion

            #region Snippet:TablesSample4QueryEntitiesMaxPerPageAsync
            AsyncPageable <TableEntity> queryResultsMaxPerPage = tableClient.QueryAsync <TableEntity>(maxPerPage: 10);

            // Iterate the <see cref="Pageable"> by page.
            await foreach (Page <TableEntity> page in queryResultsMaxPerPage.AsPages())
            {
                Console.WriteLine("This is a new page!");
                foreach (TableEntity qEntity in page.Values)
                {
                    Console.WriteLine($"# of {qEntity.GetString("Product")} inventoried: {qEntity.GetInt32("Quantity")}");
                }
            }
            #endregion

            await serviceClient.DeleteTableAsync(tableName);
        }
Beispiel #12
0
        public async Task EntityDeleteRespectsEtag()
        {
            string             tableName         = $"testtable{Recording.GenerateId()}";
            const string       partitionKeyValue = "somPartition";
            const string       rowKeyValue       = "1";
            const string       propertyName      = "SomeStringProperty";
            const string       originalValue     = "This is the original";
            bool               doCleanup         = false;
            TableServiceClient service           = CreateTableServiceClient();

            try
            {
                var createdTable = await service.CreateTableAsync(tableName).ConfigureAwait(false);

                TableClient client = InstrumentClient(service.GetTableClient(tableName));
                var         entity = new Dictionary <string, object>
                {
                    { "PartitionKey", partitionKeyValue },
                    { "RowKey", rowKeyValue },
                    { propertyName, originalValue }
                };

                // Insert the new entity.

                await client.UpsertAsync(entity).ConfigureAwait(false);

                // Fetch the created entity from the service.

                var originalEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{partitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
                var staleEtag      = originalEntity[TableConstants.PropertyNames.Etag] as string;

                // Use a wildcard ETag to delete unconditionally.

                await client.DeleteAsync(partitionKeyValue, rowKeyValue).ConfigureAwait(false);

                // Validate that the entity is deleted.

                var emptyresult = (await client.QueryAsync(filter: $"PartitionKey eq '{partitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false));

                Assert.That(emptyresult, Is.Empty, $"The query should have returned no results.");

                // Insert the new entity again.

                await client.UpsertAsync(entity).ConfigureAwait(false);

                // Fetch the created entity from the service.

                originalEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{partitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();

                // Use a non-matching ETag.

                Assert.That(async() => await client.DeleteAsync(partitionKeyValue, rowKeyValue, staleEtag).ConfigureAwait(false), Throws.InstanceOf <RequestFailedException>());

                // Use a matching ETag.

                await client.DeleteAsync(partitionKeyValue, rowKeyValue, originalEntity[TableConstants.PropertyNames.Etag] as string).ConfigureAwait(false);

                // Validate that the entity is deleted.

                emptyresult = (await client.QueryAsync(filter: $"PartitionKey eq '{partitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false));

                Assert.That(emptyresult, Is.Empty, $"The query should have returned no results.");
            }
            finally
            {
                if (doCleanup)
                {
                    await service.DeleteTableAsync(tableName);
                }
            }
        }
Beispiel #13
0
        public async Task EntityMergeDoesPartialPropertyUpdates()
        {
            string             tableName         = $"testtable{Recording.GenerateId()}";
            const string       partitionKeyValue = "somPartition";
            const string       rowKeyValue       = "1";
            const string       propertyName      = "SomeStringProperty";
            const string       mergepropertyName = "MergedProperty";
            const string       originalValue     = "This is the original";
            const string       mergeValue        = "This was merged!";
            const string       mergeUpdatedValue = "merged value was updated!";
            bool               doCleanup         = false;
            TableServiceClient service           = CreateTableServiceClient();

            try
            {
                var createdTable = await service.CreateTableAsync(tableName).ConfigureAwait(false);

                TableClient client = InstrumentClient(service.GetTableClient(tableName));
                var         entity = new Dictionary <string, object>
                {
                    { "PartitionKey", partitionKeyValue },
                    { "RowKey", rowKeyValue },
                    { propertyName, originalValue }
                };
                var partialEntity = new Dictionary <string, object>
                {
                    { "PartitionKey", partitionKeyValue },
                    { "RowKey", rowKeyValue },
                    { mergepropertyName, mergeValue }
                };


                // Insert the new entity.

                await client.UpsertAsync(entity).ConfigureAwait(false);

                // Fetch the created entity from the service.

                var originalEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{partitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();

                // Verify that the merge property does not yet exist yet and that the original property does exist.

                Assert.That(originalEntity.TryGetValue(mergepropertyName, out var _), Is.False);
                Assert.That(originalEntity[propertyName], Is.EqualTo(originalValue));

                // Do not provide an ETag to update unconditionally.

                await client.MergeAsync(partialEntity).ConfigureAwait(false);

                // Fetch the updated entity from the service.

                var mergedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{partitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();

                // Verify that the merge property does not yet exist yet and that the original property does exist.

                Assert.That(mergedEntity[mergepropertyName], Is.EqualTo(mergeValue));
                Assert.That(mergedEntity[propertyName], Is.EqualTo(originalValue));

                // Update just the merged value.

                partialEntity[mergepropertyName] = mergeUpdatedValue;
                await client.MergeAsync(partialEntity).ConfigureAwait(false);

                // Fetch the updated entity from the service.

                mergedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{partitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();

                // Verify that the merge property does not yet exist yet and that the original property does exist.

                Assert.That(mergedEntity[mergepropertyName], Is.EqualTo(mergeUpdatedValue));
                Assert.That(mergedEntity[propertyName], Is.EqualTo(originalValue));
            }
            finally
            {
                if (doCleanup)
                {
                    await service.DeleteTableAsync(tableName);
                }
            }
        }
        public async Task CreateTableAsync_TableAlreadyExists_ReportsConflict()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = GenerateSampleTableName();
            CreateTable(tableName);

            await client.CreateTableAsync(tableName);

            // expects exception
        }
        public async Task CreateTableAsync_RequiredArgsOnly_CreatesTable()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = GenerateSampleTableName();

            await client.CreateTableAsync(tableName);

            AssertTableExists(tableName);
        }
        public async Task QueryEntitiesAsync()
        {
            string storageUri        = StorageUri;
            string accountName       = StorageAccountName;
            string storageAccountKey = PrimaryStorageAccountKey;
            string tableName         = "OfficeSupplies4p2";
            string partitionKey      = "somePartition";
            string rowKey            = "1";
            string rowKey2           = "2";

            var serviceClient = new TableServiceClient(
                new Uri(storageUri),
                new TableSharedKeyCredential(accountName, storageAccountKey));

            await serviceClient.CreateTableAsync(tableName);

            var client = serviceClient.GetTableClient(tableName);

            var entity = new TableEntity(partitionKey, rowKey)
            {
                { "Product", "Markers" },
                { "Price", 5.00 },
            };
            await client.CreateEntityAsync(entity);

            var entity2 = new TableEntity(partitionKey, rowKey2)
            {
                { "Product", "Chair" },
                { "Price", 7.00 },
            };
            await client.CreateEntityAsync(entity2);

            #region Snippet:TablesSample4QueryEntitiesAsync
            // Use the <see cref="TableClient"> to query the table. Passing in OData filter strings is optional.
            AsyncPageable <TableEntity> queryResults = client.QueryAsync <TableEntity>(filter: $"PartitionKey eq '{partitionKey}'");
            int count = 0;

            // Iterate the list in order to access individual queried entities.
            await foreach (TableEntity qEntity in queryResults)
            {
                Console.WriteLine($"{qEntity.GetString("Product")}: {qEntity.GetDouble("Price")}");
                count++;
            }

            Console.WriteLine($"The query returned {count} entities.");
            #endregion

            #region Snippet:TablesSample4QueryEntitiesExpressionTreeAsync
            // Use the <see cref="TableClient"> to query the table and pass in expression tree.
            double priceCutOff = 6.00;
            AsyncPageable <OfficeSupplyEntity> queryResultsLINQ = client.QueryAsync <OfficeSupplyEntity>(ent => ent.Price >= priceCutOff);
            count = 0;

            // Iterate the <see cref="Pageable"> in order to access individual queried entities.
            await foreach (OfficeSupplyEntity qEntity in queryResultsLINQ)
            {
                Console.WriteLine($"{qEntity.Product}: ${qEntity.Price}");
                count++;
            }

            Console.WriteLine($"The LINQ query returned {count} entities.");
            #endregion
            await serviceClient.DeleteTableAsync(tableName);
        }
        public async Task UpdateUpsertEntitiesAsync()
        {
            string storageUri        = StorageUri;
            string accountName       = StorageAccountName;
            string storageAccountKey = PrimaryStorageAccountKey;
            string tableName         = "OfficeSupplies5p2";
            string partitionKey      = "somePartition";
            string rowKey            = "A1";

            var serviceClient = new TableServiceClient(
                new Uri(storageUri),
                new TableSharedKeyCredential(accountName, storageAccountKey));

            await serviceClient.CreateTableAsync(tableName);

            #region Snippet:TablesSample5UpsertEntityAsync
            // Get the <see cref="TableClient" /> of the table.
            var client = serviceClient.GetTableClient(tableName);

            // Make an entity.
            var entity = new TableEntity(partitionKey, rowKey)
            {
                { "Product", "Markers" },
                { "Price", 5.00 },
                { "Brand", "myCompany" }
            };

            // Entity doesn't exist in table, so invoking UpsertEntity will simply insert the entity.
            await client.UpsertEntityAsync(entity);

            // Delete an entity property.
            entity.Remove("Brand");

            // Entity does exist in the table, so invoking UpsertEntity will update using the given UpdateMode (which defaults to Merge if not given).
            // Since UpdateMode.Replace was passed, the existing entity will be replaced and delete the "Brand" property.
            await client.UpsertEntityAsync(entity, TableUpdateMode.Replace);

            #endregion


            #region Snippet:TablesSample5UpdateEntityAsync
            // Query for entities to update.
            AsyncPageable <TableEntity> queryResultsBefore = client.QueryAsync <TableEntity>();

            await foreach (TableEntity qEntity in queryResultsBefore)
            {
                // Changing property of entity.
                qEntity["Price"] = 7.00;

                // Updating to changed entity using its generated eTag.
                // Since no UpdateMode was passed, the request will default to Merge.
                await client.UpdateEntityAsync(qEntity, qEntity.ETag);
            }
            #endregion

            AsyncPageable <TableEntity> queryResultsAfter = client.QueryAsync <TableEntity>();
            await foreach (TableEntity qEntity in queryResultsAfter)
            {
                Console.WriteLine($"'Price' before updating: ${entity.GetDouble("Price")}");
                Console.WriteLine($"'Price' after updating: ${qEntity.GetDouble("Price")}");
            }

            await serviceClient.DeleteTableAsync(tableName);
        }
Beispiel #18
0
        public async Task EntityMergeRespectsEtag()
        {
            string             tableName         = $"testtable{Recording.GenerateId()}";
            const string       partitionKeyValue = "somPartition";
            const string       rowKeyValue       = "1";
            const string       propertyName      = "SomeStringProperty";
            const string       originalValue     = "This is the original";
            const string       updatedValue      = "This is new and improved!";
            const string       updatedValue2     = "This changed due to a matching Etag";
            bool               doCleanup         = false;
            TableServiceClient service           = CreateTableServiceClient();

            try
            {
                var createdTable = await service.CreateTableAsync(tableName).ConfigureAwait(false);

                TableClient client = InstrumentClient(service.GetTableClient(tableName));
                var         entity = new Dictionary <string, object>
                {
                    { "PartitionKey", partitionKeyValue },
                    { "RowKey", rowKeyValue },
                    { propertyName, originalValue }
                };

                // Insert the new entity.

                await client.UpsertAsync(entity).ConfigureAwait(false);

                // Fetch the created entity from the service.

                var originalEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{partitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();
                originalEntity[propertyName] = updatedValue;

                // Use a wildcard ETag to update unconditionally.

                await client.MergeAsync(originalEntity, "*").ConfigureAwait(false);

                // Fetch the updated entity from the service.

                var updatedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{partitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();

                Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}");

                updatedEntity[propertyName] = updatedValue2;

                // Use a non-matching ETag.

                Assert.That(async() => await client.MergeAsync(updatedEntity, originalEntity[TableConstants.PropertyNames.Etag] as string).ConfigureAwait(false), Throws.InstanceOf <RequestFailedException>());

                // Use a matching ETag.

                await client.MergeAsync(updatedEntity, updatedEntity[TableConstants.PropertyNames.Etag] as string).ConfigureAwait(false);

                // Fetch the newly updated entity from the service.

                updatedEntity = (await client.QueryAsync(filter: $"PartitionKey eq '{partitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single();

                Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue2), $"The property value should be {updatedValue2}");
            }
            finally
            {
                if (doCleanup)
                {
                    await service.DeleteTableAsync(tableName);
                }
            }
        }
        public async Task TransactionalBatchAsync()
        {
            string storageUri        = StorageUri;
            string accountName       = StorageAccountName;
            string storageAccountKey = PrimaryStorageAccountKey;
            string tableName         = "OfficeSuppliesBatch";
            string partitionKey      = "BatchInsertSample";

            var serviceClient = new TableServiceClient(
                new Uri(storageUri),
                new TableSharedKeyCredential(accountName, storageAccountKey));

            await serviceClient.CreateTableAsync(tableName);

            TableClient client = serviceClient.GetTableClient(tableName);

            #region Snippet:BatchAdd

            // Create a list of 5 entities with the same partition key.
#if SNIPPET
            string partitionKey = "BatchInsertSample";
#endif
            List <TableEntity> entityList = new List <TableEntity>
            {
                new TableEntity(partitionKey, "01")
                {
                    { "Product", "Marker" },
                    { "Price", 5.00 },
                    { "Brand", "Premium" }
                },
                new TableEntity(partitionKey, "02")
                {
                    { "Product", "Pen" },
                    { "Price", 3.00 },
                    { "Brand", "Premium" }
                },
                new TableEntity(partitionKey, "03")
                {
                    { "Product", "Paper" },
                    { "Price", 0.10 },
                    { "Brand", "Premium" }
                },
                new TableEntity(partitionKey, "04")
                {
                    { "Product", "Glue" },
                    { "Price", 1.00 },
                    { "Brand", "Generic" }
                },
            };

            // Create the batch.
            List <TableTransactionAction> addEntitiesBatch = new List <TableTransactionAction>();

            // Add the entities to be added to the batch.
            addEntitiesBatch.AddRange(entityList.Select(e => new TableTransactionAction(TableTransactionActionType.Add, e)));

            // Submit the batch.
            Response <IReadOnlyList <Response> > response = await client.SubmitTransactionAsync(addEntitiesBatch).ConfigureAwait(false);

            for (int i = 0; i < entityList.Count; i++)
            {
                Console.WriteLine($"The ETag for the entity with RowKey: '{entityList[i].RowKey}' is {response.Value[i].Headers.ETag}");
            }

            #endregion

            #region Snippet:BatchMixed

            // Create a new batch.
            List <TableTransactionAction> mixedBatch = new List <TableTransactionAction>();

            // Add an entity for deletion to the batch.
            mixedBatch.Add(new TableTransactionAction(TableTransactionActionType.Delete, entityList[0]));

            // Remove this entity from our list so that we can track that it will no longer be in the table.
            entityList.RemoveAt(0);

            // Change only the price of the entity with a RoyKey equal to "02".
            TableEntity mergeEntity = new TableEntity(partitionKey, "02")
            {
                { "Price", 3.50 },
            };

            // Add a merge operation to the batch.
            // We specify an ETag value of ETag.All to indicate that this merge should be unconditional.
            mixedBatch.Add(new TableTransactionAction(TableTransactionActionType.UpdateMerge, mergeEntity, ETag.All));

            // Update a property on an entity.
            TableEntity updateEntity = entityList[2];
            updateEntity["Brand"] = "Generic";

            // Add an upsert operation to the batch.
            // Using the UpsertEntity method allows us to implicitly ignore the ETag value.
            mixedBatch.Add(new TableTransactionAction(TableTransactionActionType.UpsertReplace, updateEntity));

            // Submit the batch.
            await client.SubmitTransactionAsync(mixedBatch).ConfigureAwait(false);

            #endregion

            #region Snippet:BatchDelete

            // Create a new batch.
            List <TableTransactionAction> deleteEntitiesBatch = new List <TableTransactionAction>();

            // Add the entities for deletion to the batch.
            foreach (TableEntity entity in entityList)
            {
                deleteEntitiesBatch.Add(new TableTransactionAction(TableTransactionActionType.Delete, entity));
            }

            // Submit the batch.
            await client.SubmitTransactionAsync(deleteEntitiesBatch).ConfigureAwait(false);

            #endregion

            // Delete the table.
            await client.DeleteAsync();
        }
        public async Task CreateDeleteEntitiesAsync()
        {
            string storageUri        = StorageUri;
            string accountName       = StorageAccountName;
            string storageAccountKey = PrimaryStorageAccountKey;
            string tableName         = "OfficeSupplies2p2";
            string partitionKey      = "somePartition";
            string rowKey            = "A1";
            string rowKeyStrong      = "B1";

            var serviceClient = new TableServiceClient(
                new Uri(storageUri),
                new TableSharedKeyCredential(accountName, storageAccountKey));

            await serviceClient.CreateTableAsync(tableName);

            try
            {
                // Get a reference to the <see cref="TableClient" /> of the table.
                var client = serviceClient.GetTableClient(tableName);

                #region Snippet:TablesSample2CreateEntityAsync
                // Make an entity by defining a <see cref="Dictionary"> that includes the partition and row key.
                var entity = new Dictionary <string, object>
                {
                    { "PartitionKey", partitionKey },
                    { "RowKey", rowKey },
                    { "Product", "Markers" },
                    { "Price", 5.00 },
                };

                // Insert the newly created entity.
                await client.CreateEntityAsync(entity);

                #endregion

                #region Snippet:TablesSample2CreateStronglyTypedEntityAsync
                // Make a strongly typed entity by defining a custom class that extends <see cref="TableEntity">.
                var strongEntity = new OfficeSupplyEntity
                {
                    PartitionKey = partitionKey,
                    RowKey       = rowKeyStrong,
                    Product      = "Notebook",
                    Price        = 3.00
                };

                // Insert the newly created entity.
                await client.CreateEntityAsync(strongEntity);

                #endregion

                #region Snippet:TablesSample2DeleteEntityAsync
                // Delete the entity given the partition and row key.
                await client.DeleteEntityAsync(partitionKey, rowKey);

                #endregion
            }
            finally
            {
                await serviceClient.DeleteTableAsync(tableName);
            }
        }