static NDIAzureTableController()
 {
     _storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
     _tableClient = _storageAccount.CreateCloudTableClient();
     _table = _tableClient.GetTableReference("ndiparams");
     _retrieveOperation = TableOperation.Retrieve("VidParams", "LastVideo");
 }
コード例 #2
0
 public ExecutableTableOperation( string table, TableOperation operation, TableOperationType operationType, string partitionKey, string rowKey )
 {
     Table = table;
      Operation = operation;
      OperationType = operationType;
      PartitionKey = partitionKey;
      RowKey = rowKey;
 }
        public int PutVideo(string video)
        {
            var entity = new DynamicTableEntity("VidParams", "LastVideo") { ETag = "*" };
            entity.Properties["VideoCode"] = new EntityProperty(video);
            _updateOperation = TableOperation.Replace(entity);

            dynamic result = _table.Execute(_updateOperation).Result;
            return result.Properties.Count;
        }
コード例 #4
0
        public async Task <T> ById(string partitionKey, string rowKey)
        {
            CT.TableOperation op     = CT.TableOperation.Retrieve <FatEntity>(partitionKey, rowKey);
            CT.TableResult    result = await _table.ExecuteWrap(t => t.ExecuteAsync(op)).ConfigureAwait(false);

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

            return(ConvertFatEntity((FatEntity)result.Result));
        }
コード例 #5
0
        public void Add(string partition, TableOperation operation)
        {
            if (!updatePool.ContainsKey(partition))
            {
                updatePool[partition] = new DelayedBatchOperation(partition);
            }

            updatePool[partition].TableBatchOperation.Add(operation);

            if (updatePool[partition].TableBatchOperation.Count == 100)
            {
                EnqueueBatch(partition);

            }
        }
コード例 #6
0
        private static RESTCommand <TableResult> InsertImpl(TableOperation operation, CloudTableClient client, string tableName, TableRequestOptions requestOptions)
        {
            RESTCommand <TableResult> insertCmd = new RESTCommand <TableResult>(client.Credentials, operation.GenerateRequestURI(client.StorageUri, tableName));

            requestOptions.ApplyToStorageCommand(insertCmd);

            TableResult result = new TableResult()
            {
                Result = operation.Entity
            };

            insertCmd.RetrieveResponseStream = true;
            insertCmd.Handler            = client.AuthenticationHandler;
            insertCmd.BuildClient        = HttpClientFactory.BuildHttpClient;
            insertCmd.ParseError         = StorageExtendedErrorInformation.ReadFromStreamUsingODataLib;
            insertCmd.BuildRequest       = (cmd, uri, builder, cnt, serverTimeout, ctx) => TableOperationHttpRequestMessageFactory.BuildRequestForTableOperation(cmd, uri, builder, serverTimeout, operation, client, cnt, ctx, requestOptions.PayloadFormat.Value);
            insertCmd.PreProcessResponse = (cmd, resp, ex, ctx) => TableOperationHttpResponseParsers.TableOperationPreProcess(result, operation, resp, ex, cmd, ctx);

            insertCmd.PostProcessResponse = (cmd, resp, ctx) => TableOperationHttpResponseParsers.TableOperationPostProcess(result, operation, cmd, resp, ctx, requestOptions, client.AccountName);

            return(insertCmd);
        }
