private async Task DoCloudTableCreateAlreadyExistsAsync(TablePayloadFormat payloadFormat)
        {
            tableClient.DefaultRequestOptions.PayloadFormat = payloadFormat;
            CloudTable       tableRef = tableClient.GetTableReference(GenerateRandomTableName());
            OperationContext ctx      = new OperationContext();

            try
            {
                Assert.IsFalse(await tableRef.ExistsAsync());
                await tableRef.CreateAsync();

                Assert.IsTrue(await tableRef.ExistsAsync());

                // This should throw with no retries
                await tableRef.CreateAsync(null, ctx);

                Assert.Fail();
            }
            catch (Exception)
            {
                Assert.AreEqual(ctx.LastResult.ExtendedErrorInformation.ErrorCode, "TableAlreadyExists");
                TestHelper.AssertNAttempts(ctx, 1);
            }
            finally
            {
                tableRef.DeleteIfExistsAsync().Wait();
            }
        }
Exemple #2
0
        public async Task CloudTableCreateAlreadyExistsAsync()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            string           tableName   = GenerateRandomTableName();
            CloudTable       tableRef    = tableClient.GetTableReference(tableName);
            OperationContext ctx         = new OperationContext();

            try
            {
                Assert.IsFalse(await tableRef.ExistsAsync());
                await tableRef.CreateAsync();

                Assert.IsTrue(await tableRef.ExistsAsync());

                // This should throw with no retries
                await tableRef.CreateAsync(null, ctx);

                Assert.Fail();
            }
            catch (Exception)
            {
                Assert.AreEqual(ctx.LastResult.ExtendedErrorInformation.ErrorCode, "TableAlreadyExists");
                TestHelper.AssertNAttempts(ctx, 1);
            }
            finally
            {
                tableRef.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public void CloudTableCreateAlreadyExistsTask()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            string           tableName   = GenerateRandomTableName();
            CloudTable       tableRef    = tableClient.GetTableReference(tableName);
            OperationContext ctx         = new OperationContext();

            try
            {
                Assert.IsFalse(tableRef.ExistsAsync().Result);
                tableRef.CreateAsync().Wait();
                Assert.IsTrue(tableRef.ExistsAsync().Result);

                // This should throw with no retries
                tableRef.CreateAsync(null, ctx).Wait();

                Assert.Fail();
            }
            catch (AggregateException e)
            {
                StorageException ex = e.InnerException as StorageException;
                if (ex == null)
                {
                    throw;
                }

                Assert.AreEqual(ex.RequestInformation.ExtendedErrorInformation.ErrorCode, "TableAlreadyExists");
                Assert.AreEqual(ex.RequestInformation.HttpStatusCode, (int)HttpStatusCode.Conflict);
                TestHelper.AssertNAttempts(ctx, 1);
            }
            finally
            {
                tableRef.DeleteIfExists();
            }
        }
