Beispiel #1
0
        public static async Task <IActionResult> UpdateTodo(
            [HttpTrigger(AuthorizationLevel.Anonymous, "put", Route = "todo/{id}")] HttpRequest req,
            [Table("todos", Connection = "AzureWebJobsStorage")] Microsoft.WindowsAzure.Storage.Table.CloudTable todoTable,
            ILogger log, string id)
        {
            log.LogInformation($"Updating todo item with Id {id}");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var    updated     = JsonConvert.DeserializeObject <TodoUpdateModel>(requestBody);

            var findOperation = Microsoft.WindowsAzure.Storage.Table.TableOperation.Retrieve <TodoTableEntity>("TODO", id);
            var findResult    = await todoTable.ExecuteAsync(findOperation);

            if (findResult == null)
            {
                return(new NotFoundResult());
            }
            var existingRow = (TodoTableEntity)findResult.Result;

            existingRow.IsCompleted = updated.IsCompleted;
            if (!string.IsNullOrEmpty(updated.TaskDescription))
            {
                existingRow.TaskDescription = updated.TaskDescription;
            }
            var replaceOperation = Microsoft.WindowsAzure.Storage.Table.TableOperation.Replace(existingRow);
            await todoTable.ExecuteAsync(replaceOperation);

            return(new OkObjectResult(existingRow.ToTodo()));
        }
        /// <summary>
        /// Demonstrate the most efficient storage query - the point query - where both partition key and row key are specified. 
        /// </summary>
        /// <param name="table">Sample table name</param>
        /// <param name="partitionKey">Partition key - ie - last name</param>
        /// <param name="rowKey">Row key - ie - first name</param>
        private static async Task<AuditModel> RetrieveEntityUsingPointQueryAsync(CloudTable table, string partitionKey, string rowKey)
        {
            TableOperation retrieveOperation = TableOperation.Retrieve<AuditModel>(partitionKey, rowKey);
            TableResult result = await table.ExecuteAsync(retrieveOperation);
            AuditModel audit = result.Result as AuditModel;

            return audit;
        }
Beispiel #3
0
        private async Task <TableResult> InsertEntity(CloudTable table, WalkToSave entityToSave)
        {
            // Create an entity and set properties
            var lens = new WalkToSave(entityToSave.SubmitterName, entityToSave.WalkName)
            {
                Description   = entityToSave.Description,
                Location      = entityToSave.Location,
                SubmitterName = entityToSave.SubmitterName,
                WalkName      = entityToSave.WalkName,
                Url           = entityToSave.Url
            };
            // Add the entity
            TableOperation insertOrMerge = TableOperation.InsertOrMerge(lens);

            return(await table.ExecuteAsync(insertOrMerge));
        }
Beispiel #4
0
        public static async Task <IActionResult> DeleteTodo(
            [HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "todo/{id}")] HttpRequest req,
            [Table("todos", Connection = "AzureWebJobsStorage")] Microsoft.WindowsAzure.Storage.Table.CloudTable todoTable,
            ILogger log, string id)
        {
            var deleteOperation = Microsoft.WindowsAzure.Storage.Table.TableOperation.Delete(
                new Microsoft.WindowsAzure.Storage.Table.TableEntity()
            {
                PartitionKey = "TODO", RowKey = id, ETag = "*"
            });

            try
            {
                var deletedResult = await todoTable.ExecuteAsync(deleteOperation);
            }
            catch (StorageException e) when(e.RequestInformation.HttpStatusCode == 404)
            {
                return(new NotFoundResult());
            }
            return(new OkResult());
        }
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log, ExecutionContext context)
        {
            string Path = req.Query["Path"].ToString();
            var    sas  = "https://adsgofasttransientstg.blob.core.windows.net/" + Path + "?";

            foreach (var i in req.Query)
            {
                if (i.Key != "Path" && i.Key != "TargetSystemUidInPHI")
                {
                    sas += "&" + i.Key + "=" + i.Value;
                }
            }

            var cloudBlockBlob = new Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob(new Uri(sas));
            await cloudBlockBlob.UploadTextAsync("Hello World");

            //Write to Filelist table so that downstream tasks can be triggered efficiently
            var _storageCredentials  = new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials("?sv=2018-03-28&tn=Filelist&sig=MFbvVgbNLs3UjqAPfU%2BYwQqxcTYwCPnNKCwCUp4XRmo%3D&se=2021-09-06T23%3A15%3A57Z&sp=au");
            var SourceStorageAccount = new Microsoft.WindowsAzure.Storage.CloudStorageAccount(storageCredentials: _storageCredentials, accountName: "adsgofasttransientstg", endpointSuffix: "core.windows.net", useHttps: true);
            var client = SourceStorageAccount.CreateCloudTableClient();

            Microsoft.WindowsAzure.Storage.Table.CloudTable table = client.GetTableReference("Filelist");
            var _dict = new Dictionary <string, EntityProperty>();

            _dict.Add("FilePath", new EntityProperty(Path));
            var _tableEntity    = new DynamicTableEntity(DateTime.UtcNow.ToString("yyyy-MM-dd hh:mm"), Guid.NewGuid().ToString(), null, _dict);
            var _tableOperation = TableOperation.Insert(_tableEntity);

            try
            {
                await table.ExecuteAsync(_tableOperation);
            }
            catch (Microsoft.WindowsAzure.Storage.StorageException ex)
            {
            }
            return(new OkObjectResult(new { }));
        }