コード例 #7
0
        public async Task TableSasUriTestAsync()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                await table.CreateAsync();

                BaseEntity entity  = new BaseEntity("PK", "RK");
                BaseEntity entity1 = new BaseEntity("PK", "RK1");
                await table.ExecuteAsync(TableOperation.Insert(entity));

                await table.ExecuteAsync(TableOperation.Insert(entity1));

                SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
                {
                    SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                    Permissions            = SharedAccessTablePermissions.Delete,
                };

                string              sasToken = table.GetSharedAccessSignature(policy, null, null, null, null, null);
                StorageCredentials  creds    = new StorageCredentials(sasToken);
                CloudStorageAccount sasAcc   = new CloudStorageAccount(creds, null /* blobEndpoint */, null /* queueEndpoint */, new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint), null /* fileEndpoint */);
                CloudTableClient    client   = sasAcc.CreateCloudTableClient();

                CloudTable sasTable = new CloudTable(client.Credentials.TransformUri(table.Uri));
                await sasTable.ExecuteAsync(TableOperation.Delete(entity));

                CloudTable sasTable2 = new CloudTable(new Uri(table.Uri.ToString() + sasToken));
                await sasTable2.ExecuteAsync(TableOperation.Delete(entity1));
            }
            finally
            {
                table.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
コード例 #8
0
ファイル: TableQueryTests.cs プロジェクト: Ankitvaibs/SM
        private async Task DoTableQueryEmptyValueAsync(TablePayloadFormat format)
        {
            tableClient.DefaultRequestOptions.PayloadFormat = format;
            CloudTable table = tableClient.GetTableReference(GenerateRandomTableName());
            await table.CreateAsync();

            // Setup
            string pk = Guid.NewGuid().ToString();

            DynamicTableEntity dynEnt = new DynamicTableEntity(pk, "rowkey");

            dynEnt.Properties.Add("A", new EntityProperty(string.Empty));
            await table.ExecuteAsync(TableOperation.Insert(dynEnt));

            // 1. Filter on String
            List <DynamicTableEntity> results = (await table.ExecuteQuerySegmentedAsync(new TableQuery().Where(TableQuery.GenerateFilterCondition("A", QueryComparisons.Equal, string.Empty)), null)).ToList();

            Assert.AreEqual(1, results.Count);

            List <BaseEntity> pocoresults = (await table.ExecuteQuerySegmentedAsync(new TableQuery <BaseEntity>().Where(TableQuery.GenerateFilterCondition("A", QueryComparisons.Equal, string.Empty)), null)).ToList();

            Assert.AreEqual(1, pocoresults.Count);
        }
コード例 #9
0
        public void TableOperationConflictDoesNotRetry()
        {
            CloudTableClient   tableClient  = GenerateCloudTableClient();
            DynamicTableEntity insertEntity = new DynamicTableEntity("insert test", "foo");

            currentTable.Execute(TableOperation.Insert(insertEntity));

            OperationContext opContext = new OperationContext();

            try
            {
                currentTable.Execute(TableOperation.Insert(insertEntity), null, opContext);
                Assert.Fail();
            }
            catch (StorageException)
            {
                TestHelper.AssertNAttempts(opContext, 1);
            }
            catch (Exception)
            {
                Assert.Fail();
            }
        }
コード例 #10
0
        public async Task TableSetGetPermissionsAsync()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                await table.CreateAsync();

                await table.ExecuteAsync(TableOperation.Insert(new BaseEntity("PK", "RK")));

                TablePermissions expectedPermissions = new TablePermissions();
                TablePermissions testPermissions     = await table.GetPermissionsAsync();

                AssertPermissionsEqual(expectedPermissions, testPermissions);

                // Add a policy, check setting and getting.
                expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy
                {
                    Permissions            = SharedAccessTablePermissions.Query,
                    SharedAccessStartTime  = DateTimeOffset.Now - TimeSpan.FromHours(1),
                    SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(1)
                });

                await table.SetPermissionsAsync(expectedPermissions);

                await Task.Delay(30 * 1000);

                testPermissions = await table.GetPermissionsAsync();

                AssertPermissionsEqual(expectedPermissions, testPermissions);
            }
            finally
            {
                table.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
コード例 #11
0
        private static RESTCommand<TableResult> InsertImpl(TableOperation operation, CloudTableClient client, string tableName, TableRequestOptions requestOptions)
        {
            RESTCommand<TableResult> insertCmd = new RESTCommand<TableResult>(client.Credentials, operation.GenerateRequestURI(client.BaseUri, tableName));
            insertCmd.ApplyRequestOptions(requestOptions);

            TableResult result = new TableResult() { Result = operation.Entity };
            insertCmd.RetrieveResponseStream = true;
            insertCmd.Handler = client.AuthenticationHandler;
            insertCmd.BuildClient = HttpClientFactory.BuildHttpClient;
            insertCmd.BuildRequest = (cmd, cnt, ctx) => TableOperationHttpRequestMessageFactory.BuildRequestForTableOperation(cmd, cmd.ServerTimeoutInSeconds, operation, client, ctx);
            insertCmd.PreProcessResponse = (cmd, resp, ex, ctx) => TableOperationHttpResponseParsers.TableOperationPreProcess(result, operation, resp, ex, cmd, ctx);

            insertCmd.PostProcessResponse = (cmd, resp, ctx) => TableOperationHttpResponseParsers.TableOperationPostProcess(result, operation, cmd, resp, ctx);

            return insertCmd;
        }
コード例 #12
0
 /// <summary>
 /// Executes the operation on a table.
 /// </summary>
 /// <param name="operation">A <see cref="TableOperation"/> object that represents the operation to perform.</param>
 /// <returns>A <see cref="TableResult"/> containing the result of executing the operation on the table.</returns>
 public IAsyncOperation <TableResult> ExecuteAsync(TableOperation operation)
 {
     return(this.ExecuteAsync(operation, null /* RequestOptions */, null /* OperationContext */));
 }
コード例 #13
0
        private static RESTCommand<TableResult> ReplaceImpl(TableOperation operation, CloudTableClient client, CloudTable table, TableRequestOptions requestOptions)
        {
            RESTCommand<TableResult> replaceCmd = new RESTCommand<TableResult>(client.Credentials, operation.GenerateRequestURI(client.StorageUri, table.Name));
            requestOptions.ApplyToStorageCommand(replaceCmd);

            TableResult result = new TableResult() { Result = operation.Entity };
            replaceCmd.RetrieveResponseStream = false;
            replaceCmd.SignRequest = client.AuthenticationHandler.SignRequest;
            replaceCmd.ParseError = StorageExtendedErrorInformation.ReadFromStreamUsingODataLib;
            replaceCmd.BuildRequestDelegate = (uri, builder, timeout, useVersionHeader, ctx) =>
            {
                Tuple<HttpWebRequest, Stream> res = TableOperationHttpWebRequestFactory.BuildRequestForTableOperation(uri, builder, client.BufferManager, timeout, operation, useVersionHeader, ctx, requestOptions, client.AccountName);
                replaceCmd.SendStream = res.Item2;
                return res.Item1;
            };

            replaceCmd.PreProcessResponse = (cmd, resp, ex, ctx) => TableOperationHttpResponseParsers.TableOperationPreProcess(result, operation, resp, ex);

            return replaceCmd;
        }
コード例 #14
0
        private static RESTCommand<TableResult> ReplaceImpl(TableOperation operation, CloudTableClient client, string tableName, TableRequestOptions requestOptions)
        {
            RESTCommand<TableResult> replaceCmd = new RESTCommand<TableResult>(client.Credentials, operation.GenerateRequestURI(client.StorageUri, tableName));
            requestOptions.ApplyToStorageCommand(replaceCmd);

            TableResult result = new TableResult() { Result = operation.Entity };
            replaceCmd.RetrieveResponseStream = false;
            replaceCmd.Handler = client.AuthenticationHandler;
            replaceCmd.BuildClient = HttpClientFactory.BuildHttpClient;
            replaceCmd.BuildRequest = (cmd, uri, builder, cnt, serverTimeout, ctx) => TableOperationHttpRequestMessageFactory.BuildRequestForTableOperation(cmd, uri, builder, serverTimeout, operation, client, cnt, ctx);
            replaceCmd.PreProcessResponse = (cmd, resp, ex, ctx) => TableOperationHttpResponseParsers.TableOperationPreProcess(result, operation, resp, ex, cmd, ctx);

            return replaceCmd;
        }
コード例 #15
0
        /// <summary>
        /// Executes the operation on a table, using the specified <see cref="TableRequestOptions"/> and <see cref="OperationContext"/>.
        /// </summary>
        /// <param name="operation">A <see cref="TableOperation"/> object that represents the operation to perform.</param>
        /// <param name="requestOptions">A <see cref="TableRequestOptions"/> object that specifies execution options, such as retry policy and timeout settings, for the operation.</param>
        /// <param name="operationContext">An <see cref="OperationContext"/> object for tracking the current operation.</param>
        /// <returns>A <see cref="TableResult"/> containing the result of executing the operation on the table.</returns>
        public IAsyncOperation<TableResult> ExecuteAsync(TableOperation operation, TableRequestOptions requestOptions, OperationContext operationContext)
        {
            CommonUtility.AssertNotNull("operation", operation);

            return operation.ExecuteAsync(this.ServiceClient, this.Name, requestOptions, operationContext);
        }
コード例 #16
0
        /// <summary>
        /// Checks existence of the queue.
        /// </summary>
        /// <param name="primaryOnly">If <c>true</c>, the command will be executed against the primary location.</param>
        /// <param name="requestOptions">A <see cref="TableRequestOptions"/> object that specifies execution options, such as retry policy and timeout settings, for the operation.</param>
        /// <param name="operationContext">An <see cref="OperationContext"/> object for tracking the current operation.</param>
        /// <returns><c>true</c> if the queue exists.</returns>
        private IAsyncOperation<bool> ExistsAsync(bool primaryOnly, TableRequestOptions requestOptions, OperationContext operationContext)
        {
            requestOptions = TableRequestOptions.ApplyDefaults(requestOptions, this.ServiceClient);
            operationContext = operationContext ?? new OperationContext();

            DynamicTableEntity tblEntity = new DynamicTableEntity();
            tblEntity.Properties.Add(TableConstants.TableName, new EntityProperty(this.Name));
            TableOperation operation = new TableOperation(tblEntity, TableOperationType.Retrieve);
            operation.IsTableEntity = true;
            operation.IsPrimaryOnlyRetrieve = primaryOnly;

            return AsyncInfo.Run(async (cancellationToken) =>
            {
                TableResult res = await this.ServiceClient.ExecuteAsync(TableConstants.TableServiceTablesName, operation, requestOptions, operationContext).AsTask(cancellationToken);

                // Only other option is not found, other status codes will throw prior to this.            
                return res.HttpStatusCode == (int)HttpStatusCode.OK;
            });
        }
コード例 #17
0
        private void DoTableBatchBasicOperationsCheck(TablePayloadFormat format)
        {
            tableClient.DefaultRequestOptions.PayloadFormat = format;

            string pk = Guid.NewGuid().ToString();
            TableBatchOperation batch = new TableBatchOperation();

            // Add insert
            DynamicTableEntity ent1 = GenerateRandomEntity(pk);
            TableOperation operation1 = TableOperation.Insert(ent1);
            batch.Add(operation1);

            DynamicTableEntity ent2 = GenerateRandomEntity(pk);
            TableOperation operation2 = TableOperation.Insert(ent2);
            batch.Add(operation2);

            TableOperation[] operationsArray = new TableOperation[2];
            batch.CopyTo(operationsArray, 0);

            Assert.AreEqual(operation1.Entity.RowKey, operationsArray[0].Entity.RowKey);
            Assert.AreEqual(operation1.OperationType, operationsArray[0].OperationType);
            Assert.AreEqual(operation2.Entity.RowKey, operationsArray[1].Entity.RowKey);
            Assert.AreEqual(operation2.OperationType, operationsArray[1].OperationType);

            Assert.AreEqual(0, batch.IndexOf(operation1));
            Assert.AreEqual(1, batch.IndexOf(operation2));

            IEnumerator<TableOperation> enumerator = batch.GetEnumerator();
            int totalCount = 0;
            while (enumerator.MoveNext())
                totalCount++;
            Assert.AreEqual(2, totalCount);

            Assert.IsTrue(batch.Remove(operation2));
            Assert.IsFalse(batch.IsReadOnly);
            TestHelper.ExpectedException<NotSupportedException>(() => batch[0] = operation1,
                    "Setter is not supported for TableBatchOperation");
        }
コード例 #18
0
 /// <summary>
 ///     Executes table operation asynchronously.
 /// </summary>
 /// <param name="operation">
 ///     A <see cref="T:Microsoft.WindowsAzure.Storage.Table.TableOperation" /> object that represents the operation to perform.
 /// </param>
 /// <param name="cancellationToken">Cancellation token.</param>
 /// <returns>
 ///     A <see cref="T:Microsoft.WindowsAzure.Storage.Table.TableResult" /> containing the result of executing the operation on the table.
 /// </returns>
 public Task<TableResult> ExecuteAsync(TableOperation operation, CancellationToken cancellationToken)
 {
     return _cloudTable.ExecuteAsync(operation, cancellationToken);
 }
コード例 #19
0
 /// <summary>
 ///     Executes the operation on a table.
 /// </summary>
 /// <param name="operation">
 ///     A <see cref="T:Microsoft.WindowsAzure.Storage.Table.TableOperation" /> object that represents the operation to perform.
 /// </param>
 /// <returns>
 ///     A <see cref="T:Microsoft.WindowsAzure.Storage.Table.TableResult" /> containing the result of executing the operation on the table.
 /// </returns>
 public TableResult Execute(TableOperation operation)
 {
     return _cloudTable.Execute(operation);
 }
コード例 #20
0
        private async Task DoEscapeTestAsync(string data, bool useBatch, bool includeKey)
        {
            DynamicTableEntity ent = new DynamicTableEntity(includeKey ? "temp" + data : "temp", Guid.NewGuid().ToString());

            ent.Properties.Add("foo", new EntityProperty(data));

            // Insert
            if (useBatch)
            {
                TableBatchOperation batch = new TableBatchOperation();
                batch.Insert(ent);
                await currentTable.ExecuteBatchAsync(batch);
            }
            else
            {
                await currentTable.ExecuteAsync(TableOperation.Insert(ent));
            }

            // Retrieve
            TableResult res = null;

            if (useBatch)
            {
                TableBatchOperation batch = new TableBatchOperation();
                batch.Retrieve(ent.PartitionKey, ent.RowKey);
                res = (await currentTable.ExecuteBatchAsync(batch))[0];
            }
            else
            {
                res = await currentTable.ExecuteAsync(TableOperation.Retrieve(ent.PartitionKey, ent.RowKey));
            }

            // Check equality
            DynamicTableEntity retrievedEntity = res.Result as DynamicTableEntity;

            Assert.AreEqual(ent.PartitionKey, retrievedEntity.PartitionKey);
            Assert.AreEqual(ent.RowKey, retrievedEntity.RowKey);
            Assert.AreEqual(ent.ETag, retrievedEntity.ETag);
            Assert.AreEqual(ent.Properties.Count, retrievedEntity.Properties.Count);
            Assert.AreEqual(ent.Properties["foo"], retrievedEntity.Properties["foo"]);

            // Merge
            ent.Properties.Add("foo2", new EntityProperty("bar2"));

            if (useBatch)
            {
                TableBatchOperation batch = new TableBatchOperation();
                batch.Merge(ent);
                await currentTable.ExecuteBatchAsync(batch);
            }
            else
            {
                await currentTable.ExecuteAsync(TableOperation.Merge(ent));
            }

            // Retrieve
            if (useBatch)
            {
                TableBatchOperation batch = new TableBatchOperation();
                batch.Retrieve(ent.PartitionKey, ent.RowKey);
                res = (await currentTable.ExecuteBatchAsync(batch))[0];
            }
            else
            {
                res = await currentTable.ExecuteAsync(TableOperation.Retrieve(ent.PartitionKey, ent.RowKey));
            }

            retrievedEntity = res.Result as DynamicTableEntity;
            Assert.AreEqual(ent.PartitionKey, retrievedEntity.PartitionKey);
            Assert.AreEqual(ent.RowKey, retrievedEntity.RowKey);
            Assert.AreEqual(ent.ETag, retrievedEntity.ETag);
            Assert.AreEqual(ent.Properties.Count, retrievedEntity.Properties.Count);
            Assert.AreEqual(ent.Properties["foo"], retrievedEntity.Properties["foo"]);

            // Replace
            ent.Properties.Remove("foo2");
            ent.Properties.Add("foo3", new EntityProperty("bar3"));

            if (useBatch)
            {
                TableBatchOperation batch = new TableBatchOperation();
                batch.Replace(ent);
                await currentTable.ExecuteBatchAsync(batch);
            }
            else
            {
                await currentTable.ExecuteAsync(TableOperation.Replace(ent));
            }

            // Retrieve
            if (useBatch)
            {
                TableBatchOperation batch = new TableBatchOperation();
                batch.Retrieve(ent.PartitionKey, ent.RowKey);
                res = (await currentTable.ExecuteBatchAsync(batch))[0];
            }
            else
            {
                res = await currentTable.ExecuteAsync(TableOperation.Retrieve(ent.PartitionKey, ent.RowKey));
            }

            retrievedEntity = res.Result as DynamicTableEntity;
            Assert.AreEqual(ent.PartitionKey, retrievedEntity.PartitionKey);
            Assert.AreEqual(ent.RowKey, retrievedEntity.RowKey);
            Assert.AreEqual(ent.ETag, retrievedEntity.ETag);
            Assert.AreEqual(ent.Properties.Count, retrievedEntity.Properties.Count);
            Assert.AreEqual(ent.Properties["foo"], retrievedEntity.Properties["foo"]);
        }
コード例 #21
0
 public static Func<string, string, DateTimeOffset, IDictionary<string, EntityProperty>, string, object> GetRetrieveResolver(TableOperation operation)
 {
     return (Func<string, string, DateTimeOffset, IDictionary<string, EntityProperty>, string, object>)
         TableOperation_RetrieveResolver.GetValue(operation, null);
 }
コード例 #22
0
        public async Task TableGetSetPermissionTestAsync()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                await table.CreateAsync();

                var entity = new BaseEntity("PK", "RK");
                entity.Populate();

                await table.ExecuteAsync(TableOperation.Insert(entity));

                TablePermissions expectedPermissions;
                TablePermissions testPermissions;

                // Test new table permissions.
                expectedPermissions = new TablePermissions();
                testPermissions     = await table.GetPermissionsAsync();

                AssertPermissionsEqual(expectedPermissions, testPermissions);

                // Test setting empty permissions.
                await table.SetPermissionsAsync(expectedPermissions);

                await Task.Delay(30 * 1000);

                testPermissions = await table.GetPermissionsAsync();

                AssertPermissionsEqual(expectedPermissions, testPermissions);

                // Add a policy, check setting and getting.
                expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy
                {
                    Permissions            = SharedAccessTablePermissions.Query,
                    SharedAccessStartTime  = DateTimeOffset.Now - TimeSpan.FromHours(1),
                    SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(1)
                });

                await table.SetPermissionsAsync(expectedPermissions);

                await Task.Delay(30 * 1000);

                testPermissions = await table.GetPermissionsAsync();

                AssertPermissionsEqual(expectedPermissions, testPermissions);

                // Add a policy, check setting and getting.
                expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy
                {
                    Permissions            = SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Add,
                    SharedAccessStartTime  = DateTimeOffset.Now + TimeSpan.FromHours(1),
                    SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromDays(1)
                });

                await table.SetPermissionsAsync(expectedPermissions);

                await Task.Delay(30 * 1000);

                testPermissions = await table.GetPermissionsAsync();

                AssertPermissionsEqual(expectedPermissions, testPermissions);

                // Add a null policy, check setting and getting.
                expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy
                {
                    Permissions = SharedAccessTablePermissions.None,
                });

                await table.SetPermissionsAsync(expectedPermissions);

                await Task.Delay(30 * 1000);

                testPermissions = await table.GetPermissionsAsync();

                AssertPermissionsEqual(expectedPermissions, testPermissions);

                // Add a policy, check setting and getting.
                expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy
                {
                    Permissions            = SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Query | SharedAccessTablePermissions.Update | SharedAccessTablePermissions.Delete,
                    SharedAccessStartTime  = DateTimeOffset.Now + TimeSpan.FromDays(0.5),
                    SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromDays(1)
                });

                await table.SetPermissionsAsync(expectedPermissions);

                await Task.Delay(30 * 1000);

                testPermissions = await table.GetPermissionsAsync();

                AssertPermissionsEqual(expectedPermissions, testPermissions);

                // Add a policy, check setting and getting.
                expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy
                {
                    Permissions            = SharedAccessTablePermissions.Update,
                    SharedAccessStartTime  = DateTimeOffset.Now + TimeSpan.FromHours(6),
                    SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(6.5)
                });

                await table.SetPermissionsAsync(expectedPermissions);

                await Task.Delay(30 * 1000);

                testPermissions = await table.GetPermissionsAsync();

                AssertPermissionsEqual(expectedPermissions, testPermissions);
            }
            finally
            {
                table.DeleteIfExistsAsync().Wait();
            }
        }