Exemple #4
0
        public async Task TableSasInvalidOperations()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                await table.CreateAsync();

                // Prepare SAS authentication with full permissions
                string sasString = table.GetSharedAccessSignature(
                    new SharedAccessTablePolicy
                {
                    Permissions            = SharedAccessTablePermissions.Delete,
                    SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30)
                },
                    null,
                    null,
                    null,
                    null,
                    null);

                CloudTableClient sasClient = new CloudTableClient(tableClient.BaseUri, new StorageCredentials(sasString));

                // Construct a valid set of service properties to upload.
                ServiceProperties properties = new ServiceProperties();
                properties.Logging.Version       = "1.0";
                properties.HourMetrics.Version   = "1.0";
                properties.Logging.RetentionDays = 9;
                await sasClient.GetServicePropertiesAsync();

                await sasClient.SetServicePropertiesAsync(properties);

                // Test invalid client operations
                // BUGBUG: ListTables hides the exception. We should fix this
                // TestHelpers.ExpectedException(() => sasClient.ListTablesSegmented(), "List tables with SAS", HttpStatusCode.NotFound);
                TestHelper.ExpectedException((ctx) => sasClient.GetServicePropertiesAsync().AsTask().Wait(), "Get service properties with SAS", (int)HttpStatusCode.NotFound);
                TestHelper.ExpectedException((ctx) => sasClient.SetServicePropertiesAsync(properties).AsTask().Wait(), "Set service properties with SAS", (int)HttpStatusCode.NotFound);

                CloudTable sasTable = sasClient.GetTableReference(table.Name);

                // Verify that creation fails with SAS
                TestHelper.ExpectedException((ctx) => sasTable.CreateAsync(null, ctx).AsTask().Wait(), "Create a table with SAS", (int)HttpStatusCode.NotFound);

                // Create the table.
                await table.CreateAsync();

                // Test invalid table operations
                TestHelper.ExpectedException((ctx) => sasTable.DeleteAsync(null, ctx).AsTask().Wait(), "Delete a table with SAS", (int)HttpStatusCode.NotFound);
                TestHelper.ExpectedException((ctx) => sasTable.GetPermissionsAsync(null, ctx).AsTask().Wait(), "Get ACL with SAS", (int)HttpStatusCode.NotFound);
                TestHelper.ExpectedException((ctx) => sasTable.SetPermissionsAsync(new TablePermissions(), null, ctx).AsTask().Wait(), "Set ACL with SAS", (int)HttpStatusCode.NotFound);
            }
            finally
            {
                table.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemple #5
0
        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
#if !FACADE_NETCORE
            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);
#else
            var q = new TableQuery().Where(TableQuery.GenerateFilterCondition("A", "eq", string.Empty));
            List <DynamicTableEntity> results = (await table.ExecuteQuerySegmentedAsync <DynamicTableEntity>(q, (prk, rk, ts, prop, etag) => new DynamicTableEntity(prk, rk, etag, prop), null)).ToList();
            Assert.AreEqual(1, results.Count);

            List <BaseEntity> pocoresults = (await table.ExecuteQuerySegmentedAsync <BaseEntity>(q, (prk2, rk, ts, prop, etag) => new BaseEntity(prk2, rk), null)).ToList();
            Assert.AreEqual(1, pocoresults.Count);
#endif
        }
