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 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
        }
示例#3
0
        /// <summary>
        /// Connects to, or creates and initializes a new Azure table if it does not already exist.
        /// </summary>
        /// <returns>Completion promise for this operation.</returns>
        public async Task InitTableAsync()
        {
            const string operation = "InitTable";
            var          startTime = DateTime.UtcNow;

            try
            {
                TableServiceClient tableCreationClient = await GetCloudTableCreationClientAsync();

                var table     = tableCreationClient.GetTableClient(TableName);
                var tableItem = await table.CreateIfNotExistsAsync();

                var didCreate = tableItem is not null;

                Logger.Info((int)Utilities.ErrorCode.AzureTable_01, "{0} Azure storage table {1}", (didCreate ? "Created" : "Attached to"), TableName);

                Table = table;
            }
            catch (TimeoutException te)
            {
                var errorMsg = $"Unable to create or connect to the Azure table in {this.StoragePolicyOptions.CreationTimeout}";
                this.Logger.Error((int)Utilities.ErrorCode.AzureTable_TableNotCreated, errorMsg, te);
                throw new OrleansException(errorMsg, te);
            }
            catch (Exception exc)
            {
                Logger.Error((int)Utilities.ErrorCode.AzureTable_02, $"Could not initialize connection to storage table {TableName}", exc);
                throw;
            }
            finally
            {
                CheckAlertSlowAccess(startTime, operation);
            }
        }
示例#4
0
        public void QueryTables()
        {
            string storageUri        = StorageUri;
            string accountName       = StorageAccountName;
            string storageAccountKey = PrimaryStorageAccountKey;
            string tableName         = "OfficeSupplies3p1";

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

            serviceClient.CreateTable(tableName);

            #region Snippet:TablesSample3QueryTables
            // Use the <see cref="TableServiceClient"> to query the service. Passing in OData filter strings is optional.

            Pageable <TableItem> queryTableResults = serviceClient.GetTables(filter: $"TableName eq '{tableName}'");

            Console.WriteLine("The following are the names of the tables in the query results:");

            // Iterate the <see cref="Pageable"> in order to access queried tables.

            foreach (TableItem table in queryTableResults)
            {
                Console.WriteLine(table.Name);
            }
            #endregion

            serviceClient.DeleteTable(tableName);
        }
        /// <inheritdoc />
        public async Task InitializeDataStoreAsync(TableServiceClient tableServiceClient)
        {
            EnsureArg.IsNotNull(tableServiceClient, nameof(tableServiceClient));

            try
            {
                _logger.LogInformation("Initializing Table Storage and tables");
                foreach (string tableName in Constants.AllTables)
                {
                    if (await tableServiceClient.CreateTableIfNotExistsAsync(tableName) != null)
                    {
                        _logger.LogInformation("Created Table named '{TableName}'", tableName);
                    }
                    else
                    {
                        _logger.LogInformation("Table '{TableName}' already exists", tableName);
                    }
                }

                _logger.LogInformation("Table Storage and tables successfully initialized");
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, "Table Storage and table initialization failed");
                throw;
            }
        }
        public void TableCreateError()
        {
            string storageUri        = StorageUri;
            string accountName       = AccountName;
            string storageAccountKey = PrimaryStorageAccountKey;
            string tableName         = "OfficeSupplies2";

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

            #region Snippet:TablesSample1CreateExistingTable
            try
            {
                // Creates a table.
                serviceClient.CreateTable(tableName);

                // Second attempt to create table with the same name should throw exception.
                serviceClient.CreateTable(tableName);
            }
            catch (RequestFailedException e)
            {
                Console.WriteLine("Create existing table throws the following exception:");
                Console.WriteLine(e.Message);
            }
            #endregion
            finally
            {
                serviceClient.DeleteTable(tableName);
            }
        }