コード例 #23
0
        private static RESTCommand<TableResult> InsertImpl(TableOperation operation, CloudTableClient client, string tableName, TableRequestOptions requestOptions)
        {
            RESTCommand<TableResult> insertCmd = new RESTCommand<TableResult>(client.Credentials, operation.GenerateRequestURI(client.BaseUri, tableName));
            requestOptions.ApplyToStorageCommand(insertCmd);

            TableResult result = new TableResult() { Result = operation.Entity };
            insertCmd.RetrieveResponseStream = true;
            insertCmd.Handler = client.AuthenticationHandler;
            insertCmd.BuildClient = HttpClientFactory.BuildHttpClient;
            insertCmd.BuildRequest = (cmd, cnt, ctx) => TableOperationHttpRequestMessageFactory.BuildRequestForTableOperation(cmd.Uri, cmd.ServerTimeoutInSeconds, operation, ctx);
            insertCmd.PreProcessResponse = (cmd, resp, ex, ctx) => TableOperationHttpResponseParsers.TableOperationPreProcess(result, operation, resp, ex, cmd, ctx);

            insertCmd.PostProcessResponse = (cmd, resp, ex, ctx) =>
                  Task.Run(async () =>
                    {
                        HttpResponseParsers.ProcessExpectedStatusCodeNoException(
                                                operation.OperationType == TableOperationType.Insert ? HttpStatusCode.Created : HttpStatusCode.NoContent,
                                                resp,
                                                result,
                                                cmd,
                                                ex,
                                                ctx);

                        result = await TableOperationHttpResponseParsers.TableOperationPostProcess(result, operation, cmd, resp, ctx);
                        return result;
                    });

            return insertCmd;
        }