Exemple #6
0
        public async Task TableSASConstructorsAsync()
        {
            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")));

                // Prepare SAS authentication with full permissions
                string sasToken = table.GetSharedAccessSignature(
                    new SharedAccessTablePolicy
                {
                    Permissions            = SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Delete | SharedAccessTablePermissions.Query,
                    SharedAccessExpiryTime = DateTimeOffset.Now.AddMinutes(30)
                },
                    null /* accessPolicyIdentifier */,
                    null /* startPk */,
                    null /* startRk */,
                    null /* endPk */,
                    null /* endRk */);

                CloudStorageAccount sasAccount;
                StorageCredentials  sasCreds;
                CloudTableClient    sasClient;
                CloudTable          sasTable;
                Uri baseUri = new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint);

                // SAS via connection string parse
                sasAccount = CloudStorageAccount.Parse(string.Format("TableEndpoint={0};SharedAccessSignature={1}", baseUri.AbsoluteUri, sasToken));
                sasClient  = sasAccount.CreateCloudTableClient();
                sasTable   = sasClient.GetTableReference(table.Name);

                Assert.AreEqual(1, (await sasTable.ExecuteQuerySegmentedAsync(new TableQuery <BaseEntity>(), null)).Results.Count());

                // SAS via account constructor
                sasCreds   = new StorageCredentials(sasToken);
                sasAccount = new CloudStorageAccount(sasCreds, null, null, baseUri, null);
                sasClient  = sasAccount.CreateCloudTableClient();
                sasTable   = sasClient.GetTableReference(table.Name);
                Assert.AreEqual(1, (await sasTable.ExecuteQuerySegmentedAsync(new TableQuery <BaseEntity>(), null)).Results.Count());

                // SAS via client constructor URI + Creds
                sasCreds  = new StorageCredentials(sasToken);
                sasClient = new CloudTableClient(baseUri, sasCreds);
                Assert.AreEqual(1, (await sasTable.ExecuteQuerySegmentedAsync(new TableQuery <BaseEntity>(), null)).Results.Count());

                // SAS via CloudTable constructor Uri + Client
                sasCreds  = new StorageCredentials(sasToken);
                sasTable  = new CloudTable(table.Uri, tableClient.Credentials);
                sasClient = sasTable.ServiceClient;
                Assert.AreEqual(1, (await sasTable.ExecuteQuerySegmentedAsync(new TableQuery <BaseEntity>(), null)).Results.Count());
            }
            finally
            {
                table.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        private async Task DoTableQueryEmptyValueAsync(TablePayloadFormat format)
        {
            CloudTableClient client = GenerateCloudTableClient();

            client.PayloadFormat = format;

            CloudTable table = client.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);
        }
        public void CloudTableDeleteIfExistsRequestOptionsOperationContextCancellationTokenTask()
        {
            CloudTableClient    tableClient       = GenerateCloudTableClient();
            string              tableName         = GenerateRandomTableName();
            CloudTable          table             = tableClient.GetTableReference(tableName);
            TableRequestOptions requestOptions    = new TableRequestOptions();
            OperationContext    operationContext  = new OperationContext();
            CancellationToken   cancellationToken = CancellationToken.None;

            try
            {
                Assert.IsFalse(table.ExistsAsync().Result);
                Assert.IsFalse(table.DeleteIfExistsAsync(requestOptions, operationContext, cancellationToken).Result);
                table.CreateAsync().Wait();
                Assert.IsTrue(table.ExistsAsync().Result);
                Assert.IsTrue(table.DeleteIfExistsAsync(requestOptions, operationContext, cancellationToken).Result);
                Assert.IsFalse(table.ExistsAsync().Result);
                Assert.IsFalse(table.DeleteIfExistsAsync(requestOptions, operationContext, cancellationToken).Result);
                Assert.IsFalse(table.ExistsAsync().Result);
            }
            finally
            {
                table.DeleteIfExistsAsync().Wait();
            }
        }