示例#7
0
        public void CreateDeleteTable()
        {
            string storageUri        = StorageUri;
            string accountName       = StorageAccountName;
            string storageAccountKey = PrimaryStorageAccountKey;
            string tableName         = "OfficeSupplies1p1";

            #region Snippet:TablesSample1CreateClient
            // Construct a new <see cref="TableServiceClient" /> using a <see cref="TableSharedKeyCredential" />.

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

            #region Snippet:TablesSample1CreateTable
            // Create a new table. The <see cref="TableItem" /> class stores properties of the created table.
#if SNIPPET
            string tableName = "OfficeSupplies1p1";
#endif
            TableItem table = serviceClient.CreateTable(tableName);
            Console.WriteLine($"The created table's name is {table.Name}.");
            #endregion

            #region Snippet:TablesSample1DeleteTable
            // Deletes the table made previously.
#if SNIPPET
            string tableName = "OfficeSupplies1p1";
#endif
            serviceClient.DeleteTable(tableName);
            #endregion

            #region Snippet:TablesSample1GetTableClient
#if SNIPPET
            string tableName = "OfficeSupplies1p2";
#else
            tableName = "OfficeSupplies1p2";
#endif
            var tableClient = serviceClient.GetTableClient(tableName);
            #endregion

            #region Snippet:TablesSample1CreateTableClient
#if SNIPPET
            var tableClient = new TableClient(
#else
            tableClient = new TableClient(
#endif
                new Uri(storageUri),
                tableName,
                new TableSharedKeyCredential(accountName, storageAccountKey));
            #endregion

            #region Snippet:TablesSample1TableClientCreateTable
            tableClient.Create();
            #endregion

            #region Snippet:TablesSample1TableClientDeleteTable
            tableClient.Delete();
                               #endregion
        }
示例#8
0
        public async Task SasAuth()
        {
            string storageUri  = StorageUri;
            string accountName = StorageAccountName;
            string accountKey  = PrimaryStorageAccountKey;
            string tableName   = "OfficeSupplies";

            #region Snippet:TablesAuthSas
            // Construct a new <see cref="TableServiceClient" /> using a <see cref="TableSharedKeyCredential" />.

            var credential = new TableSharedKeyCredential(accountName, accountKey);

            var serviceClient = new TableServiceClient(
                new Uri(storageUri),
                credential);

            // Build a shared access signature with the Write and Delete permissions and access to all service resource types.

            TableAccountSasBuilder sasWriteDelete = serviceClient.GetSasBuilder(TableAccountSasPermissions.Write | TableAccountSasPermissions.Delete, TableAccountSasResourceTypes.All, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc));
            string tokenWriteDelete = sasWriteDelete.Sign(credential);

            // Create the TableServiceClients using the SAS URIs.

            var serviceClientWithSas = new TableServiceClient(new Uri(storageUri), new AzureSasCredential(tokenWriteDelete));

            // Validate that we are able to create a table using the SAS URI with Write and Delete permissions.

            await serviceClientWithSas.CreateTableIfNotExistsAsync(tableName);

            // Validate that we are able to delete a table using the SAS URI with Write and Delete permissions.

            await serviceClientWithSas.DeleteTableAsync(tableName);

            #endregion
        }
示例#9
0
 public AzureStorage(string connectionString)
 {
     blobServiceClient  = new BlobServiceClient(connectionString);
     queueServiceClient = new QueueServiceClient(connectionString);
     tableServiceClient = new TableServiceClient(connectionString);
     //tableClient = new TableClient();
 }
示例#10
0
        public async Task QueryTablesAsync()
        {
            string storageUri        = StorageUri;
            string accountName       = StorageAccountName;
            string storageAccountKey = PrimaryStorageAccountKey;
            string tableName         = "OfficeSupplies3p2" + _random.Next();

            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.QueryAsync(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.Name);
            }
            #endregion

            await serviceClient.DeleteTableAsync(tableName);
        }