コード例 #24
0
        public async Task TableSASNullAccessPolicyAsync()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                await table.CreateAsync();

                await table.ExecuteAsync(TableOperation.Insert(new BaseEntity("PK", "RK")));

                TablePermissions expectedPermissions = new TablePermissions();

                // Add a policy
                expectedPermissions.SharedAccessPolicies.Add(Guid.NewGuid().ToString(), new SharedAccessTablePolicy
                {
                    Permissions            = SharedAccessTablePermissions.Query | SharedAccessTablePermissions.Add,
                    SharedAccessStartTime  = DateTimeOffset.Now - TimeSpan.FromHours(1),
                    SharedAccessExpiryTime = DateTimeOffset.Now + TimeSpan.FromHours(1)
                });

                await table.SetPermissionsAsync(expectedPermissions);

                await Task.Delay(30 * 1000);

                // Generate the sasToken the user should use
                string sasToken = table.GetSharedAccessSignature(null, expectedPermissions.SharedAccessPolicies.First().Key, "AAAA", null, "AAAA", null);

                CloudTable sasTable = new CloudTable(table.Uri, new StorageCredentials(sasToken));

                await sasTable.ExecuteAsync(TableOperation.Insert(new DynamicTableEntity("AAAA", "foo")));

                TableResult result = await sasTable.ExecuteAsync(TableOperation.Retrieve("AAAA", "foo"));

                Assert.IsNotNull(result.Result);

                // revoke table permissions
                await table.SetPermissionsAsync(new TablePermissions());

                await Task.Delay(30 * 1000);

                OperationContext opContext = new OperationContext();
                try
                {
                    await sasTable.ExecuteAsync(TableOperation.Insert(new DynamicTableEntity("AAAA", "foo2")), null, opContext);

                    Assert.Fail();
                }
                catch (Exception)
                {
                    Assert.AreEqual(opContext.LastResult.HttpStatusCode, (int)HttpStatusCode.Forbidden);
                }

                opContext = new OperationContext();
                try
                {
                    result = await sasTable.ExecuteAsync(TableOperation.Retrieve("AAAA", "foo"), null, opContext);

                    Assert.Fail();
                }
                catch (Exception)
                {
                    Assert.AreEqual(opContext.LastResult.HttpStatusCode, (int)HttpStatusCode.Forbidden);
                }
            }
            finally
            {
                table.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
コード例 #25
0
        private static RESTCommand<TableResult> ReplaceImpl(TableOperation operation, CloudTableClient client, string tableName, TableRequestOptions requestOptions)
        {
            RESTCommand<TableResult> replaceCmd = new RESTCommand<TableResult>(client.Credentials, operation.GenerateRequestURI(client.BaseUri, tableName));
            requestOptions.ApplyToStorageCommand(replaceCmd);

            TableResult result = new TableResult() { Result = operation.Entity };
            replaceCmd.RetrieveResponseStream = false;
            replaceCmd.Handler = client.AuthenticationHandler;
            replaceCmd.BuildClient = HttpClientFactory.BuildHttpClient;
            replaceCmd.BuildRequest = (cmd, cnt, ctx) => TableOperationHttpRequestMessageFactory.BuildRequestForTableOperation(cmd.Uri, cmd.ServerTimeoutInSeconds, operation, ctx);
            replaceCmd.PreProcessResponse = (cmd, resp, ex, ctx) => TableOperationHttpResponseParsers.TableOperationPreProcess(result, operation, resp, ex, cmd, ctx);
            replaceCmd.PostProcessResponse = (cmd, resp, ex, ctx) =>
            {
                return Task.Factory.StartNew(() => HttpResponseParsers.ProcessExpectedStatusCodeNoException(HttpStatusCode.NoContent, resp, result, cmd, ex, ctx));
            };
            return replaceCmd;
        }
コード例 #26
0
ファイル: StorageManager.cs プロジェクト: aspnet/WebHooks
        /// <inheritdoc />
        public async Task<TableResult> ExecuteAsync(CloudTable table, TableOperation operation)
        {
            if (table == null)
            {
                throw new ArgumentNullException(nameof(table));
            }
            if (operation == null)
            {
                throw new ArgumentNullException(nameof(operation));
            }

            try
            {
                TableResult result = await table.ExecuteAsync(operation);
                return result;
            }
            catch (Exception ex)
            {
                string errorMessage = GetStorageErrorMessage(ex);
                int statusCode = GetStorageStatusCode(ex);
                string msg = string.Format(CultureInfo.CurrentCulture, AzureStorageResources.StorageManager_OperationFailed, statusCode, errorMessage);
                _logger.Error(msg, ex);

                return new TableResult { HttpStatusCode = statusCode };
            }
        }
コード例 #27
0
        /// <summary>
        /// Deletes the Table.
        /// </summary>
        /// <param name="requestOptions">A <see cref="TableRequestOptions"/> object that specifies execution options, such as retry policy and timeout settings, for the operation.</param>
        /// <param name="operationContext">An <see cref="OperationContext"/> object for tracking the current operation.</param>
        /// <returns>An <see cref="IAsyncAction"/> that represents an asynchronous action.</returns>
        public IAsyncAction DeleteAsync(TableRequestOptions requestOptions, OperationContext operationContext)
        {
            requestOptions = TableRequestOptions.ApplyDefaults(requestOptions, this.ServiceClient);
            operationContext = operationContext ?? new OperationContext();

            DynamicTableEntity tblEntity = new DynamicTableEntity();
            tblEntity.Properties.Add(TableConstants.TableName, new EntityProperty(this.Name));
            TableOperation operation = new TableOperation(tblEntity, TableOperationType.Delete);
            operation.IsTableEntity = true;

            return this.ServiceClient.ExecuteAsync(TableConstants.TableServiceTablesName, operation, requestOptions, operationContext).AsTask().AsAsyncAction();
        }
コード例 #28
0
 private void AssertOperationType(TableOperation operation, TableOperationType operationType)
 {
     var propInfo = typeof(TableOperation).GetProperty("OperationType", BindingFlags.NonPublic | BindingFlags.Instance);
     var type = (TableOperationType)propInfo.GetValue(operation);
     Assert.Equal(operationType, type);
 }
コード例 #29
0
 /// <summary>
 /// Executes the operation on a table.
 /// </summary>
 /// <param name="operation">A <see cref="TableOperation"/> object that represents the operation to perform.</param>
 /// <returns>A <see cref="TableResult"/> containing the result of executing the operation on the table.</returns>
 public IAsyncOperation<TableResult> ExecuteAsync(TableOperation operation)
 {
     return this.ExecuteAsync(operation, null /* RequestOptions */, null /* OperationContext */);
 }
コード例 #30
0
        private static RESTCommand<TableResult> RetrieveImpl(TableOperation operation, CloudTableClient client, string tableName, TableRequestOptions requestOptions)
        {
            RESTCommand<TableResult> retrieveCmd = new RESTCommand<TableResult>(client.Credentials, operation.GenerateRequestURI(client.StorageUri, tableName));
            requestOptions.ApplyToStorageCommand(retrieveCmd);

            TableResult result = new TableResult();
            if (operation.SelectColumns != null && operation.SelectColumns.Count > 0)
            {
                retrieveCmd.Builder = operation.GenerateQueryBuilder(requestOptions.ProjectSystemProperties);
            }

            retrieveCmd.CommandLocationMode = operation.isPrimaryOnlyRetrieve ? CommandLocationMode.PrimaryOnly : CommandLocationMode.PrimaryOrSecondary;
            retrieveCmd.RetrieveResponseStream = true;
            retrieveCmd.ParseError = StorageExtendedErrorInformation.ReadFromStreamUsingODataLib;
            retrieveCmd.BuildRequest = (cmd, uri, builder, cnt, serverTimeout, ctx) => TableOperationHttpRequestMessageFactory.BuildRequestForTableOperation(cmd, uri, builder, serverTimeout, operation, client, cnt, ctx, requestOptions.PayloadFormat.Value, client.GetCanonicalizer(), client.Credentials);
            retrieveCmd.PreProcessResponse = (cmd, resp, ex, ctx) => TableOperationHttpResponseParsers.TableOperationPreProcess(result, operation, resp, ex, cmd, ctx);
            retrieveCmd.PostProcessResponse = (cmd, resp, ctx) =>
                  Task.Run(async () =>
                    {
                        if (resp.StatusCode == HttpStatusCode.NotFound)
                        {
                            return result;
                        }

                        result = await TableOperationHttpResponseParsers.TableOperationPostProcess(result, operation, cmd, resp, ctx, requestOptions, client.AccountName);
                        return result;
                    });
            return retrieveCmd;
        }
コード例 #31
0
 internal static async Task<JsonObject> ExecuteOperationAsync(CloudTable table, TableOperation operation)
 {
     var result = await table.ExecuteAsync(operation).ConfigureAwait(false);
     var entity = result.Result as DynamicTableEntity;
     var jsonObj = entity.ToJsonObject();
     return jsonObj;
 }
コード例 #32
0
        /// <summary>
        /// Helper function for testing the IPAddressOrRange funcitonality for tables
        /// </summary>
        /// <param name="generateInitialIPAddressOrRange">Function that generates an initial IPAddressOrRange object to use. This is expected to fail on the service.</param>
        /// <param name="generateFinalIPAddressOrRange">Function that takes in the correct IP address (according to the service) and returns the IPAddressOrRange object
        /// that should be accepted by the service</param>
        public void CloudTableSASIPAddressHelper(Func<IPAddressOrRange> generateInitialIPAddressOrRange, Func<IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange)
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable table = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                table.Create();
                SharedAccessTablePolicy policy = new SharedAccessTablePolicy()
                {
                    Permissions = SharedAccessTablePermissions.Query,
                    SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                };

                DynamicTableEntity entity = new DynamicTableEntity("PK", "RK", null, new Dictionary<string, EntityProperty>() {{"prop", new EntityProperty(4)}});
                table.Execute(new TableOperation(entity, TableOperationType.Insert));

                // The plan then is to use an incorrect IP address to make a call to the service
                // ensure that we get an error message
                // parse the error message to get my actual IP (as far as the service sees)
                // then finally test the success case to ensure we can actually make requests

                IPAddressOrRange ipAddressOrRange = generateInitialIPAddressOrRange();
                string tableToken = table.GetSharedAccessSignature(policy, null, null, null, null, null, null, ipAddressOrRange);
                StorageCredentials tableSAS = new StorageCredentials(tableToken);
                Uri tableSASUri = tableSAS.TransformUri(table.Uri);
                StorageUri tableSASStorageUri = tableSAS.TransformUri(table.StorageUri);

                CloudTable tableWithSAS = new CloudTable(tableSASUri);
                OperationContext opContext = new OperationContext();
                IPAddress actualIP = null;

                bool exceptionThrown = false;
                TableResult result = null;
                DynamicTableEntity resultEntity = new DynamicTableEntity();
                TableOperation retrieveOp = new TableOperation(resultEntity, TableOperationType.Retrieve);
                retrieveOp.RetrievePartitionKey = entity.PartitionKey;
                retrieveOp.RetrieveRowKey = entity.RowKey;
                try
                {
                    result = tableWithSAS.Execute(retrieveOp, null, opContext);
                }
                catch (StorageException e)
                {
                    string[] parts = e.RequestInformation.HttpStatusMessage.Split(' ');
                    actualIP = IPAddress.Parse(parts[parts.Length - 1].Trim('.'));
                    exceptionThrown = true;
                    Assert.IsNotNull(actualIP);
                }

                Assert.IsTrue(exceptionThrown);
                ipAddressOrRange = generateFinalIPAddressOrRange(actualIP);
                tableToken = table.GetSharedAccessSignature(policy, null, null, null, null, null, null, ipAddressOrRange);
                tableSAS = new StorageCredentials(tableToken);
                tableSASUri = tableSAS.TransformUri(table.Uri);
                tableSASStorageUri = tableSAS.TransformUri(table.StorageUri);


                tableWithSAS = new CloudTable(tableSASUri);
                resultEntity = new DynamicTableEntity();
                retrieveOp = new TableOperation(resultEntity, TableOperationType.Retrieve);
                retrieveOp.RetrievePartitionKey = entity.PartitionKey;
                retrieveOp.RetrieveRowKey = entity.RowKey;
                resultEntity = (DynamicTableEntity)tableWithSAS.Execute(retrieveOp).Result;
    
                Assert.AreEqual(entity.Properties["prop"].PropertyType, resultEntity.Properties["prop"].PropertyType);
                Assert.AreEqual(entity.Properties["prop"].Int32Value.Value, resultEntity.Properties["prop"].Int32Value.Value);
                Assert.IsTrue(table.StorageUri.PrimaryUri.Equals(tableWithSAS.Uri));
                Assert.IsNull(tableWithSAS.StorageUri.SecondaryUri);

                tableWithSAS = new CloudTable(tableSASStorageUri, null);
                resultEntity = new DynamicTableEntity();
                retrieveOp = new TableOperation(resultEntity, TableOperationType.Retrieve);
                retrieveOp.RetrievePartitionKey = entity.PartitionKey;
                retrieveOp.RetrieveRowKey = entity.RowKey;
                resultEntity = (DynamicTableEntity)tableWithSAS.Execute(retrieveOp).Result;
                Assert.AreEqual(entity.Properties["prop"].PropertyType, resultEntity.Properties["prop"].PropertyType);
                Assert.AreEqual(entity.Properties["prop"].Int32Value.Value, resultEntity.Properties["prop"].Int32Value.Value);
                Assert.IsTrue(table.StorageUri.Equals(tableWithSAS.StorageUri));
            }
            finally
            {
                table.DeleteIfExists();
            }
        }