Exemple #9
0
        public async Task TableUpdateSasTestAsync()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                await table.CreateAsync();

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

                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);
                CloudTable         sasTable = new CloudTable(table.Uri, creds);
                OperationContext   context  = new OperationContext();
                await TestHelper.ExpectedExceptionAsync(
                    async() => await sasTable.ExecuteAsync(TableOperation.Insert(new BaseEntity("PK", "RK2")), null, context),
                    context,
                    "Try to insert an entity when SAS doesn't allow inserts",
                    HttpStatusCode.NotFound);

                await sasTable.ExecuteAsync(TableOperation.Delete(entity));

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

                string sasToken2 = table.GetSharedAccessSignature(policy2, null, null, null, null, null);
                creds.UpdateSASToken(sasToken2);

                sasTable = new CloudTable(table.Uri, creds);

                await sasTable.ExecuteAsync(TableOperation.Insert(new BaseEntity("PK", "RK2")));
            }
            finally
            {
                table.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemple #10
0
        private async Task DoCloudTableCreateAsync(TablePayloadFormat payloadFormat)
        {
            tableClient.DefaultRequestOptions.PayloadFormat = payloadFormat;
            CloudTable tableRef = tableClient.GetTableReference(GenerateRandomTableName());

            try
            {
                Assert.IsFalse(await tableRef.ExistsAsync());
                await tableRef.CreateAsync();

                Assert.IsTrue(await tableRef.ExistsAsync());
            }
            finally
            {
                tableRef.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        public void CloudTableCreateTask()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            string           tableName   = GenerateRandomTableName();
            CloudTable       tableRef    = tableClient.GetTableReference(tableName);

            try
            {
                Assert.IsFalse(tableRef.ExistsAsync().Result);
                tableRef.CreateAsync().Wait();
                Assert.IsTrue(tableRef.ExistsAsync().Result);
            }
            finally
            {
                tableRef.DeleteIfExistsAsync().Wait();
            }
        }
Exemple #12
0
        private async Task DoCloudTableCreateAsync(TablePayloadFormat format)
        {
            CloudTableClient tableClient = GenerateCloudTableClient();

            tableClient.PayloadFormat = format;
            string     tableName = GenerateRandomTableName();
            CloudTable tableRef  = tableClient.GetTableReference(tableName);

            try
            {
                Assert.IsFalse(await tableRef.ExistsAsync());
                await tableRef.CreateAsync();

                Assert.IsTrue(await tableRef.ExistsAsync());
            }
            finally
            {
                tableRef.DeleteIfExistsAsync().Wait();
            }
        }
Exemple #13
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();
            }
        }
        public void CloudTableDeleteIfExistsCancellationTokenTask()
        {
            CloudTableClient  tableClient       = GenerateCloudTableClient();
            string            tableName         = GenerateRandomTableName();
            CloudTable        table             = tableClient.GetTableReference(tableName);
            CancellationToken cancellationToken = CancellationToken.None;

            try
            {
                Assert.IsFalse(table.ExistsAsync().Result);
                Assert.IsFalse(table.DeleteIfExistsAsync(cancellationToken).Result);
                table.CreateAsync().Wait();
                Assert.IsTrue(table.ExistsAsync().Result);
                Assert.IsTrue(table.DeleteIfExistsAsync(cancellationToken).Result);
                Assert.IsFalse(table.ExistsAsync().Result);
                Assert.IsFalse(table.DeleteIfExistsAsync(cancellationToken).Result);
                Assert.IsFalse(table.ExistsAsync().Result);
            }
            finally
            {
                table.DeleteIfExistsAsync().Wait();
            }
        }