示例#11
0
        /// <summary>
        /// Requesting Metrics from azure tables for each node in scale-set
        /// </summary>
        internal List <WadMetric> GetMetricsFromTable(string StorageAccountConnectionString, int LookupTimeInMinutes, string TablePrefix)
        {
            List <WadMetric> resultList = new List <WadMetric>();

            var serviceClient = new TableServiceClient(StorageAccountConnectionString);
            var table         = serviceClient.GetTableClient(TablePrefix);

            if (table == null)
            {
                throw new SystemException("There is no table in storage account with prefix:" + TablePrefix);
            }

            //CloudTable table = tableClient.GetTableReference(TableName);

            //Timeback in mins
            var            minutesBack = TimeSpan.FromMinutes(LookupTimeInMinutes);
            var            timeInPast  = DateTime.UtcNow.Subtract(minutesBack);
            DateTimeOffset qdate       = new DateTimeOffset(timeInPast);



            //TODO add ROWKEY to encrease performance.
            var result = table.Query <WadMetric>(wad => wad.PartitionKey == scalesetid.Replace("/", ":002F").Replace("-", ":002D").Replace(".", ":002E") &&
                                                 wad.Timestamp >= qdate && (wad.CounterName == CpuMetricName || wad.CounterName == DiskMetricName));

            foreach (var entity in result)
            {
                resultList.Add(entity);
            }

            return(resultList);
        }
示例#12
0
        public Table(string accountName, string accountKey, string tableName, string repoTableName)
        {
            var tableServiceClient = new TableServiceClient("DefaultEndpointsProtocol=https;AccountName=" + accountName + ";AccountKey=" + accountKey + ";TableEndpoint=https://" + accountName + ".table.cosmosdb.azure.com:443/;");

            CommitTable = tableServiceClient.GetTableClient(tableName);
            RepoTable   = tableServiceClient.GetTableClient(repoTableName);
        }
        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);
                }
            }
        }
 /// <summary>
 /// Returns a list of all tables and on hold invoices in the store/restaurant
 /// delivery invoices will have a sectionID of XXDELIVERY
 /// takeout invoices will have a sectionID of XXTAKEOUT
 /// tabs not associated with tables will have a section ID of XXOPEN TABS
 /// invoices that are at table will have the section ID of the resturant section that the table diagram screen lists them in(i.e. Bar, Dining Room, ext)
 /// </summary>
 /// <param name="context">The store id, station id, and cashier id the information should be restricted to.</param>
 /// <returns>A list of information about the open invoices, occupied status, cashier assigned, dollar value, etc.</returns>
 public List <TableInfo> GetAllTablesAndOpenInvoices(Context context)
 {
     using (TableServiceClient client = new TableServiceClient())
     {
         client.Open();
         return(new List <TableInfo>(client.GetAllTablesAndOpenInvoices(context)));
     }
 }
 /// <summary>
 /// Returns a list of all tables and on hold invoices in the store/restaurant 
 /// delivery invoices will have a sectionID of XXDELIVERY
 /// takeout invoices will have a sectionID of XXTAKEOUT
 /// tabs not associated with tables will have a section ID of XXOPEN TABS
 /// invoices that are at table will have the section ID of the resturant section that the table diagram screen lists them in(i.e. Bar, Dining Room, ext)
 /// </summary>
 /// <param name="context">The store id, station id, and cashier id the information should be restricted to.</param>
 /// <returns>A list of information about the open invoices, occupied status, cashier assigned, dollar value, etc.</returns>
 public List<TableInfo> GetAllTablesAndOpenInvoices(Context context)
 {
     using (TableServiceClient client = new TableServiceClient())
     {
         client.Open();
         return new List<TableInfo>(client.GetAllTablesAndOpenInvoices(context));
     }
 }
示例#16
0
        public FokkersDbService(TableServiceClient dbClient, string connectionString)
        {
            _connectionString    = connectionString;
            this._catchContainer = dbClient.GetTableClient("Catches");
            this._fishContainer  = dbClient.GetTableClient("Fish");

            this._catchContainer.CreateIfNotExists();
            this._fishContainer.CreateIfNotExists();
        }