コード例 #33
0
        private static RESTCommand<TableResult> RetrieveImpl(TableOperation operation, CloudTableClient client, string tableName, TableRequestOptions requestOptions)
        {
            RESTCommand<TableResult> retrieveCmd = new RESTCommand<TableResult>(client.Credentials, operation.GenerateRequestURI(client.StorageUri, tableName));
            requestOptions.ApplyToStorageCommand(retrieveCmd);

            TableResult result = new TableResult();
            retrieveCmd.CommandLocationMode = operation.isPrimaryOnlyRetrieve ? CommandLocationMode.PrimaryOnly : CommandLocationMode.PrimaryOrSecondary;
            retrieveCmd.RetrieveResponseStream = true;
            retrieveCmd.Handler = client.AuthenticationHandler;
            retrieveCmd.BuildClient = HttpClientFactory.BuildHttpClient;
            retrieveCmd.BuildRequest = (cmd, uri, builder, cnt, serverTimeout, ctx) => TableOperationHttpRequestMessageFactory.BuildRequestForTableOperation(cmd, uri, builder, serverTimeout, operation, client, cnt, ctx);
            retrieveCmd.PreProcessResponse = (cmd, resp, ex, ctx) => TableOperationHttpResponseParsers.TableOperationPreProcess(result, operation, resp, ex, cmd, ctx);
            retrieveCmd.PostProcessResponse = (cmd, resp, ctx) =>
                  Task.Run(async () =>
                    {
                        if (resp.StatusCode == HttpStatusCode.NotFound)
                        {
                            return result;
                        }

                        result = await TableOperationHttpResponseParsers.TableOperationPostProcess(result, operation, cmd, resp, ctx);
                        return result;
                    });
            return retrieveCmd;
        }