Exemple #15
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();
            }
        }
        public static async Task MyClassInitialize(TestContext testContext)
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            currentTable = tableClient.GetTableReference(GenerateRandomTableName());
            await currentTable.CreateIfNotExistsAsync();

            // Bulk Query Entities
            for (int i = 0; i < 15; i++)
            {
                TableBatchOperation batch = new TableBatchOperation();

                for (int j = 0; j < 100; j++)
                {
                    var ent = GenerateRandomEnitity("tables_batch_" + i.ToString());
                    ent.RowKey = string.Format("{0:0000}", j);
                    batch.Insert(ent);
                }

                await currentTable.ExecuteBatchAsync(batch);
            }


            complexEntityTable = tableClient.GetTableReference(GenerateRandomTableName());
            await complexEntityTable.CreateAsync();

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

            for (int m = 0; m < 100; m++)
            {
                ComplexEntity complexEntity = new ComplexEntity(pk, string.Format("{0:0000}", m));
                complexEntity.String = string.Format("{0:0000}", m);
                complexEntity.Binary = new byte[] { 0x01, 0x02, (byte)m };
                complexEntity.BinaryPrimitive = new byte[] { 0x01, 0x02, (byte)m };
                complexEntity.Bool = m % 2 == 0 ? true : false;
                complexEntity.BoolPrimitive = m % 2 == 0 ? true : false;
                complexEntity.Double = m + ((double)m / 100);
                complexEntity.DoublePrimitive = m + ((double)m / 100);
                complexEntity.Int32 = m;
                complexEntity.Int32N = m;
                complexEntity.IntegerPrimitive = m;
                complexEntity.IntegerPrimitiveN = m;
                complexEntity.Int64 = (long)int.MaxValue + m;
                complexEntity.LongPrimitive = (long)int.MaxValue + m;
                complexEntity.LongPrimitiveN = (long)int.MaxValue + m;
                complexEntity.Guid = Guid.NewGuid();

                complexBatch.Insert(complexEntity);

                if (m == 50)
                {
                    middleRef = complexEntity;
                }

                // Add delay to make times unique
                Thread.Sleep(100);
            }

            await complexEntityTable.ExecuteBatchAsync(complexBatch);
        }
        public static async Task MyClassInitialize(TestContext testContext)
        {
            CloudTableClient tableClient = GenerateCloudTableClient();

            currentTable = tableClient.GetTableReference(GenerateRandomTableName());
            await currentTable.CreateIfNotExistsAsync();

            // Bulk Query Entities
            for (int i = 0; i < 15; i++)
            {
                TableBatchOperation batch = new TableBatchOperation();

                for (int j = 0; j < 100; j++)
                {
                    var ent = GenerateRandomEntity("tables_batch_" + i.ToString());
                    ent.RowKey = string.Format("{0:0000}", j);
                    batch.Insert(ent);
                }

                await currentTable.ExecuteBatchAsync(batch);
            }


            complexEntityTable = tableClient.GetTableReference(GenerateRandomTableName());
            await complexEntityTable.CreateAsync();

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

            for (int m = 0; m < 100; m++)
            {
                ComplexEntity complexEntity = new ComplexEntity(pk, string.Format("{0:0000}", m));
                complexEntity.String            = string.Format("{0:0000}", m);
                complexEntity.Binary            = new byte[] { 0x01, 0x02, (byte)m };
                complexEntity.BinaryPrimitive   = new byte[] { 0x01, 0x02, (byte)m };
                complexEntity.Bool              = m % 2 == 0 ? true : false;
                complexEntity.BoolPrimitive     = m % 2 == 0 ? true : false;
                complexEntity.Double            = m + ((double)m / 100);
                complexEntity.DoublePrimitive   = m + ((double)m / 100);
                complexEntity.Int32             = m;
                complexEntity.Int32N            = m;
                complexEntity.IntegerPrimitive  = m;
                complexEntity.IntegerPrimitiveN = m;
                complexEntity.Int64             = (long)int.MaxValue + m;
                complexEntity.LongPrimitive     = (long)int.MaxValue + m;
                complexEntity.LongPrimitiveN    = (long)int.MaxValue + m;
                complexEntity.Guid              = Guid.NewGuid();

                complexBatch.Insert(complexEntity);

                if (m == 50)
                {
                    middleRef = complexEntity;
                }

                // Add delay to make times unique
                Thread.Sleep(100);
            }

            await complexEntityTable.ExecuteBatchAsync(complexBatch);
        }
        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();
            }
        }