示例#17
0
        async Task <IDictionary <string, object> > IAzureTableStoreClient.ReadRecordAsync(string tableName, string partitionKey, string rowKey, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(tableName))
            {
                throw new ArgumentNullException(nameof(tableName));
            }
            if (string.IsNullOrWhiteSpace(partitionKey))
            {
                throw new ArgumentNullException(nameof(partitionKey));
            }
            if (string.IsNullOrWhiteSpace(rowKey))
            {
                throw new ArgumentNullException(nameof(rowKey));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var managedIdentityCredential = new DefaultAzureCredential();

            var tableClientOptions = GetTableClientOptions(_geoRedundantServiceUrl);

            var tableServiceClient = new TableServiceClient(_primaryServiceUrl, managedIdentityCredential, tableClientOptions);

            var tableClient = tableServiceClient.GetTableClient(tableName);

            try
            {
                var result = await tableClient.GetEntityAsync <TableEntity>(partitionKey, rowKey, cancellationToken : cancellationToken);

                using var response = result.GetRawResponse();

                if (!IsSuccessStatusCode(response?.Status ?? int.MinValue))
                {
                    Debug.Assert(response is not null);

                    _logger?.LogDebug("Unable to read a record from table storage '{TableName}'.  {ClientRequestId} - Reported '{ReasonPhrase}' with status code: '{StatusCode} {StatusCodeName}'", response.ClientRequestId, tableName, response.ReasonPhrase, response.Status, Enum.Parse(typeof(HttpStatusCode), Convert.ToString(response.Status, CultureInfo.InvariantCulture)));

                    // TODO - Add custom table storage exception

                    throw new ApplicationException($"{response.ClientRequestId}: Unable to read a record from table storage '{tableName}'.  Please consult log files for more information");
                }

                return(result.Value);
            }
            catch (AuthenticationFailedException ex)
            {
                _logger?.LogError(ex, "Unable to authenticate with the Azure Table Storage service using the default credentials.  Please ensure the user account this application is running under has permissions to access the Blob Storage account we are targeting");

                throw;
            }
            catch (RequestFailedException ex)
            {
                _logger?.LogError(ex, "Unable to access the Table Storage endpoint as the Read request failed: '{StatusCode} {StatusCodeName}'", ex.Status, Enum.Parse(typeof(HttpStatusCode), Convert.ToString(ex.Status, CultureInfo.InvariantCulture)));

                throw;
            }
        }
示例#18
0
        public void CreateTable_SpecifyMetadataPreference_IndicatesIfPreferenceWasApplied()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = GenerateSampleTableName();

            var response = client.CreateTable(tableName, MetadataPreference.ReturnNoContent);

            Assert.AreEqual(MetadataPreference.ReturnNoContent, response.MetadataPreferenceApplied);
        }
示例#19
0
        public void CreateTable_RequiredArgsOnly_CreatesTable()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = GenerateSampleTableName();

            client.CreateTable(tableName);

            AssertTableExists(tableName);
        }
示例#20
0
        public async Task CreateTableAsync_RequiredArgsOnly_CreatesTable()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = GenerateSampleTableName();

            await client.CreateTableAsync(tableName);

            AssertTableExists(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);
        }
        public void CreateTable_RequiredArgsOnly_CreatesTable()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = GenerateSampleTableName();

            client.CreateTable(tableName);

            AssertTableExists(tableName);
        }
示例#23
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddTransient <IShortenerService, ShortenerService>();
            builder.Services.AddTransient <IExpanderService, ExpanderService>();

            var client = new TableServiceClient(connectionString);

            builder.Services.AddSingleton(client);
        }
示例#24
0
 public StorageManager(IOptions <StorageOptions> options, ILogger <StorageManager> logger)
 {
     _options          = options.Value;
     _connectionString = _options.StorageAccount;
     _logger           = logger;
     _serviceClient    = new TableServiceClient(_connectionString);
     _dishTable        = _serviceClient.GetTableClient("dish");
     _dishTable.CreateIfNotExists();
 }