Beispiel #6
0
        async Task<CommandResult> DoInsert(CloudTable table, long n, Func<long, EntityNk> entityFactory)
        {
            var e = entityFactory(n);

#if INSERT_OR_REPLACE
            var tableOperation = TableOperation.InsertOrReplace(e);
#else
            var tableOperation = TableOperation.Insert(e);
#endif
            var cresult = new CommandResult { Start = DateTime.UtcNow.Ticks };
            var cbt = 0L;
            var context = GetOperationContext((t) => cbt = t);
            try
            {
                var result = await table.ExecuteAsync(tableOperation, operationContext: context);
                cresult.Elapsed = cbt;
            }
            catch (Exception ex)
            {
                cresult.Elapsed = -1;
                Console.Error.WriteLine("Error DoInsert {0} {1}", n, ex.ToString());
            }
            return cresult;
        }
Beispiel #7
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();
            }
        }
Beispiel #8
0
        /// <summary>
        /// Demonstrate the most efficient storage query - the point query - where both partition key and row key are specified. 
        /// </summary>
        /// <param name="table">Sample table name</param>
        /// <param name="partitionKey">Partition key - ie - last name</param>
        /// <param name="rowKey">Row key - ie - first name</param>
        private static async Task<CustomerEntity> RetrieveEntityUsingPointQueryAsync(CloudTable table, string partitionKey, string rowKey)
        {
            TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>(partitionKey, rowKey);
            TableResult result = await table.ExecuteAsync(retrieveOperation);
            CustomerEntity customer = result.Result as CustomerEntity;
            if (customer != null)
            {
                Console.WriteLine("\t{0}\t{1}\t{2}\t{3}", customer.PartitionKey, customer.RowKey, customer.Email, customer.PhoneNumber);
            }

            return customer;
        }
 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;
 }
        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();
            }
        }
        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.Forbidden);

                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();
            }
        }