Exemple #19
0
        private async Task DoTableGenericQueryOnSupportedTypesAsync(TablePayloadFormat format)
        {
            CloudTableClient client = GenerateCloudTableClient();

            client.DefaultRequestOptions.PayloadFormat = format;

            CloudTable table = client.GetTableReference(GenerateRandomTableName());
            await table.CreateAsync();

            try
            {
                // Setup
                TableBatchOperation batch = new TableBatchOperation();
                string        pk          = Guid.NewGuid().ToString();
                ComplexEntity middleRef   = null;
                for (int m = 0; m < 100; m++)
                {
                    ComplexEntity complexEntity = new ComplexEntity(pk, string.Format("{0:0000}", m));
                    complexEntity.String           = string.Format("{0:0000}", m);
                    complexEntity.Binary           = new byte[] { 0x01, 0x02, (byte)m };
                    complexEntity.BinaryPrimitive  = new byte[] { 0x01, 0x02, (byte)m };
                    complexEntity.Bool             = m % 2 == 0 ? true : false;
                    complexEntity.BoolPrimitive    = m % 2 == 0 ? true : false;
                    complexEntity.Double           = m + ((double)m / 100);
                    complexEntity.DoublePrimitive  = m + ((double)m / 100);
                    complexEntity.Int32            = m;
                    complexEntity.IntegerPrimitive = m;
                    complexEntity.Int64            = (long)int.MaxValue + m;
                    complexEntity.LongPrimitive    = (long)int.MaxValue + m;
                    complexEntity.Guid             = Guid.NewGuid();

                    batch.Insert(complexEntity);

                    if (m == 50)
                    {
                        middleRef = complexEntity;
                    }

                    // Add delay to make times unique
                    await Task.Delay(100);
                }

                await table.ExecuteBatchAsync(batch);

                // 1. Filter on String
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterCondition("String", QueryComparisons.GreaterThanOrEqual, "0050"), 50);

                // 2. Filter on Guid
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForGuid("Guid", QueryComparisons.Equal, middleRef.Guid), 1);

                // 3. Filter on Long
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForLong("Int64", QueryComparisons.GreaterThanOrEqual,
                                                                                       middleRef.LongPrimitive), 50);

                ExecuteQueryAndAssertResults(table, TableQuery.GenerateFilterConditionForLong("LongPrimitive",
                                                                                              QueryComparisons.GreaterThanOrEqual, middleRef.LongPrimitive), 50);

                // 4. Filter on Double
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForDouble("Double", QueryComparisons.GreaterThanOrEqual,
                                                                                         middleRef.Double), 50);

                ExecuteQueryAndAssertResults(table, TableQuery.GenerateFilterConditionForDouble("DoublePrimitive",
                                                                                                QueryComparisons.GreaterThanOrEqual, middleRef.DoublePrimitive), 50);

                // 5. Filter on Integer
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForInt("Int32", QueryComparisons.GreaterThanOrEqual,
                                                                                      middleRef.Int32), 50);

                ExecuteQueryAndAssertResults(table, TableQuery.GenerateFilterConditionForInt("IntegerPrimitive",
                                                                                             QueryComparisons.GreaterThanOrEqual, middleRef.IntegerPrimitive), 50);

                // 6. Filter on Date
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForDate("DateTimeOffset", QueryComparisons.GreaterThanOrEqual,
                                                                                       middleRef.DateTimeOffset), 50);

                // 7. Filter on Boolean
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForBool("Bool", QueryComparisons.Equal, middleRef.Bool), 50);

                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForBool("BoolPrimitive", QueryComparisons.Equal, middleRef.BoolPrimitive),
                                             50);

                // 8. Filter on Binary
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForBinary("Binary", QueryComparisons.Equal, middleRef.Binary), 1);

                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForBinary("BinaryPrimitive", QueryComparisons.Equal,
                                                                                         middleRef.BinaryPrimitive), 1);

                // 9. Filter on Binary GTE
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForBinary("Binary", QueryComparisons.GreaterThanOrEqual,
                                                                                         middleRef.Binary), 50);

                ExecuteQueryAndAssertResults(table, TableQuery.GenerateFilterConditionForBinary("BinaryPrimitive",
                                                                                                QueryComparisons.GreaterThanOrEqual, middleRef.BinaryPrimitive), 50);

                // 10. Complex Filter on Binary GTE
                ExecuteQueryAndAssertResults(table, TableQuery.CombineFilters(
                                                 TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal,
                                                                                    middleRef.PartitionKey),
                                                 TableOperators.And,
                                                 TableQuery.GenerateFilterConditionForBinary("Binary", QueryComparisons.GreaterThanOrEqual,
                                                                                             middleRef.Binary)), 50);

                ExecuteQueryAndAssertResults(table, TableQuery.GenerateFilterConditionForBinary("BinaryPrimitive",
                                                                                                QueryComparisons.GreaterThanOrEqual, middleRef.BinaryPrimitive), 50);
            }
            finally
            {
                table.DeleteIfExistsAsync().Wait();
            }
        }