示例#25
0
        private static IEnumerable <object[]> TableServiceClients()
        {
            var cred             = new TableSharedKeyCredential(AccountName, Secret);
            var sharedKeyClient  = new TableServiceClient(_url, cred);
            var connStringClient = new TableServiceClient($"DefaultEndpointsProtocol=https;AccountName={AccountName};AccountKey={Secret};TableEndpoint=https://{AccountName}.table.cosmos.azure.com:443/;");

            yield return(new object[] { sharedKeyClient, cred });

            yield return(new object[] { connStringClient, cred });
        }
示例#26
0
        public TableExceptionStore(
            TableServiceClientProvider tableServiceClientProvider,
            ILogger <TableExceptionStore> logger)
        {
            EnsureArg.IsNotNull(tableServiceClientProvider, nameof(tableServiceClientProvider));
            EnsureArg.IsNotNull(logger, nameof(logger));

            _tableServiceClient = tableServiceClientProvider.GetTableServiceClient();
            _logger             = logger;
        }
 public TableEntityBinding(string parameterName, IArgumentBinding <TableEntityContext> argumentBinding,
                           TableServiceClient client, IBindableTableEntityPath path)
 {
     _parameterName   = parameterName;
     _argumentBinding = argumentBinding;
     _client          = client;
     _accountName     = TableClientHelpers.GetAccountName(client);
     _path            = path;
     _converter       = CreateConverter(client, path);
 }
        private async Task <TableClient> RetrieveTable()
        {
            var serviceClient = new TableServiceClient(connectionString);

            await serviceClient.CreateTableIfNotExistsAsync(TableName);

            var tableClient = serviceClient.GetTableClient(TableName);

            return(tableClient);
        }
示例#29
0
        /// <summary>
        /// Creates a an Azure Table
        /// </summary>
        /// <returns></returns>
        private static async Task <FokkersDbService> InitializeTableClientInstanceAsync(IConfigurationSection configurationSection)
        {
            string connectionString = configurationSection.GetSection("ConnectionString").Value;
            string accountName      = configurationSection.GetSection("AccountName").Value;
            var    serviceClient    = new TableServiceClient(connectionString);

            FokkersDbService tableDbService = new FokkersDbService(serviceClient, connectionString);

            return(tableDbService);
        }
        public void AccountNameAndNameForConnStringCtor(string connString, string accountName)
        {
            var client = new TableServiceClient(connString, new TableClientOptions());

            Assert.AreEqual(accountName, client.AccountName);

            var tableClient = client.GetTableClient("someTable");

            Assert.AreEqual(accountName, tableClient.AccountName);
        }