コード例 #34
0
        /// <summary>
        /// Test a table operation on entities inside and outside the given range.
        /// </summary>
        /// <param name="tableName">The name of the table to test.</param>
        /// <param name="startPk">The start partition key range.</param>
        /// <param name="startRk">The start row key range.</param>
        /// <param name="endPk">The end partition key range.</param>
        /// <param name="endRk">The end row key range.</param>
        /// <param name="runOperationDelegate">A delegate with the table operation to test.</param>
        /// <param name="opName">The name of the operation being tested.</param>
        /// <param name="expectSuccess">Whether the operation should succeed on entities within the range.</param>
        private async Task TestOperationWithRange(
            string tableName,
            string startPk,
            string startRk,
            string endPk,
            string endRk,
            Action <BaseEntity, OperationContext> runOperationDelegate,
            string opName,
            bool expectSuccess,
            HttpStatusCode expectedStatusCode,
            bool isRangeQuery)
        {
            CloudTableClient referenceClient = GenerateCloudTableClient();

            string partitionKey = startPk ?? endPk ?? "M";
            string rowKey       = startRk ?? endRk ?? "S";

            // if we expect a success for creation - avoid inserting duplicate entities
            BaseEntity tableEntity = new BaseEntity(partitionKey, rowKey);

            if (expectedStatusCode == HttpStatusCode.Created)
            {
                try
                {
                    tableEntity.ETag = "*";
                    await referenceClient.GetTableReference(tableName).ExecuteAsync(TableOperation.Delete(tableEntity));
                }
                catch (Exception)
                {
                }
            }
            else
            {
                // only for add we should not be adding the entity
                await referenceClient.GetTableReference(tableName).ExecuteAsync(TableOperation.InsertOrReplace(tableEntity));
            }

            if (expectSuccess)
            {
                runOperationDelegate(tableEntity, null);
            }
            else
            {
                TestHelper.ExpectedException(
                    (ctx) => runOperationDelegate(tableEntity, ctx),
                    string.Format("{0} without appropriate permission.", opName),
                    (int)HttpStatusCode.NotFound);
            }

            if (startPk != null)
            {
                tableEntity.PartitionKey = "A";
                if (startPk.CompareTo(tableEntity.PartitionKey) <= 0)
                {
                    Assert.Inconclusive("Test error: partition key for this test must not be less than or equal to \"A\"");
                }

                TestHelper.ExpectedException(
                    (ctx) => runOperationDelegate(tableEntity, ctx),
                    string.Format("{0} before allowed partition key range", opName),
                    (int)HttpStatusCode.NotFound);
                tableEntity.PartitionKey = partitionKey;
            }

            if (endPk != null)
            {
                tableEntity.PartitionKey = "Z";
                if (endPk.CompareTo(tableEntity.PartitionKey) >= 0)
                {
                    Assert.Inconclusive("Test error: partition key for this test must not be greater than or equal to \"Z\"");
                }

                TestHelper.ExpectedException(
                    (ctx) => runOperationDelegate(tableEntity, ctx),
                    string.Format("{0} after allowed partition key range", opName),
                    (int)HttpStatusCode.NotFound);

                tableEntity.PartitionKey = partitionKey;
            }

            if (startRk != null)
            {
                if (isRangeQuery || startPk != null)
                {
                    tableEntity.PartitionKey = startPk;
                    tableEntity.RowKey       = "A";
                    if (startRk.CompareTo(tableEntity.RowKey) <= 0)
                    {
                        Assert.Inconclusive("Test error: row key for this test must not be less than or equal to \"A\"");
                    }

                    TestHelper.ExpectedException(
                        (ctx) => runOperationDelegate(tableEntity, ctx),
                        string.Format("{0} before allowed row key range", opName),
                        (int)HttpStatusCode.NotFound);

                    tableEntity.RowKey = rowKey;
                }
            }

            if (endRk != null)
            {
                if (isRangeQuery || endPk != null)
                {
                    tableEntity.PartitionKey = endPk;
                    tableEntity.RowKey       = "Z";
                    if (endRk.CompareTo(tableEntity.RowKey) >= 0)
                    {
                        Assert.Inconclusive("Test error: row key for this test must not be greater than or equal to \"Z\"");
                    }

                    TestHelper.ExpectedException(
                        (ctx) => runOperationDelegate(tableEntity, ctx),
                        string.Format("{0} after allowed row key range", opName),
                        (int)HttpStatusCode.NotFound);

                    tableEntity.RowKey = rowKey;
                }
            }
        }