Exemple #20
0
        public async Task TableRegionalQueryOnSupportedTypesAsync()
        {
            string currentPrimaryLanguage = ApplicationLanguages.PrimaryLanguageOverride;

            ApplicationLanguages.PrimaryLanguageOverride = "tr";

            CloudTableClient client = GenerateCloudTableClient();

            CloudTable table = client.GetTableReference(GenerateRandomTableName());
            await table.CreateAsync();

            try
            {
                // Setup
                TableBatchOperation batch    = new TableBatchOperation();
                string             pk        = Guid.NewGuid().ToString();
                DynamicTableEntity middleRef = null;
                for (int m = 0; m < 100; m++)
                {
                    ComplexEntity complexEntity = new ComplexEntity();
                    complexEntity.String           = string.Format("{0:0000}", m);
                    complexEntity.Binary           = new byte[] { 0x01, 0x02, (byte)m };
                    complexEntity.BinaryPrimitive  = new byte[] { 0x01, 0x02, (byte)m };
                    complexEntity.Bool             = m % 2 == 0 ? true : false;
                    complexEntity.BoolPrimitive    = m % 2 == 0 ? true : false;
                    complexEntity.Double           = m + ((double)m / 100);
                    complexEntity.DoublePrimitive  = m + ((double)m / 100);
                    complexEntity.Int32            = m;
                    complexEntity.IntegerPrimitive = m;
                    complexEntity.Int64            = (long)int.MaxValue + m;
                    complexEntity.LongPrimitive    = (long)int.MaxValue + m;
                    complexEntity.Guid             = Guid.NewGuid();

                    DynamicTableEntity dynEnt = new DynamicTableEntity(pk, string.Format("{0:0000}", m));
                    dynEnt.Properties = complexEntity.WriteEntity(null);
                    batch.Insert(dynEnt);

                    if (m == 50)
                    {
                        middleRef = dynEnt;
                    }

                    // Add delay to make times unique
                    await Task.Delay(100);
                }

                await table.ExecuteBatchAsync(batch);

                // 1. Filter on String
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterCondition("String", QueryComparisons.GreaterThanOrEqual, "0050"), 50);

                // 2. Filter on Guid
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForGuid("Guid", QueryComparisons.Equal, middleRef.Properties["Guid"].GuidValue.Value), 1);

                // 3. Filter on Long
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForLong("Int64", QueryComparisons.GreaterThanOrEqual,
                                                                                       middleRef.Properties["LongPrimitive"].Int64Value.Value), 50);

                ExecuteQueryAndAssertResults(table, TableQuery.GenerateFilterConditionForLong("LongPrimitive",
                                                                                              QueryComparisons.GreaterThanOrEqual, middleRef.Properties["LongPrimitive"].Int64Value.Value), 50);

                // 4. Filter on Double
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForDouble("Double", QueryComparisons.GreaterThanOrEqual,
                                                                                         middleRef.Properties["Double"].DoubleValue.Value), 50);

                ExecuteQueryAndAssertResults(table, TableQuery.GenerateFilterConditionForDouble("DoublePrimitive",
                                                                                                QueryComparisons.GreaterThanOrEqual, middleRef.Properties["DoublePrimitive"].DoubleValue.Value), 50);

                // 5. Filter on Integer
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForInt("Int32", QueryComparisons.GreaterThanOrEqual,
                                                                                      middleRef.Properties["Int32"].Int32Value.Value), 50);

                ExecuteQueryAndAssertResults(table, TableQuery.GenerateFilterConditionForInt("IntegerPrimitive",
                                                                                             QueryComparisons.GreaterThanOrEqual, middleRef.Properties["IntegerPrimitive"].Int32Value.Value), 50);

                // 6. Filter on Date
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForDate("DateTimeOffset", QueryComparisons.GreaterThanOrEqual,
                                                                                       middleRef.Properties["DateTimeOffset"].DateTimeOffsetValue.Value), 50);

                // 7. Filter on Boolean
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForBool("Bool", QueryComparisons.Equal, middleRef.Properties["Bool"].BooleanValue.Value), 50);

                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForBool("BoolPrimitive", QueryComparisons.Equal, middleRef.Properties["BoolPrimitive"].BooleanValue.Value),
                                             50);

                // 8. Filter on Binary
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForBinary("Binary", QueryComparisons.Equal, middleRef.Properties["Binary"].BinaryValue), 1);

                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForBinary("BinaryPrimitive", QueryComparisons.Equal,
                                                                                         middleRef.Properties["BinaryPrimitive"].BinaryValue), 1);

                // 9. Filter on Binary GTE
                ExecuteQueryAndAssertResults(table,
                                             TableQuery.GenerateFilterConditionForBinary("Binary", QueryComparisons.GreaterThanOrEqual,
                                                                                         middleRef.Properties["Binary"].BinaryValue), 50);

                ExecuteQueryAndAssertResults(table, TableQuery.GenerateFilterConditionForBinary("BinaryPrimitive",
                                                                                                QueryComparisons.GreaterThanOrEqual, middleRef.Properties["BinaryPrimitive"].BinaryValue), 50);

                // 10. Complex Filter on Binary GTE
                ExecuteQueryAndAssertResults(table, TableQuery.CombineFilters(
                                                 TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal,
                                                                                    middleRef.PartitionKey),
                                                 TableOperators.And,
                                                 TableQuery.GenerateFilterConditionForBinary("Binary", QueryComparisons.GreaterThanOrEqual,
                                                                                             middleRef.Properties["Binary"].BinaryValue)), 50);

                ExecuteQueryAndAssertResults(table, TableQuery.GenerateFilterConditionForBinary("BinaryPrimitive",
                                                                                                QueryComparisons.GreaterThanOrEqual, middleRef.Properties["BinaryPrimitive"].BinaryValue), 50);
            }
            finally
            {
                ApplicationLanguages.PrimaryLanguageOverride = currentPrimaryLanguage;
                table.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Exemple #21
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();
            }
        }