示例#31
0
 public TableStorageReplayValidator(
     TableServiceClient tableServiceClient,
     ILogger <TableStorageReplayValidator> logger,
     IOptions <TableStorageReplayValidatorOptions> options)
 {
     _logger             = logger;
     _tablePrefix        = options.Value.TablePrefix;
     _bucketSize         = options.Value.BucketSize;
     _tableServiceClient = tableServiceClient;
 }
        public void CreateTable_TableAlreadyExists_ReportsConflict()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = GenerateSampleTableName();
            CreateTable(tableName);

            client.CreateTable(tableName);

            // expects exception
        }
        public void GenerateSasUri(TableServiceClient client, TableSharedKeyCredential cred)
        {
            TableAccountSasPermissions   permissions   = TableAccountSasPermissions.Add;
            TableAccountSasResourceTypes resourceTypes = TableAccountSasResourceTypes.Container;
            var expires     = DateTime.Now.AddDays(1);
            var expectedSas = new TableAccountSasBuilder(permissions, resourceTypes, expires).Sign(cred);

            var actualSas = client.GenerateSasUri(permissions, resourceTypes, expires);

            Assert.AreEqual("?" + expectedSas, actualSas.Query);
        }
        public void QueryEntities_NonExistentTable_ThrowsTableNotFound()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = _util.GenerateSampleTableName();
            string partitionKey = "A";
            string rowKey = "1";

            var response = client.QueryEntities<SampleEntity>(tableName, partitionKey, rowKey);

            //expects exception
        }
        public void CreateTable_ValidName_ReceivesFullUrlInResponse()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = GenerateSampleTableName();

            var response = client.CreateTable(tableName);

            // I'm just looking for link text that has the name, not a direct match 
            //  against what they happen to be repsonding with right now
            string expectedLinkPattern = "https?://.*" + tableName + ".*";
            Assert.IsTrue(Regex.IsMatch(response.Link, expectedLinkPattern));
        }
        public async Task QueryEntitiesAsync_PartitionAndRowKey_ReturnsSingleEntity()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = _util.GenerateSampleTableName();
            _util.CreateTable(tableName);
            string partitionKey = "A";
            string rowKey = "1";
            _util.InsertTableEntity(tableName, partitionKey, rowKey);

            var response = await client.QueryEntitiesAsync<SampleEntity>(tableName, partitionKey, rowKey);

            Assert.AreEqual(1, response.Entities.Count);
            var entity = response.Entities[0];
            Assert.AreEqual(partitionKey, entity.PartitionKey);
            Assert.AreEqual(rowKey, entity.RowKey);
        }
        public void QueryTables_LessThan1000Tables_ReturnsList()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableList = new List<string>();
            for (int i = 0; i < 10; i++)
            {
                var name = _util.GenerateSampleTableName();
                tableList.Add(name);
                _util.CreateTable(name);
            }

            var response = client.QueryTables();

            int numExpectedTablesInResponse = 0;
            foreach (var expectedTable in tableList)
            {
                if (response.TableList.Contains(expectedTable))
                    numExpectedTablesInResponse++;
            }
            Assert.AreEqual(tableList.Count, numExpectedTablesInResponse);
        }
        public async Task InsertOrMergeEntityAsync_ExistingEntity_UpdatesEntityInTable()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = _util.GenerateSampleTableName();
            _util.CreateTable(tableName);
            var sampleEntity = new SampleEntity()
            {
                PartitionKey = "1",
                RowKey = "A",
                ExtraValue = "Extra"
            };
            _util.InsertTableEntity(tableName, sampleEntity.PartitionKey, sampleEntity.RowKey);

            await client.InsertOrMergeEntityAsync(tableName, sampleEntity);

            _util.AssertEntityExists(tableName, sampleEntity);
            var entity = _util.GetEntity<SampleMSEntity>(tableName, sampleEntity.PartitionKey, sampleEntity.RowKey);
            Assert.AreEqual(sampleEntity.ExtraValue, entity.ExtraValue);
        }
        public void UpdateEntity_NonexistentEntity_ExpectsException()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = _util.GenerateSampleTableName();
            var sampleEntity = new SampleEntity()
            {
                PartitionKey = "1",
                RowKey = "A",
                ExtraValue = "Extra"
            };

            client.UpdateEntity(tableName, sampleEntity);

            // expects exception
        }
        public void CreateTable_SpecifyMetadataPreference_IndicatesIfPreferenceWasApplied()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = GenerateSampleTableName();

            var response = client.CreateTable(tableName, MetadataPreference.ReturnNoContent);

            Assert.AreEqual(MetadataPreference.ReturnNoContent, response.MetadataPreferenceApplied);
        }
        public async Task CreateTableAsync_TableAlreadyExists_ReportsConflict()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = _util.GenerateSampleTableName();
            _util.CreateTable(tableName);

            await client.CreateTableAsync(tableName);

            // expects exception
        }
        public void MergeEntity_ExistingEntityWithMatchingRequiredETag_MergesEntityInTable()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = _util.GenerateSampleTableName();
            _util.CreateTable(tableName);
            var sampleEntity = new SampleEntity()
            {
                PartitionKey = "1",
                RowKey = "A",
                ExtraValue = "Extra"
            };
            var etag = _util.InsertTableEntity(tableName, sampleEntity.PartitionKey, sampleEntity.RowKey);

            client.MergeEntity(tableName, sampleEntity, etag);

            _util.AssertEntityExists(tableName, sampleEntity);
            var entity = _util.GetEntity<SampleMSEntity>(tableName, sampleEntity.PartitionKey, sampleEntity.RowKey);
            Assert.AreEqual(sampleEntity.ExtraValue, entity.ExtraValue);
        }
        public void MergeEntity_ExistingEntityWithMismatchedRequiredETag_ThrowsException()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = _util.GenerateSampleTableName();
            _util.CreateTable(tableName);
            var sampleEntity = new SampleEntity()
            {
                PartitionKey = "1",
                RowKey = "A",
                ExtraValue = "Extra"
            };
            var etag = _util.InsertTableEntity(tableName, sampleEntity.PartitionKey, sampleEntity.RowKey);

            client.MergeEntity(tableName, sampleEntity, etag.Replace("201", "XXX"));    // etag includes a date string, so we can easily swap out part to create an invalid one

            // expects exception
        }
        public void DeleteEntity_ValidEntityWithRightETag_DeletesEntity()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = _util.GenerateSampleTableName();
            string partitionKey = "A";
            string rowKey = "1";
            _util.CreateTable(tableName);
            var etag = _util.InsertTableEntity(tableName, partitionKey, rowKey);

            client.DeleteEntity(tableName, partitionKey, rowKey, etag);

            _util.AssertEntityDoesNotExist(tableName, partitionKey, rowKey);
        }
        public void DeleteEntity_ValidEntityWithWrongETag_ThrowsException()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = _util.GenerateSampleTableName();
            string partitionKey = "A";
            string rowKey = "1";
            _util.CreateTable(tableName);
            var etag = _util.InsertTableEntity(tableName, partitionKey, rowKey);

            client.DeleteEntity(tableName, partitionKey, rowKey, etag.Replace("201","XXX"));    // ms uses a date in the etag so we can replace part of it to invalidate it

            // expects exception
        }
        public void DeleteEntity_NonExistentTable_ThrowsException()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = _util.GenerateSampleTableName();
            string partitionKey = "A";
            string rowKey = "1";

            client.DeleteEntity(tableName, partitionKey, rowKey);

            // expects exception
        }
        public void InsertEntity_ValidTable_InsertsEntityInTable()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = _util.GenerateSampleTableName();
            _util.CreateTable(tableName);
            var sampleEntity = new SampleEntity() { 
                PartitionKey = "1",
                RowKey = "A"
            };

            client.InsertEntity(tableName, sampleEntity);

            _util.AssertEntityExists(tableName, sampleEntity);
        }
        public void InsertEntity_PreexistingEntity_ExpectsException()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = _util.GenerateSampleTableName();
            _util.CreateTable(tableName);
            var sampleEntity = new SampleEntity()
            {
                PartitionKey = "1",
                RowKey = "A"
            };
            _util.InsertTableEntity(tableName, sampleEntity.PartitionKey, sampleEntity.RowKey);

            client.InsertEntity(tableName, sampleEntity);

            // expects exception
        }
        public void InsertOrMergeEntity_InvalidTable_ExpectsException()
        {
            ITableServiceClient client = new TableServiceClient(_accountSettings);
            var tableName = _util.GenerateSampleTableName();
            var sampleEntity = new SampleEntity()
            {
                PartitionKey = "1",
                RowKey = "A",
                ExtraValue = "Extra"
            };

            client.InsertOrMergeEntity(tableName, sampleEntity);

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

            await client.CreateTableAsync(tableName);

            AssertTableExists(tableName);
        }