コード例 #35
0
        private static RESTCommand<TableResult> RetrieveImpl(TableOperation operation, CloudTableClient client, CloudTable table, TableRequestOptions requestOptions)
        {
            requestOptions.AssertPolicyIfRequired();

            RESTCommand<TableResult> retrieveCmd = new RESTCommand<TableResult>(client.Credentials, operation.GenerateRequestURI(client.StorageUri, table.Name));
            requestOptions.ApplyToStorageCommand(retrieveCmd);

            TableResult result = new TableResult();
            retrieveCmd.CommandLocationMode = operation.isPrimaryOnlyRetrieve ? CommandLocationMode.PrimaryOnly : CommandLocationMode.PrimaryOrSecondary;
            retrieveCmd.RetrieveResponseStream = true;
            retrieveCmd.SignRequest = client.AuthenticationHandler.SignRequest;
            retrieveCmd.ParseError = StorageExtendedErrorInformation.ReadFromStreamUsingODataLib;
            retrieveCmd.BuildRequestDelegate = (uri, builder, timeout, useVersionHeader, ctx) => TableOperationHttpWebRequestFactory.BuildRequestForTableOperation(uri, builder, client.BufferManager, timeout, operation, useVersionHeader, ctx, requestOptions, client.AccountName).Item1;
            retrieveCmd.PreProcessResponse = (cmd, resp, ex, ctx) => TableOperationHttpResponseParsers.TableOperationPreProcess(result, operation, resp, ex);
            retrieveCmd.PostProcessResponse = (cmd, resp, ctx) =>
            {
                if (resp.StatusCode == HttpStatusCode.NotFound)
                {
                    return result;
                }

                result = TableOperationHttpResponseParsers.TableOperationPostProcess(result, operation, cmd, resp, ctx, requestOptions, client.AccountName);
                return result;
            };

            return retrieveCmd;
        }
コード例 #36
0
        internal Task<TableResult> ExecuteAsync(string tableName, TableOperation operation, TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken)
        {
            CommonUtility.AssertNotNull("operation", operation);

            return operation.ExecuteAsync(this, tableName, requestOptions, operationContext, cancellationToken);
        }
コード例 #37
0
        /// <summary>
        /// Executes the operation on a table, using the specified <see cref="TableRequestOptions"/> and <see cref="OperationContext"/>.
        /// </summary>
        /// <param name="operation">A <see cref="TableOperation"/> object that represents the operation to perform.</param>
        /// <param name="requestOptions">A <see cref="TableRequestOptions"/> object that specifies execution options, such as retry policy and timeout settings, for the operation.</param>
        /// <param name="operationContext">An <see cref="OperationContext"/> object for tracking the current operation.</param>
        /// <returns>A <see cref="TableResult"/> containing the result of executing the operation on the table.</returns>
        public IAsyncOperation <TableResult> ExecuteAsync(TableOperation operation, TableRequestOptions requestOptions, OperationContext operationContext)
        {
            CommonUtility.AssertNotNull("operation", operation);

            return(operation.ExecuteAsync(this.ServiceClient, this.Name, requestOptions, operationContext));
        }
コード例 #38
0
 /// <summary>
 /// Runs the given <paramref name="op"/> on the Azure table.
 /// </summary>
 /// <param name="op"><see cref="TableOperation"/></param>
 /// <returns><see cref="Task"/></returns>
 protected virtual async Task<TableResult> Run(string tableName, TableOperation op)
 {
     var table = await GetTable(tableName);
     return await table.ExecuteAsync(op);
 }
コード例 #39
0
        public void TableOperationExecuteRetryAPM()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();

            DynamicTableEntity insertEntity = new DynamicTableEntity("insert test", "foo");

            for (int m = 0; m < 20; m++)
            {
                insertEntity.Properties.Add("prop" + m.ToString(), new EntityProperty(new byte[50 * 1024]));
            }

            TestHelper.ExecuteAPMMethodWithRetry(3,
                                                 new[] {
                //Insert upstream network delay to prevent upload to server @ 1000ms / kb
                PerformanceBehaviors.InsertUpstreamNetworkDelay(10000,
                                                                XStoreSelectors.TableTraffic().IfHostNameContains(tableClient.Credentials.AccountName),
                                                                new BehaviorOptions(2)),
                // After 500 ms return throttle message
                DelayedActionBehaviors.ExecuteAfter(Actions.ThrottleTableRequest,
                                                    100,
                                                    XStoreSelectors.TableTraffic().IfHostNameContains(tableClient.Credentials.AccountName),
                                                    new BehaviorOptions(2))
            },
                                                 (options, opContext, callback, state) => currentTable.BeginExecute(TableOperation.Insert(insertEntity), (TableRequestOptions)options, opContext, callback, state),
                                                 (res) => currentTable.EndExecute(res));
        }
コード例 #40
0
        private static RESTCommand<TableResult> ReplaceImpl(TableOperation operation, CloudTableClient client, string tableName, TableRequestOptions requestOptions)
        {
            RESTCommand<TableResult> replaceCmd = new RESTCommand<TableResult>(client.Credentials, operation.GenerateRequestURI(client.StorageUri, tableName));
            requestOptions.ApplyToStorageCommand(replaceCmd);

            TableResult result = new TableResult() { Result = operation.Entity };
            replaceCmd.RetrieveResponseStream = false;
            replaceCmd.ParseError = StorageExtendedErrorInformation.ReadFromStreamUsingODataLib;
            replaceCmd.BuildRequest = (cmd, uri, builder, cnt, serverTimeout, ctx) => TableOperationHttpRequestMessageFactory.BuildRequestForTableOperation(cmd, uri, builder, serverTimeout, operation, client, cnt, ctx, requestOptions.PayloadFormat.Value, client.GetCanonicalizer(), client.Credentials);
            replaceCmd.PreProcessResponse = (cmd, resp, ex, ctx) => TableOperationHttpResponseParsers.TableOperationPreProcess(result, operation, resp, ex, cmd, ctx);

            return replaceCmd;
        }
コード例 #41
0
        /// <summary>
        /// Test point queries entities inside and outside the given range.
        /// </summary>
        /// <param name="testClient">The table client to test.</param>
        /// <param name="tableName">The name of the table to test.</param>
        /// <param name="accessPermissions">The access permissions of the table client.</param>
        /// <param name="startPk">The start partition key range.</param>
        /// <param name="startRk">The start row key range.</param>
        /// <param name="endPk">The end partition key range.</param>
        /// <param name="endRk">The end row key range.</param>
        private async Task TestPointQuery(
            CloudTableClient testClient,
            string tableName,
            SharedAccessTablePermissions accessPermissions,
            string startPk,
            string startRk,
            string endPk,
            string endRk)
        {
            bool expectSuccess = (accessPermissions & SharedAccessTablePermissions.Query) != 0;

            Action <BaseEntity, OperationContext> queryDelegate = (tableEntity, ctx) =>
            {
                Task <TableResult> retrieveTask = testClient.GetTableReference(tableName).ExecuteAsync(TableOperation.Retrieve <BaseEntity>(tableEntity.PartitionKey, tableEntity.RowKey), null, ctx).AsTask();

                retrieveTask.Wait();

                if (expectSuccess)
                {
                    Assert.IsNotNull(retrieveTask.Result.Result);
                }
                else
                {
                    Assert.AreEqual(ctx.LastResult.HttpStatusCode, (int)HttpStatusCode.OK);
                }
            };


            // Perform test
            await TestOperationWithRange(
                tableName,
                startPk,
                startRk,
                endPk,
                endRk,
                queryDelegate,
                "point query",
                expectSuccess,
                expectSuccess?HttpStatusCode.OK : HttpStatusCode.NotFound);
        }
