コード例 #1
0
        public async Task CreateIfNotExists()
        {
            // Call CreateIfNotExists when the table already exists.
            Assert.That(async() => await CosmosThrottleWrapper(async() => await client.CreateIfNotExistsAsync().ConfigureAwait(false)), Throws.Nothing);

            // Call CreateIfNotExists when the table does not already exist.
            var         newTableName = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true);
            TableItem   table;
            TableClient tableClient = null;

            try
            {
                tableClient = service.GetTableClient(newTableName);
                table       = await CosmosThrottleWrapper(async() => await tableClient.CreateIfNotExistsAsync().ConfigureAwait(false));
            }
            finally
            {
                await tableClient.DeleteAsync().ConfigureAwait(false);
            }

            Assert.That(table.TableName, Is.EqualTo(newTableName));
        }
        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";

            #region Snippet:TablesSample2CreateTableClientAsync
            // Construct a new <see cref="TableClient" /> using a <see cref="TableSharedKeyCredential" />.
            var client = new TableClient(
                tableName,
                new Uri(storageUri),
                new TableSharedKeyCredential(accountName, storageAccountKey));

            // Create the table in the service.
            await client.CreateAsync();

            #endregion

            #region Snippet:TablesSample2CreateEntityAsync
            // Make an entity by defining a <see cref="Dictionary"> that includes the partition and row key.
            var entity = new TableEntity(partitionKey, 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

            #region Snippet:TablesSample2DeleteTableWithTableClientAsync
            await client.DeleteAsync();

            #endregion
        }
        public async Task CreateDeleteEntitiesAsync()
        {
            string storageUri        = StorageUri;
            string accountName       = StorageAccountName;
            string storageAccountKey = PrimaryStorageAccountKey;
            string tableName         = "OfficeSupplies2p2";
            string partitionKey      = "Stationery";
            string rowKey            = "A1";
            string rowKeyStrong      = "B1";

            #region Snippet:TablesSample2CreateTableClientAsync
            // Construct a new <see cref="TableClient" /> using a <see cref="TableSharedKeyCredential" />.
            var client = new TableClient(
                new Uri(storageUri),
                tableName,
                new TableSharedKeyCredential(accountName, storageAccountKey));

            // Create the table in the service.
            await client.CreateAsync();

            #endregion

            #region Snippet:TablesSample2CreateEntityAsync
            // Make a dictionary entity by defining a <see cref="TableEntity">.
            var entity = new TableEntity(partitionKey, rowKey)
            {
                { "Product", "Marker Set" },
                { "Price", 5.00 },
                { "Quantity", 21 }
            };

            Console.WriteLine($"{entity.RowKey}: {entity["Product"]} costs ${entity.GetDouble("Price")}.");
            #endregion

            #region Snippet:TablesSample2AddEntityAsync
            // Insert the newly created entity.
            await client.AddEntityAsync(entity);

            #endregion

            #region Snippet:TablesSample2CreateStronglyTypedEntityAsync
            // Create an instance of the strongly-typed entity and set their properties.
            var strongEntity = new OfficeSupplyEntity
            {
                PartitionKey = partitionKey,
                RowKey       = rowKeyStrong,
                Product      = "Notebook",
                Price        = 3.00,
                Quantity     = 50
            };

            Console.WriteLine($"{entity.RowKey}: {strongEntity.Product} costs ${strongEntity.Price}.");
            #endregion

            // Add the newly created entity.
            await client.AddEntityAsync(strongEntity);

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

            #endregion

            #region Snippet:TablesSample2DeleteTableWithTableClientAsync
            await client.DeleteAsync();

            #endregion
        }
コード例 #5
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);
                }
            }
        }
コード例 #6
0
 public static async Task Delete(string account, string key, string tableName)
 {
     TableClient table = new TableClient(Client.GetConnectionString(account, key), tableName);
     await table.DeleteAsync();
 }
コード例 #7
0
 /// <summary>
 /// Delete the table
 /// </summary>
 public Task DeleteTableAsync()
 {
     return(CloudTable.DeleteAsync());
 }