Exemple #22
0
        /// <summary>
        /// Tests table access permissions with SAS, using a stored policy and using permissions on the URI.
        /// </summary>
        /// <param name="accessPermissions">The permissions 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>
        internal async Task TestTableSasWithRange(
            SharedAccessTablePermissions accessPermissions,
            string startPk,
            string startRk,
            string endPk,
            string endRk)
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                await table.CreateAsync();

                // Set up a policy
                string           identifier  = Guid.NewGuid().ToString();
                TablePermissions permissions = new TablePermissions();
                permissions.SharedAccessPolicies.Add(identifier, new SharedAccessTablePolicy
                {
                    Permissions            = accessPermissions,
                    SharedAccessExpiryTime = DateTimeOffset.Now.AddDays(1)
                });

                await table.SetPermissionsAsync(permissions);

                await Task.Delay(30 * 1000);

                // Prepare SAS authentication using access identifier
                string           sasString           = table.GetSharedAccessSignature(new SharedAccessTablePolicy(), identifier, startPk, startRk, endPk, endRk);
                CloudTableClient identifierSasClient = new CloudTableClient(tableClient.BaseUri, new StorageCredentials(sasString));

                // Prepare SAS authentication using explicit policy
                sasString = table.GetSharedAccessSignature(
                    new SharedAccessTablePolicy
                {
                    Permissions            = accessPermissions,
                    SharedAccessExpiryTime = DateTimeOffset.Now.AddMinutes(30)
                },
                    null,
                    startPk,
                    startRk,
                    endPk,
                    endRk);

                CloudTableClient explicitSasClient = new CloudTableClient(tableClient.BaseUri, new StorageCredentials(sasString));

                // Point query
                await TestPointQuery(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);
                await TestPointQuery(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);

                // Add row
                await TestAdd(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);
                await TestAdd(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);

                // Update row (merge)
                await TestUpdateMerge(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);
                await TestUpdateMerge(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);

                // Update row (replace)
                await TestUpdateReplace(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);
                await TestUpdateReplace(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);

                // Delete row
                await TestDelete(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);
                await TestDelete(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);

                // Upsert row (merge)
                await TestUpsertMerge(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);
                await TestUpsertMerge(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);

                // Upsert row (replace)
                await TestUpsertReplace(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);
                await TestUpsertReplace(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);
            }
            finally
            {
                table.DeleteIfExistsAsync().AsTask().Wait();
            }
        }