コード例 #42
0
        private static RESTCommand<TableResult> RetrieveImpl(TableOperation operation, CloudTableClient client, CloudTable table, TableRequestOptions requestOptions)
        {
            requestOptions.AssertPolicyIfRequired();

            RESTCommand<TableResult> retrieveCmd = new RESTCommand<TableResult>(client.Credentials, operation.GenerateRequestURI(client.StorageUri, table.Name));
            requestOptions.ApplyToStorageCommand(retrieveCmd);

            TableResult result = new TableResult();
            if (operation.SelectColumns != null && operation.SelectColumns.Count > 0)
            {
                // If encryption policy is set, then add the encryption metadata column to Select columns in order to be able to decrypt properties.
                if (requestOptions.EncryptionPolicy != null)
                {
                    operation.SelectColumns.Add(Constants.EncryptionConstants.TableEncryptionKeyDetails);
                    operation.SelectColumns.Add(Constants.EncryptionConstants.TableEncryptionPropertyDetails);
                }

                retrieveCmd.Builder = operation.GenerateQueryBuilder(requestOptions.ProjectSystemProperties);
            }

            retrieveCmd.CommandLocationMode = operation.isPrimaryOnlyRetrieve ? CommandLocationMode.PrimaryOnly : CommandLocationMode.PrimaryOrSecondary;
            retrieveCmd.RetrieveResponseStream = true;
            retrieveCmd.SignRequest = client.AuthenticationHandler.SignRequest;
            retrieveCmd.ParseError = StorageExtendedErrorInformation.ReadFromStreamUsingODataLib;
            retrieveCmd.BuildRequestDelegate = (uri, builder, timeout, useVersionHeader, ctx) => TableOperationHttpWebRequestFactory.BuildRequestForTableOperation(uri, builder, client.BufferManager, timeout, operation, useVersionHeader, ctx, requestOptions, client.AccountName).Item1;
            retrieveCmd.PreProcessResponse = (cmd, resp, ex, ctx) => TableOperationHttpResponseParsers.TableOperationPreProcess(result, operation, resp, ex);
            retrieveCmd.PostProcessResponse = (cmd, resp, ctx) =>
            {
                if (resp.StatusCode == HttpStatusCode.NotFound)
                {
                    return result;
                }

                result = TableOperationHttpResponseParsers.TableOperationPostProcess(result, operation, cmd, resp, ctx, requestOptions, client.AccountName);
                return result;
            };

            return retrieveCmd;
        }
コード例 #43
0
ファイル: Program.cs プロジェクト: takekazuomi/WAAC201202
 public static Task<TableResult> ExecuteAsync(this CloudTable cloudTable, TableOperation operation, TableRequestOptions requestOptions = null, OperationContext operationContext = null, object state = null)
 {
     return Task.Factory.FromAsync<TableOperation, TableRequestOptions, OperationContext, TableResult>(
         cloudTable.BeginExecute, cloudTable.EndExecute, operation, requestOptions, operationContext, state);
 }
コード例 #44
0
        private void DoEscapeTest(string data, bool useBatch, bool includeKey)
        {
            DynamicTableEntity ent = new DynamicTableEntity(includeKey ? "temp" + data : "temp", Guid.NewGuid().ToString());

            ent.Properties.Add("foo", new EntityProperty(data));

            // Insert
            if (useBatch)
            {
                TableBatchOperation batch = new TableBatchOperation();
                batch.Insert(ent);
                currentTable.ExecuteBatch(batch);
            }
            else
            {
                currentTable.Execute(TableOperation.Insert(ent));
            }

            // Retrieve
            TableResult res = null;

            if (useBatch)
            {
                TableBatchOperation batch = new TableBatchOperation();
                batch.Retrieve(ent.PartitionKey, ent.RowKey);
                res = (currentTable.ExecuteBatch(batch))[0];
            }
            else
            {
                res = currentTable.Execute(TableOperation.Retrieve(ent.PartitionKey, ent.RowKey));
            }

            // Check equality
            DynamicTableEntity retrievedEntity = res.Result as DynamicTableEntity;

            Assert.IsNotNull(retrievedEntity);
            Assert.AreEqual(ent.PartitionKey, retrievedEntity.PartitionKey);
            Assert.AreEqual(ent.RowKey, retrievedEntity.RowKey);
            Assert.AreEqual(ent.ETag, retrievedEntity.ETag);
            Assert.AreEqual(ent.Properties.Count, retrievedEntity.Properties.Count);
            Assert.AreEqual(ent.Properties["foo"], retrievedEntity.Properties["foo"]);

            // Query using data filter
            TableQuery query = new TableQuery();

            query.Where(string.Format(
                            "(PartitionKey eq \'{0}\') and (RowKey eq \'{1}\') and (foo eq \'{2}\')",
                            ent.PartitionKey,
                            ent.RowKey,
                            data.Replace("\'", "\'\'")));

            retrievedEntity = currentTable.ExecuteQuery(query).Single();

            Assert.IsNotNull(retrievedEntity);
            Assert.AreEqual(ent.PartitionKey, retrievedEntity.PartitionKey);
            Assert.AreEqual(ent.RowKey, retrievedEntity.RowKey);
            Assert.AreEqual(ent.ETag, retrievedEntity.ETag);
            Assert.AreEqual(ent.Properties.Count, retrievedEntity.Properties.Count);
            Assert.AreEqual(ent.Properties["foo"], retrievedEntity.Properties["foo"]);

            // Merge
            ent.Properties.Add("foo2", new EntityProperty("bar2"));

            if (useBatch)
            {
                TableBatchOperation batch = new TableBatchOperation();
                batch.Merge(ent);
                currentTable.ExecuteBatch(batch);
            }
            else
            {
                currentTable.Execute(TableOperation.Merge(ent));
            }

            // Retrieve
            if (useBatch)
            {
                TableBatchOperation batch = new TableBatchOperation();
                batch.Retrieve(ent.PartitionKey, ent.RowKey);
                res = (currentTable.ExecuteBatch(batch))[0];
            }
            else
            {
                res = currentTable.Execute(TableOperation.Retrieve(ent.PartitionKey, ent.RowKey));
            }

            retrievedEntity = res.Result as DynamicTableEntity;
            Assert.AreEqual(ent.PartitionKey, retrievedEntity.PartitionKey);
            Assert.AreEqual(ent.RowKey, retrievedEntity.RowKey);
            Assert.AreEqual(ent.ETag, retrievedEntity.ETag);
            Assert.AreEqual(ent.Properties.Count, retrievedEntity.Properties.Count);
            Assert.AreEqual(ent.Properties["foo"], retrievedEntity.Properties["foo"]);

            // Replace
            ent.Properties.Remove("foo2");
            ent.Properties.Add("foo3", new EntityProperty("bar3"));

            if (useBatch)
            {
                TableBatchOperation batch = new TableBatchOperation();
                batch.Replace(ent);
                currentTable.ExecuteBatch(batch);
            }
            else
            {
                currentTable.Execute(TableOperation.Replace(ent));
            }

            // Retrieve
            if (useBatch)
            {
                TableBatchOperation batch = new TableBatchOperation();
                batch.Retrieve(ent.PartitionKey, ent.RowKey);
                res = (currentTable.ExecuteBatch(batch))[0];
            }
            else
            {
                res = currentTable.Execute(TableOperation.Retrieve(ent.PartitionKey, ent.RowKey));
            }

            retrievedEntity = res.Result as DynamicTableEntity;
            Assert.AreEqual(ent.PartitionKey, retrievedEntity.PartitionKey);
            Assert.AreEqual(ent.RowKey, retrievedEntity.RowKey);
            Assert.AreEqual(ent.ETag, retrievedEntity.ETag);
            Assert.AreEqual(ent.Properties.Count, retrievedEntity.Properties.Count);
            Assert.AreEqual(ent.Properties["foo"], retrievedEntity.Properties["foo"]);
        }
コード例 #45
0
        internal IAsyncOperation<TableResult> ExecuteAsync(string tableName, TableOperation operation, TableRequestOptions requestOptions, OperationContext operationContext)
        {
            CommonUtility.AssertNotNull("operation", operation);

            return operation.ExecuteAsync(this, tableName, requestOptions, operationContext);
        }
コード例 #46
0
ファイル: CloudTableClient.cs プロジェクト: Ankitvaibs/SM
        internal Task <TableResult> ExecuteAsync(string tableName, TableOperation operation, TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken)
        {
            CommonUtility.AssertNotNull("operation", operation);

            return(operation.ExecuteAsync(this, tableName, requestOptions, operationContext, cancellationToken));
        }