Beispiel #12
0
        /// <inheritdoc />
        public async Task<TableResult> ExecuteRetrievalAsync(CloudTable table, string partitionKey, string rowKey)
        {
            if (table == null)
            {
                throw new ArgumentNullException(nameof(table));
            }
            if (partitionKey == null)
            {
                throw new ArgumentNullException(nameof(partitionKey));
            }
            if (rowKey == null)
            {
                throw new ArgumentNullException(nameof(rowKey));
            }

            try
            {
                TableOperation operation = TableOperation.Retrieve(partitionKey, rowKey);
                TableResult result = await table.ExecuteAsync(operation);
                return result;
            }
            catch (Exception ex)
            {
                string msg = string.Format(CultureInfo.CurrentCulture, AzureStorageResources.StorageManager_ErrorRetrieving, ex.Message);
                _logger.Error(msg, ex);
            }
            return null;
        }
        /// <summary>
        /// Tests a table SAS to determine which operations it allows.
        /// </summary>
        /// <param name="sasUri">A string containing a URI with a SAS appended.</param>
        /// <param name="customer">The customer entity.</param>
        /// <returns>A Task object</returns>
        private static async Task TestTableSAS(string sasUri, CustomerEntity customer)
        {
            // Try performing table operations with the SAS provided.
            // Note that the storage account credentials are not required here; the SAS provides the necessary
            // authentication information on the URI.

            // Return a reference to the table using the SAS URI.
            CloudTable table = new CloudTable(new Uri(sasUri));

            // Upsert (add/update) operations: insert an entity.
            // This operation requires both add and update permissions on the SAS.
            try
            {
                // Insert the new entity.
                customer = await InsertOrMergeEntityAsync(table, customer);

                Console.WriteLine("Add operation succeeded for SAS {0}", sasUri);
                Console.WriteLine();
            }
            catch (StorageException e)
            {
                if (e.RequestInformation.HttpStatusCode == 403)
                {
                    Console.WriteLine("Add operation failed for SAS {0}", sasUri);
                    Console.WriteLine("Additional error information: " + e.Message);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                    throw;
                }
            }

            // Read operation: query an entity.
            // This operation requires read permissions on the SAS.
            try
            {
                TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>(customer.PartitionKey, customer.RowKey);
                TableResult result = await table.ExecuteAsync(retrieveOperation);
                CustomerEntity customerRead = result.Result as CustomerEntity;
                if (customerRead != null)
                {
                    Console.WriteLine("\t{0}\t{1}\t{2}\t{3}", customerRead.PartitionKey, customerRead.RowKey, customerRead.Email, customerRead.PhoneNumber);
                }

                Console.WriteLine("Read operation succeeded for SAS {0}", sasUri);
                Console.WriteLine();
            }
            catch (StorageException e)
            {
                if (e.RequestInformation.HttpStatusCode == 403)
                {
                    Console.WriteLine("Read operation failed for SAS {0}", sasUri);
                    Console.WriteLine("Additional error information: " + e.Message);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                    throw;
                }
            }

            // Delete operation: delete an entity.
            try
            {
                TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>(customer.PartitionKey, customer.RowKey);
                TableResult result = await table.ExecuteAsync(retrieveOperation);
                CustomerEntity customerDelete = result.Result as CustomerEntity;
                if (customerDelete != null)
                {
                    await DeleteEntityAsync(table, customerDelete);
                }

                Console.WriteLine("Delete operation succeeded for SAS {0}", sasUri);
                Console.WriteLine();
            }
            catch (StorageException e)
            {
                if (e.RequestInformation.HttpStatusCode == 403)
                {
                    Console.WriteLine("Delete operation failed for SAS {0}", sasUri);
                    Console.WriteLine("Additional error information: " + e.Message);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                    throw;
                }
            }

            Console.WriteLine();
        }
        /// <summary>
        /// Delete an entity
        /// </summary>
        /// <param name="table">Sample table name</param>
        /// <param name="deleteEntity">Entity to delete</param>
        /// <returns>A Task object</returns>
        private static async Task DeleteEntityAsync(CloudTable table, CustomerEntity deleteEntity)
        {
            try
            {
                if (deleteEntity == null)
                {
                    throw new ArgumentNullException("deleteEntity");
                }

                TableOperation deleteOperation = TableOperation.Delete(deleteEntity);
                await table.ExecuteAsync(deleteOperation);
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
        /// <summary>
        /// The Table Service supports two main types of insert operations. 
        ///  1. Insert - insert a new entity. If an entity already exists with the same PK + RK an exception will be thrown.
        ///  2. Replace - replace an existing entity. Replace an existing entity with a new entity. 
        ///  3. Insert or Replace - insert the entity if the entity does not exist, or if the entity exists, replace the existing one.
        ///  4. Insert or Merge - insert the entity if the entity does not exist or, if the entity exists, merges the provided entity properties with the already existing ones.
        /// </summary>
        /// <param name="table">The sample table name</param>
        /// <param name="entity">The entity to insert or merge</param>
        /// <returns>A Task object</returns>
        private static async Task<CustomerEntity> InsertOrMergeEntityAsync(CloudTable table, CustomerEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            try
            {
                // Create the InsertOrReplace table operation
                TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);

                // Execute the operation.
                TableResult result = await table.ExecuteAsync(insertOrMergeOperation);
                CustomerEntity insertedCustomer = result.Result as CustomerEntity;

                return insertedCustomer;
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
        static async Task ClearSagaIndex(ISagaData sagaData, CloudTable table)
        {
            var partitionKey = sagaData.GetType().Name;
            var op = TableOperation.Retrieve<DynamicTableEntity>(partitionKey, $"{sagaData.Id:N}_{sagaData.Revision:0000000000}");

            var operationContext = new OperationContext();
            var tableRequestOptions = new TableRequestOptions { RetryPolicy = new ExponentialRetry() };

            var res = await table.ExecuteAsync(op, tableRequestOptions, operationContext);
            if (res != null && res.Result != null)
            {
                var index = (DynamicTableEntity)res.Result;
                var entries = GetIndicies(index, partitionKey);
                foreach (var e in entries)
                {
                    await table.ExecuteAsync(TableOperation.Delete(e), tableRequestOptions, operationContext);
                }
                await table.ExecuteAsync(TableOperation.Delete(index), tableRequestOptions, operationContext);
            }
        }
        private async Task<PersonEntity> InsertOrMergeEntityAsync(CloudTable table, PersonEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);

            TableResult result = await table.ExecuteAsync(insertOrMergeOperation);
            PersonEntity insertedCustomer = result.Result as PersonEntity;
            return insertedCustomer;
        }
Beispiel #18
0
        private static async Task Backup(dynamic u, CloudTable table)
        {
            try
            {
                if (u.Value.messages.Value != "")
                {
                    var origin = new List<dynamic>();
                    foreach (var s in u.Value.messages)
                    {
                        origin.Add(s);
                    }

                    var sorted = origin.OrderBy(o => o.Value.timestamp).ToList();

                    if (sorted.Count <= RecordRemained) return;

                    for (int i = 0; i < sorted.Count - RecordRemained; i++)
                    {
                        var s = sorted[i];
                        TableChat c = new TableChat(u.Value.room.ID.ToString(), s.Name.ToString())
                        {
                            roomName = u.Value.room.Name,
                            timestamp = s.Value.timestamp,
                            user = s.Value.user,
                            uid = s.Value.uid,
                            message = s.Value.message
                        };
                        TableOperation insertOperation = TableOperation.Insert(c);
                        // Execute the insert operation.
                        var res = await table.ExecuteAsync(insertOperation);
                        if (res.HttpStatusCode == 204)
                        {
                            string url = "ChatRoom/" + u.Name + "/messages/" + s.Name;
                            await _firebaseClient.DeleteAsync(url);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #19
0
        /// <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 };
            }
        }
Beispiel #20
0
        public async Task TableOperationInsertAsync()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();

            // Insert Entity
            DynamicTableEntity ent = new DynamicTableEntity()
            {
                PartitionKey = Guid.NewGuid().ToString(), RowKey = DateTime.Now.Ticks.ToString()
            };

            ent.Properties.Add("foo2", new EntityProperty("bar2"));
            ent.Properties.Add("foo", new EntityProperty("bar"));
            await currentTable.ExecuteAsync(TableOperation.Insert(ent));

            // Retrieve Entity
            TableResult result = await currentTable.ExecuteAsync(TableOperation.Retrieve(ent.PartitionKey, ent.RowKey));

            DynamicTableEntity retrievedEntity = result.Result as DynamicTableEntity;

            Assert.IsNotNull(retrievedEntity);
            Assert.AreEqual(ent.PartitionKey, retrievedEntity.PartitionKey);
            Assert.AreEqual(ent.RowKey, retrievedEntity.RowKey);
            Assert.AreEqual(ent.Properties.Count, retrievedEntity.Properties.Count);
            Assert.AreEqual(ent.Properties["foo"].StringValue, retrievedEntity.Properties["foo"].StringValue);
            Assert.AreEqual(ent.Properties["foo"], retrievedEntity.Properties["foo"]);
            Assert.AreEqual(ent.Properties["foo2"].StringValue, retrievedEntity.Properties["foo2"].StringValue);
            Assert.AreEqual(ent.Properties["foo2"], retrievedEntity.Properties["foo2"]);
        }
        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();
            }
        }
        private static async Task<UrlEntityInternal> GetEntity(string id, string AccessToken, CloudTable tableRef)
        {

            TableResult retrievedResult = null;

            TableOperation retrieveOperation = TableOperation.Retrieve<UrlEntityInternal>( id.Substring(3, 3), id.Substring(6));
            retrievedResult = await tableRef.ExecuteAsync(retrieveOperation);
            var entity = retrievedResult.Result as UrlEntityInternal;

            if (entity == null)
                throw new NotFoundException(id);

            if(AccessToken!=null)
                if (!entity.AccessToken.Equals(AccessToken))
                    throw new UnAuthorizedException(id);

            return entity;
        }
 private async Task UpdateEntity(CloudTable table, DynamicTableEntity entity)
 {
     try
     {
         await table.ExecuteAsync(TableOperation.Merge(entity)).ConfigureAwait(false);
         return;
     }
     catch(StorageException ex)
     {
         if(!Helper.IsError(ex, "EntityTooLarge"))
             throw;
     }
     var serialized = entity.Serialize();
     Configuration
             .GetBlocksContainer()
             .GetBlockBlobReference(entity.GetFatBlobName())
             .UploadFromByteArray(serialized, 0, serialized.Length);
     entity.MakeFat(serialized.Length);
     await table.ExecuteAsync(TableOperation.InsertOrReplace(entity)).ConfigureAwait(false);
 }
Beispiel #24
0
        public async Task TableGetSetPermissionTestAsync()
        {
            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;
                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().AsTask().Wait();
            }
        }
Beispiel #25
0
        /// <summary>
        /// The Table Service supports two main types of insert operations. 
        ///  1. Insert - insert a new entity. If an entity already exists with the same PK + RK an exception will be thrown.
        ///  2. Replace - replace an existing entity. Replace an existing entity with a new entity. 
        ///  3. Insert or Replace - insert the entity if the entity does not exist, or if the entity exists, replace the existing one.
        ///  4. Insert or Merge - insert the entity if the entity does not exist or, if the entity exists, merges the provided entity properties with the already existing ones.
        /// </summary>
        /// <param name="table">The sample table name</param>
        /// <param name="entity">The entity to insert or merge</param>
        /// <returns></returns>
        private static async Task<CustomerEntity> InsertOrMergeEntityAsync(CloudTable table, CustomerEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            // Create the InsertOrReplace  TableOperation
            TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);

            // Execute the operation.
            TableResult result = await table.ExecuteAsync(insertOrMergeOperation);
            CustomerEntity insertedCustomer = result.Result as CustomerEntity;
            return insertedCustomer;
        }
Beispiel #26
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"]);
        }
Beispiel #27
0
        /// <summary>
        /// Delete an entity
        /// </summary>
        /// <param name="table">Sample table name</param>
        /// <param name="deleteEntity">Entity to delete</param>
        private static async Task DeleteEntityAsync(CloudTable table, CustomerEntity deleteEntity)
        {
            if (deleteEntity == null)
            {
                throw new ArgumentNullException("deleteEntity");
            }

            TableOperation deleteOperation = TableOperation.Delete(deleteEntity);
            await table.ExecuteAsync(deleteOperation);
        }
Beispiel #28
0
        private static async Task DeleteAllEntities(CloudTable table)
        {
            TableQuerySegment<DynamicTableEntity> segment = null;

            while (segment == null || segment.ContinuationToken != null)
            {
                segment = await table.ExecuteQuerySegmentedAsync(new TableQuery().Take(100), segment?.ContinuationToken);
                foreach (var entity in segment.Results)
                {
                    await table.ExecuteAsync(TableOperation.Delete(entity));
                }
            }
        }