/// <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 void TestTableSasWithRange(
            SharedAccessTablePermissions accessPermissions,
            string startPk,
            string startRk,
            string endPk,
            string endRk)
        {
            TestContext.WriteLine("Testing SAS range: spk={0}; epk={1}; srk={2}; erk={3}", startPk, endPk, startRk, endRk);

            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                table.Create();

                // 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)
                });
                table.SetPermissions(permissions);
                Thread.Sleep(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
                TestPointQuery(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);
                TestPointQuery(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);

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

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

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

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

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

                // Upsert row (replace)
                TestUpsertReplace(identifierSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);
                TestUpsertReplace(explicitSasClient, table.Name, accessPermissions, startPk, startRk, endPk, endRk);
            }
            finally
            {
                table.DeleteIfExists();
            }
        }
示例#2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Table encryption sample");

            // Retrieve storage account information from connection string
            // How to create a storage connection string - https://azure.microsoft.com/en-us/documentation/articles/storage-configure-connection-string/
            CloudStorageAccount storageAccount = EncryptionShared.Utility.CreateStorageAccountFromConnectionString();
            CloudTableClient    client         = storageAccount.CreateCloudTableClient();
            CloudTable          table          = client.GetTableReference(DemoTable + Guid.NewGuid().ToString("N"));

            try
            {
                table.Create();

                // Create the IKey used for encryption.
                RsaKey key = new RsaKey("private:key1");

                DynamicTableEntity ent = new DynamicTableEntity()
                {
                    PartitionKey = Guid.NewGuid().ToString(), RowKey = DateTime.Now.Ticks.ToString()
                };
                ent.Properties.Add("EncryptedProp1", new EntityProperty(string.Empty));
                ent.Properties.Add("EncryptedProp2", new EntityProperty("bar"));
                ent.Properties.Add("NotEncryptedProp", new EntityProperty(1234));

                // This is used to indicate whether a property should be encrypted or not given the partition key, row key,
                // and the property name.
                Func <string, string, string, bool> encryptionResolver = (pk, rk, propName) =>
                {
                    if (propName.StartsWith("EncryptedProp"))
                    {
                        return(true);
                    }

                    return(false);
                };

                TableRequestOptions insertOptions = new TableRequestOptions()
                {
                    EncryptionPolicy = new TableEncryptionPolicy(key, null),

                    EncryptionResolver = encryptionResolver
                };

                // Insert Entity
                Console.WriteLine("Inserting the encrypted entity.");
                table.Execute(TableOperation.Insert(ent), insertOptions, null);

                // For retrieves, a resolver can be set up that will help pick the key based on the key id.
                LocalResolver resolver = new LocalResolver();
                resolver.Add(key);

                TableRequestOptions retrieveOptions = new TableRequestOptions()
                {
                    EncryptionPolicy = new TableEncryptionPolicy(null, resolver)
                };

                // Retrieve Entity
                Console.WriteLine("Retrieving the encrypted entity.");
                TableOperation operation = TableOperation.Retrieve(ent.PartitionKey, ent.RowKey);
                TableResult    result    = table.Execute(operation, retrieveOptions, null);

                Console.WriteLine("Press enter key to exit");
                Console.ReadLine();
            }
            finally
            {
                table.DeleteIfExists();
            }
        }
示例#3
0
 private static void DeleteAzureStorageTable()
 {
     table.DeleteIfExists();
     Console.WriteLine("Table Deleted");
 }
示例#4
0
 public void Dispose()
 {
     _cloudTable.DeleteIfExists();
 }
示例#5
0
        /*
         *  https://docs.microsoft.com/en-us/azure/storage/storage-dotnet-how-to-use-tables
         */

        /// <summary>Does examples of basic actions on azure tables</summary>
        /// <param name="ConfigurationConnectionId">The name of the connection definition</param>
        public static void ExampleOfAzureTables(string ConfigurationConnectionId = "example")
        {
            #region Create a table

            /*
             *  Entities map to C# objects by using a custom class derived from TableEntity.
             *  To add an entity to a table, create a class that defines the properties of your entity.
             *  The following code defines an entity class that uses the customer's first name as the
             *      row key and last name as the partition key.
             *  Together, an entity's partition and row key uniquely identify the entity in the table.
             *  Entities with the same partition key can be queried faster than those with different
             *      partition keys, but using diverse partition keys allows for greater scalability
             *      of parallel operations.
             *  For any property that should be stored in the Table service, the property must be a
             *      public property of a supported type that exposes both setting and retrieving values.
             *  Also, your entity type must expose a parameter-less constructor.
             */

            // Parse the connection string and return a reference to the storage account.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting(ConfigurationConnectionId));

            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Retrieve a reference to the table.
            CloudTable table = tableClient.GetTableReference("people");

            // Create the table if it doesn't exist.
            table.CreateIfNotExists();

            #endregion

            #region Add a single entity to a table

            /*
             * Table operations that involve entities are performed via the CloudTable object
             * that you created earlier in the "Create a table" section. The operation to be
             * performed is represented by a TableOperation object. The following code example
             * shows the creation of the CloudTable object and then a CustomerEntity object.
             * To prepare the operation, a TableOperation object is created to insert the
             * customer entity into the table. Finally, the operation is executed by calling
             * CloudTable.Execute.
             */
            // Create a new customer entity.
            CustomerEntity customer0 = new CustomerEntity("Harp", "Walter");
            customer0.Email       = "*****@*****.**";
            customer0.PhoneNumber = "425-555-0101";

            // Create the TableOperation object that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(customer0);

            // Execute the insert operation.
            table.Execute(insertOperation);

            #endregion

            #region Insert a batch of entities to a table

            /*
             *  You can insert a batch of entities into a table in one write operation. Some other notes on batch operations:
             *
             * You can perform updates, deletes, and inserts in the same single batch operation.
             * A single batch operation can include up to 100 entities.
             * All entities in a single batch operation must have the same partition key.
             * While it is possible to perform a query as a batch operation, it must be the only operation in the batch.
             *
             *  The following code example creates two entity objects and adds each to TableBatchOperation by using the Insert method.
             *  Then, CloudTable.Execute is called to execute the operation.
             */

            // Create the batch operation.
            TableBatchOperation batchOperation = new TableBatchOperation();

            // Create a customer entity and add it to the table.
            CustomerEntity customer1 = new CustomerEntity("Smith", "Jeff");
            customer1.Email       = "*****@*****.**";
            customer1.PhoneNumber = "425-555-0104";

            // Create another customer entity and add it to the table.
            CustomerEntity customer2 = new CustomerEntity("Smith", "Ben");
            customer2.Email       = "*****@*****.**";
            customer2.PhoneNumber = "425-555-0102";

            // Add both customer entities to the batch insert operation.
            batchOperation.Insert(customer1);
            batchOperation.Insert(customer2);

            // Execute the batch operation.
            table.ExecuteBatch(batchOperation);

            #endregion

            #region Retrieve all entities in a partition

            /*
             * To query a table for all entities in a partition, use a TableQuery object.
             * The following code example specifies a filter for entities where 'Smith' is the partition key.
             * This example prints the fields of each entity in the query results to the console.
             */

            // Construct the query operation for all customer entities where PartitionKey="Smith".
            TableQuery <CustomerEntity> query = new TableQuery <CustomerEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "Smith"));

            // Print the fields for each customer.
            foreach (CustomerEntity entity in table.ExecuteQuery(query))
            {
                Console.WriteLine("{0}, {1}\t{2}\t{3}", entity.PartitionKey, entity.RowKey,
                                  entity.Email, entity.PhoneNumber);
            }

            #endregion

            #region Retrieve a range of of entities in partition

            /*
             *  If you don't want to query all the entities in a partition, you can specify a
             *      range by combining the partition key filter with a row key filter.
             *  The following code example uses two filters to get all entities in partition
             *      'Smith' where the row key (first name) starts with a letter earlier than
             *      'E' in the alphabet and then prints the query results.
             */

            // Create the table query.
            TableQuery <CustomerEntity> rangeQuery = new TableQuery <CustomerEntity>().Where(
                TableQuery.CombineFilters(
                    TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "Smith"),
                    TableOperators.And,
                    TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.LessThan, "E")));

            // Loop through the results, displaying information about the entity.
            foreach (CustomerEntity entity in table.ExecuteQuery(rangeQuery))
            {
                Console.WriteLine("{0}, {1}\t{2}\t{3}", entity.PartitionKey, entity.RowKey,
                                  entity.Email, entity.PhoneNumber);
            }

            #endregion

            #region Retrieve a single entity

            /*
             *  You can write a query to retrieve a single, specific entity.
             *  The following code uses TableOperation to specify the customer 'Ben Smith'.
             *  This method returns just one entity rather than a collection, and the
             *      returned value in TableResult.Result is a CustomerEntity object.
             *  Specifying both partition and row keys in a query is the fastest way to
             *      retrieve a single entity from the Table service.
             */

            // Create a retrieve operation that takes a customer entity.
            TableOperation retrieveOperation = TableOperation.Retrieve <CustomerEntity>("Smith", "Ben");

            // Execute the retrieve operation.
            TableResult retrievedResult = table.Execute(retrieveOperation);

            // Print the phone number of the result.
            if (retrievedResult.Result != null)
            {
                Console.WriteLine(((CustomerEntity)retrievedResult.Result).PhoneNumber);
            }
            else
            {
                Console.WriteLine("The phone number could not be retrieved.");
            }

            #endregion

            #region Replace an entity

            /*
             *  To update an entity, retrieve it from the Table service, modify the entity object,
             *      and then save the changes back to the Table service.
             *  The following code changes an existing customer's phone number.
             *  Instead of calling Insert, this code uses Replace.
             *  This causes the entity to be fully replaced on the server, unless the entity on the
             *      server has changed since it was retrieved, in which case the operation will fail.
             *  This failure is to prevent your application from inadvertently overwriting a change
             *      made between the retrieval and update by another component of your application.
             *  The proper handling of this failure is to retrieve the entity again, make your changes
             *      (if still valid), and then perform another Replace operation.
             *  The next section will show you how to override this behavior.
             */

            // Create a retrieve operation that takes a customer entity.
            TableOperation retrieveOperation2 = TableOperation.Retrieve <CustomerEntity>("Smith", "Ben");

            // Execute the operation.
            TableResult retrievedResult2 = table.Execute(retrieveOperation2);

            // Assign the result to a CustomerEntity object.
            CustomerEntity updateEntity = (CustomerEntity)retrievedResult2.Result;

            if (updateEntity != null)
            {
                // Change the phone number.
                updateEntity.PhoneNumber = "425-555-0105";

                // Create the Replace TableOperation.
                TableOperation updateOperation = TableOperation.Replace(updateEntity);

                // Execute the operation.
                table.Execute(updateOperation);

                Console.WriteLine("Entity updated.");
            }
            else
            {
                Console.WriteLine("Entity could not be retrieved.");
            }

            #endregion

            #region Insert-or-replace an entity

            /*
             *  Replace operations will fail if the entity has been changed since it was
             *      retrieved from the server.
             *  Furthermore, you must retrieve the entity from the server first in order
             *      for the Replace operation to be successful.
             *  Sometimes, however, you don't know if the entity exists on the server and
             *      the current values stored in it are irrelevant.
             *  Your update should overwrite them all.
             *  To accomplish this, you would use an InsertOrReplace operation.
             *  This operation inserts the entity if it doesn't exist, or replaces it if
             *      it does, regardless of when the last update was made.
             *  In the following code example, the customer entity for Ben Smith is still
             *      retrieved, but it is then saved back to the server via InsertOrReplace.
             *  Any updates made to the entity between the retrieval and update operations
             *      will be overwritten.
             */

            // Create a retrieve operation that takes a customer entity.
            TableOperation retrieveOperation3 = TableOperation.Retrieve <CustomerEntity>("Smith", "Ben");

            // Execute the operation.
            TableResult retrievedResult3 = table.Execute(retrieveOperation3);

            // Assign the result to a CustomerEntity object.
            CustomerEntity updateEntity3 = (CustomerEntity)retrievedResult3.Result;

            if (updateEntity3 != null)
            {
                // Change the phone number.
                updateEntity3.PhoneNumber = "425-555-1234";

                // Create the InsertOrReplace TableOperation.
                TableOperation insertOrReplaceOperation = TableOperation.InsertOrReplace(updateEntity3);

                // Execute the operation.
                table.Execute(insertOrReplaceOperation);

                Console.WriteLine("Entity was updated.");
            }

            else
            {
                Console.WriteLine("Entity could not be retrieved.");
            }

            #endregion

            #region Query a subset of entity properties

            /*
             *  A table query can retrieve just a few properties from an entity instead of
             *      all the entity properties.
             *  This technique, called projection, reduces bandwidth and can improve query
             *      performance, especially for large entities.
             *  The query in the following code returns only the email addresses of entities
             *      in the table.
             *  This is done by using a query of DynamicTableEntity and also EntityResolver.
             *  You can learn more about projection on the Introducing Upsert and Query
             *      Projection blog post.
             *  Note that projection is not supported on the local storage emulator, so this
             *      code runs only when you're using an account on the Table service.
             */

            // Define the query, and select only the Email property.
            TableQuery <DynamicTableEntity> projectionQuery = new TableQuery <DynamicTableEntity>().Select(new string[] { "Email" });

            // Define an entity resolver to work with the entity after retrieval.
            EntityResolver <string> resolver = (pk, rk, ts, props, etag) => props.ContainsKey("Email") ? props["Email"].StringValue : null;

            foreach (string projectedEmail in table.ExecuteQuery(projectionQuery, resolver, null, null))
            {
                Console.WriteLine(projectedEmail);
            }

            #endregion

            #region Delete an entity

            /*
             *  You can easily delete an entity after you have retrieved it, by using
             *      the same pattern shown for updating an entity.
             *  The following code retrieves and deletes a customer entity.
             */

            // Create a retrieve operation that expects a customer entity.
            TableOperation retrieveOperation4 = TableOperation.Retrieve <CustomerEntity>("Smith", "Ben");

            // Execute the operation.
            TableResult retrievedResult4 = table.Execute(retrieveOperation4);

            // Assign the result to a CustomerEntity.
            CustomerEntity deleteEntity4 = (CustomerEntity)retrievedResult4.Result;

            // Create the Delete TableOperation.
            if (deleteEntity4 != null)
            {
                TableOperation deleteOperation = TableOperation.Delete(deleteEntity4);

                // Execute the operation.
                table.Execute(deleteOperation);

                Console.WriteLine("Entity deleted.");
            }
            else
            {
                Console.WriteLine("Could not retrieve the entity.");
            }

            #endregion

            #region Retrieve entities in pages asynchronously

            /*
             *  If you are reading a large number of entities, and you want to process/display
             *      entities as they are retrieved rather than waiting for them all to return,
             *      you can retrieve entities by using a segmented query.
             *  This example shows how to return results in pages by using the Async-Await
             *      pattern so that execution is not blocked while you're waiting for a large
             *      set of results to return.
             *  For more details on using the Async-Await pattern in .NET,
             *      see Asynchronous programming with Async and Await (C# and Visual Basic).
             */

            // Initialize a default TableQuery to retrieve all the entities in the table.
            TableQuery <CustomerEntity> tableQuery = new TableQuery <CustomerEntity>();

            // Initialize the continuation token to null to start from the beginning of the table.
            TableContinuationToken continuationToken = null;

            do
            {
                // Retrieve a segment (up to 100 entities).
                TableQuerySegment <CustomerEntity> tableQueryResult =
                    //await table.ExecuteQuerySegmentedAsync(tableQuery, continuationToken);
                    table.ExecuteQuerySegmented(tableQuery, continuationToken);

                // Assign the new continuation token to tell the service where to
                // continue on the next iteration (or null if it has reached the end).
                continuationToken = tableQueryResult.ContinuationToken;

                // Print the number of rows retrieved.
                Console.WriteLine("Rows retrieved {0}", tableQueryResult.Results.Count);

                // Loop until a null continuation token is received, indicating the end of the table.
            } while (continuationToken != null);

            #endregion

            #region Delete a table

            /*
             *  Finally, the following code example deletes a table from a storage account.
             *  A table that has been deleted will be unavailable to be re-created for a
             *      period of time following the deletion.
             */

            // Print the number of rows retrieved.
            Console.WriteLine("Removing table {0}, {1}", table.Name, table.Uri);

            // Delete the table it if exists.
            table.DeleteIfExists();

            #endregion
        }
示例#6
0
        public void TableListOperations()
        {
            string PREFIX = Utility.GenNameString("uniqueprefix");

            string[] TABLE_NAMES = new string[] { Utility.GenNameString(PREFIX), Utility.GenNameString(PREFIX), Utility.GenNameString(PREFIX) };

            // PART_EXISTING_NAMES differs only the last element with Table_NAMES
            string[] PARTLY_EXISTING_NAMES = new string[TABLE_NAMES.Length];
            Array.Copy(TABLE_NAMES, PARTLY_EXISTING_NAMES, TABLE_NAMES.Length - 1);
            PARTLY_EXISTING_NAMES[TABLE_NAMES.Length - 1] = Utility.GenNameString(PREFIX);

            string[] MERGED_NAMES = TABLE_NAMES.Union(PARTLY_EXISTING_NAMES).ToArray();
            Array.Sort(MERGED_NAMES);

            bool multiOutput = lang == Language.PowerShell;

            // Generate the comparison data
            Collection <Dictionary <string, object> > comp = new Collection <Dictionary <string, object> >();

            foreach (string name in MERGED_NAMES)
            {
                comp.Add(Utility.GenComparisonData(StorageObjectType.Table, name));
            }

            CloudTableClient tableClient = StorageAccount.CreateCloudTableClient();

            // Check if all the above Tables have been removed
            foreach (string name in MERGED_NAMES)
            {
                CloudTable Table = tableClient.GetTableReference(name);
                Table.DeleteIfExists();
            }

            //--------------1. New operation--------------
            Test.Assert(CommandAgent.NewAzureStorageTable(TABLE_NAMES), Utility.GenComparisonData("NewAzureStorageTable", true));
            // Verification for returned values
            if (multiOutput)
            {
                Test.Assert(CommandAgent.Output.Count == TABLE_NAMES.Count(), "{0} row returned : {1}", TABLE_NAMES.Count(), CommandAgent.Output.Count);
            }

            // Check if all the above tables have been created
            foreach (string name in TABLE_NAMES)
            {
                CloudTable table = tableClient.GetTableReference(name);
                Test.Assert(table.Exists(), "table {0} should exist", name);
            }

            try
            {
                //--------------2. New operation--------------
                Test.Assert(!CommandAgent.NewAzureStorageTable(TABLE_NAMES), Utility.GenComparisonData("NewAzureStorageTable", false));
                // Verification for returned values
                if (multiOutput)
                {
                    Test.Assert(CommandAgent.Output.Count == 0, "0 row returned : {0}", CommandAgent.Output.Count);
                }
                int i = 0;
                foreach (string name in TABLE_NAMES)
                {
                    if (multiOutput)
                    {
                        Test.Assert(CommandAgent.ErrorMessages[i].Contains(String.Format("Table '{0}' already exists.", name)), CommandAgent.ErrorMessages[i]);
                    }
                    else
                    {
                        Test.Assert(CommandAgent.ErrorMessages[0].Contains("The table specified already exists"), CommandAgent.ErrorMessages[0]);
                    }
                    ++i;
                }

                //--------------3. New operation--------------
                Test.Assert(!CommandAgent.NewAzureStorageTable(PARTLY_EXISTING_NAMES), Utility.GenComparisonData("NewAzureStorageTable", false));
                // Verification for returned values
                if (multiOutput)
                {
                    Test.Assert(CommandAgent.Output.Count == 1, "1 row returned : {0}", CommandAgent.Output.Count);
                }

                // Check if all the above tables have been created
                foreach (string name in TABLE_NAMES)
                {
                    CloudTable table = tableClient.GetTableReference(name);
                    Test.Assert(table.Exists(), "table {0} should exist", name);
                }

                //--------------4. Get operation--------------
                if (multiOutput)
                {
                    Test.Assert(CommandAgent.GetAzureStorageTable("*" + PREFIX + "*"), Utility.GenComparisonData("GetAzureStorageTable", true));
                    // Verification for returned values
                    CommandAgent.OutputValidation(StorageAccount.CreateCloudTableClient().ListTables(PREFIX));
                }

                // use Prefix parameter
                Test.Assert(CommandAgent.GetAzureStorageTableByPrefix(PREFIX), Utility.GenComparisonData("GetAzureStorageTableByPrefix", true));
                // Verification for returned values
                CommandAgent.OutputValidation(StorageAccount.CreateCloudTableClient().ListTables(PREFIX));
            }
            finally
            {
                //--------------5. Remove operation--------------
                Test.Assert(CommandAgent.RemoveAzureStorageTable(TABLE_NAMES), Utility.GenComparisonData("RemoveAzureStorageTable", true));
                // Check if all the above tables have been removed
                foreach (string name in TABLE_NAMES)
                {
                    CloudTable table = tableClient.GetTableReference(name);
                    Test.Assert(!table.Exists(), "table {0} should not exist", name);
                }
            }
        }
示例#7
0
        static void Main(string[] args)
        {
            CloudStorageAccount CuentaAlamacenamiento =
                CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("CadenaConexion"));

            CloudTableClient ClienteTablas = CuentaAlamacenamiento.CreateCloudTableClient();

            CloudTable Tabla = ClienteTablas.GetTableReference("Clases");

            Tabla.DeleteIfExists(); /* Eliminar tabla*/

            ///* Listar las tablas */
            //Tabla.CreateIfNotExists(); /* Crea la tabla si no existe */

            //var NombreTablas = ClienteTablas.ListTables();

            ///* var se le asigna el valor retornado en este caso lo especificaomos pero no es necesario*/
            //foreach (CloudTable item in NombreTablas)
            //{
            //    Console.WriteLine(item.Name);
            //}

            ///* Insertar entidades a una tabla */
            //Profesor Profe1 = new Profesor("003", "Profesores");
            //Profe1.NombreProfesor = "Percy Leon";
            //Profe1.NombreAsignatura = "Microcontroladores";

            //Profesor Profe2 = new Profesor("004", "Profesores");
            //Profe2.NombreProfesor = "Victor Leon";
            //Profe2.NombreAsignatura = "Diseño audiovisual";

            //TableOperation InsertProfe1 = TableOperation.Insert(Profe1);
            //TableOperation InsertProfe2 = TableOperation.Insert(Profe2);

            //Tabla.Execute(InsertProfe1);
            //Tabla.Execute(InsertProfe2);

            /* Listar registros de la tabla Clases */
            //TableQuery<Profesor> Consulta = new TableQuery<Profesor>()
            //        .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.GreaterThan, "000"));

            //var ListRegistros = Tabla.ExecuteQuery(Consulta);

            //foreach (Profesor profe in ListRegistros)
            //{
            //    Console.WriteLine("{0}, {1}\t{2}\t{3}", profe.PartitionKey, profe.RowKey, profe.NombreProfesor, profe.NombreAsignatura);
            //}

            ///* Modificar */
            //TableOperation OperacionModificar = TableOperation.Retrieve<Profesor>("002", "Profesores"); /* Select */
            //TableResult ResultadoObtenido = Tabla.Execute(OperacionModificar);
            //Profesor EntidadModificada = (Profesor)ResultadoObtenido.Result;

            ///* Si encuentra el registro */
            //if (EntidadModificada != null)
            //{
            //    EntidadModificada.NombreAsignatura = "Diseño Grafico";
            //    TableOperation OperacionActualizar = TableOperation.Replace(EntidadModificada);
            //    Tabla.Execute(OperacionActualizar);

            //    Console.WriteLine("tu reagistro ha sido modificado");
            //}
            //else
            //{
            //    Console.WriteLine("Tu entidad no existe");
            //}

            /* Eliminar */
            //TableOperation OperacionModificar = TableOperation.Retrieve<Profesor>("002", "Profesores"); /* Select */
            //TableResult ResultadoObtenido = Tabla.Execute(OperacionModificar);
            //Profesor EntidadEliminada = (Profesor)ResultadoObtenido.Result;

            ///* Si encuentra el registro */
            //if (EntidadEliminada != null)
            //{
            //    TableOperation OperacionEliminarr = TableOperation.Delete(EntidadEliminada);
            //    Tabla.Execute(OperacionEliminarr);

            //    Console.WriteLine("tu reagistro ha sido modificado");
            //}
            //else
            //{
            //    Console.WriteLine("Tu entidad no existe");
            //}

            //var ListRegistros = Tabla.ExecuteQuery(Consulta);

            //foreach (Profesor profe in ListRegistros)
            //{
            //    Console.WriteLine("{0}, {1}\t{2}\t{3}", profe.PartitionKey, profe.RowKey, profe.NombreProfesor, profe.NombreAsignatura);
            //}

            Console.WriteLine("Lista de profesores obtenidad con exito");
            Console.ReadLine();
        }
示例#8
0
        /// <summary>
        /// Delete Table if exists
        /// </summary>
        /// <param name="tableName">table name</param>
        public void DeleteTable(string tableName)
        {
            CloudTable tableReference = _tableClient.GetTableReference(tableName);

            tableReference.DeleteIfExists();
        }
示例#9
0
 static void DeleteATable(CloudTable table)
 {
     // Delete the table it if exists.
     table.DeleteIfExists();
 }
 public void DeleteTable()
 {
     table.DeleteIfExists();
 }
示例#11
0
 private void deleteTable()
 {
     _table.DeleteIfExists();
 }
示例#12
0
        //public void InitializeDatabase(ApplicationDbContext db)
        //{
        //    if (db.Database.Exists())
        //    {
        //        //Single user mode not available in Azure SQL
        //        db.Database.Delete();
        //    }
        //    db.Database.Create();
        //    WebSecurity.InitializeDatabaseConnection(
        //        "DefaultConnection",
        //        "Users",
        //        "Id",
        //        "userId",
        //        autoCreateTables: true);
        //    this.Seed(db);
        //    //throw new NotImplementedException();
        //}

        protected override void Seed(ApplicationDbContext db)
        {
            /*if (!WebSecurity.UserExists("*****@*****.**"))
             * {
             *  WebSecurity.CreateUserAndAccount(
             *      "*****@*****.**",
             *      "SandeepJoshi",
             *      new { ADA = false, Active = true });
             * }
             *
             * if (!WebSecurity.UserExists("*****@*****.**"))
             * {
             *  WebSecurity.CreateUserAndAccount(
             *      "*****@*****.**",
             *      "BruceWayne",
             *      new { ADA = false, Active = true });
             * }
             *
             * if (!WebSecurity.UserExists("*****@*****.**"))
             * {
             *  WebSecurity.CreateUserAndAccount(
             *      "*****@*****.**",
             *      "RichardNixon",
             *      new { ADA = true, Active = true });
             * }
             *
             * db.Tags.Add(new Tag { Name = "Abstract" });
             * db.Tags.Add(new Tag { Name = "Anime" });
             * db.Tags.Add(new Tag { Name = "Music" });
             * db.Tags.Add(new Tag { Name = "Nature" });
             * db.Tags.Add(new Tag { Name = "Sports" });
             *
             * if (!Roles.RoleExists("User"))
             *  Roles.CreateRole("User");
             * if (!Roles.RoleExists("Admin"))
             *  Roles.CreateRole("Admin");
             * if (!Roles.RoleExists("Approver"))
             *  Roles.CreateRole("Approver");
             *
             * db.SaveChanges();
             *
             * if (!Roles.GetRolesForUser("*****@*****.**").Contains("Approver"))
             * Roles.AddUserToRole("*****@*****.**", "Approver");
             *
             * if (!Roles.GetRolesForUser("*****@*****.**").Contains("Admin"))
             *  Roles.AddUserToRole("*****@*****.**", "Admin");
             *
             * if (!Roles.GetRolesForUser("*****@*****.**").Contains("User"))
             *  Roles.AddUserToRole("*****@*****.**", "User");
             */



            RoleStore <IdentityRole>    roleStore = new RoleStore <IdentityRole>(db);
            UserStore <ApplicationUser> userStore = new UserStore <ApplicationUser>(db);

            RoleManager <IdentityRole>    rm = new RoleManager <IdentityRole>(roleStore);
            UserManager <ApplicationUser> um = new UserManager <ApplicationUser>(userStore);

            IdentityResult  ir;
            ApplicationUser Sandeep = createUser("*****@*****.**");
            ApplicationUser Batman  = createUser("*****@*****.**");
            ApplicationUser nixon   = createUser("*****@*****.**");
            ApplicationUser super   = createUser("*****@*****.**");

            //Flush Validation queue
            ValidationQueue.flush();

            //Delete previous user queues
            QueueManager.deleteQueues();

            ir = um.Create(Sandeep, "SandeepJoshi");
            Sandeep.addQueue();
            ir = um.Create(Batman, "BruceWayne");
            Batman.addQueue();
            ir = um.Create(nixon, "RichardNixon");
            nixon.addQueue();
            ir = um.Create(super, "ClarkKent");
            super.addQueue();

            rm.Create(new IdentityRole("User"));
            if (!um.IsInRole(Batman.Id, "User"))
            {
                um.AddToRole(Batman.Id, "User");
            }

            if (!um.IsInRole(nixon.Id, "User"))
            {
                um.AddToRole(nixon.Id, "User");
            }

            if (!um.IsInRole(Sandeep.Id, "User"))
            {
                um.AddToRole(Sandeep.Id, "User");
            }

            rm.Create(new IdentityRole("Admin"));
            if (!um.IsInRole(Sandeep.Id, "Admin"))
            {
                um.AddToRole(Sandeep.Id, "Admin");
            }

            rm.Create(new IdentityRole("Approver"));
            if (!um.IsInRole(Batman.Id, "Approver"))
            {
                um.AddToRole(Batman.Id, "Approver");
            }

            rm.Create(new IdentityRole("Supervisor"));
            if (!um.IsInRole(super.Id, "Supervisor"))
            {
                um.AddToRole(super.Id, "Supervisor");
            }

            db.Tags.Add(new Tag {
                Name = "Abstract"
            });
            db.Tags.Add(new Tag {
                Name = "Anime"
            });
            db.Tags.Add(new Tag {
                Name = "Music"
            });
            db.Tags.Add(new Tag {
                Name = "Nature"
            });
            db.Tags.Add(new Tag {
                Name = "Sports"
            });

            db.SaveChanges();

            db.Images.Add(new Image
            {
                Caption     = "Pink Floyd",
                Description = "Music gods",
                DateTaken   = new DateTime(2015, 01, 01),
                Userid      = Sandeep.Id,
                TagId       = BaseController.getIdForTag("Music"), //Convert this to method to get Tag id from name
                Approved    = true,
                Validated   = true
            });

            //upload image to blob
            //HttpPostedFileBase postedFile = new HttpPostedFileBase();
            //HttpServerUtilityBase server = null;
            //FileStream f = new FileStream((@"~/Images/PinkFloyd.jpg"), FileMode.Open, FileAccess.Read);
            //postedFile.InputStream.CopyTo(f);
            //f.Close();
            //ImageStorage.SaveFile(server, postedFile, 1);

            CloudStorageAccount account = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));
            CloudBlobClient    client    = account.CreateCloudBlobClient();
            CloudBlobContainer container = client.GetContainerReference(ImageStorage.CONTAINER);
            CloudBlockBlob     blob      = container.GetBlockBlobReference(ImageStorage.FilePath(null, 1));

            try
            {
                using (var file = System.IO.File.OpenRead(@"C:\Users\joshi\Documents\Visual Studio 2015\Projects\ImageSharingWithCloudStorage\ImageSharingWithCloudStorage\Images\PinkFloyd.jpg"))
                {
                    blob.UploadFromStream(file);
                    //Add it in the user queue

                    //Add it in the validation queue
                }
            }
            catch (Exception ex)
            {
            }

            CloudTableClient tableClient = account.CreateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference(LogContext.LOG_TABLE_NAME);

            //Delete the table it if exists.
            try
            {
                table.DeleteIfExists();
            }
            catch (Exception ex)
            {
                ///do nothing.. we don't really need to delete this
            }



            //db.Images.Add(new Image
            //{
            //    Caption = "Spike Speagel",
            //    Description = "Cowboy Bebop",
            //    DateTaken = new DateTime(2015, 01, 01),
            //    Userid = Sandeep.Id,
            //    TagId = BaseController.getIdForTag("Anime"),   //Convert this to method to get Tag id from name
            //    Approved = false
            //});

            db.SaveChanges();
            base.Seed(db);

            //LogContext.CreateTable //Should happen on adding image by itself
        }
        public void TableSASConstructors()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                table.Create();

                TableServiceContext context = tableClient.GetTableServiceContext();
                context.AddObject(table.Name, new BaseEntity("PK", "RK"));
                context.SaveChangesWithRetries();

                // 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;
                TableServiceContext sasContext;
                Uri baseUri = new Uri(TestBase.TargetTenantConfig.TableServiceEndpoint);
                int count;

                // 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);
                sasContext = sasClient.GetTableServiceContext();
                count      = sasContext.CreateQuery <BaseEntity>(sasTable.Name).AsTableServiceQuery(sasContext).Execute().Count();
                Assert.AreEqual(1, count);

                // SAS via account constructor
                sasCreds   = new StorageCredentials(sasToken);
                sasAccount = new CloudStorageAccount(sasCreds, null, null, baseUri);
                sasClient  = sasAccount.CreateCloudTableClient();
                sasTable   = sasClient.GetTableReference(table.Name);
                sasContext = sasClient.GetTableServiceContext();
                count      = sasContext.CreateQuery <BaseEntity>(sasTable.Name).AsTableServiceQuery(sasContext).Execute().Count();
                Assert.AreEqual(1, count);

                // SAS via client constructor URI + Creds
                sasCreds   = new StorageCredentials(sasToken);
                sasClient  = new CloudTableClient(baseUri, sasCreds);
                sasContext = sasClient.GetTableServiceContext();
                count      = sasContext.CreateQuery <BaseEntity>(sasTable.Name).AsTableServiceQuery(sasContext).Execute().Count();
                Assert.AreEqual(1, count);

                // SAS via CloudTable constructor Uri + Client
                sasCreds   = new StorageCredentials(sasToken);
                sasTable   = new CloudTable(table.Uri, tableClient);
                sasClient  = sasTable.ServiceClient;
                sasContext = sasClient.GetTableServiceContext();
                count      = sasContext.CreateQuery <BaseEntity>(sasTable.Name).AsTableServiceQuery(sasContext).Execute().Count();
                Assert.AreEqual(1, count);
            }
            finally
            {
                table.DeleteIfExists();
            }
        }
 /// <summary>
 /// Delete the table
 /// </summary>
 public void DeleteTable()
 {
     _cloudTable.DeleteIfExists();
 }
示例#15
0
 public bool DeleteTable <T>()
 {
     table = tableClient.GetTableReference(typeof(T).Name);
     return(table.DeleteIfExists());
 }
示例#16
0
 public virtual void TearDown()
 {
     _table.DeleteIfExists();
 }
示例#17
0
        /// <summary>
        /// Run a bunch of core Table operations. Each operation is run ~100 times to measure latency.
        /// You can swap the endpoint and compare with regular Azure Table storage.
        /// </summary>
        /// <param name="tableClient">The Azure Table storage client</param>
        /// <param name="numIterations">Number of iterations</param>
        public void Run(CloudTableClient tableClient, int numIterations)
        {
            Console.WriteLine("\n");
            Console.WriteLine("Creating Table if it doesn't exist...");

            CloudTable table = tableClient.GetTableReference("People");

            table.DeleteIfExists();
            table.CreateIfNotExists();

            List <CustomerEntity> items = new List <CustomerEntity>();
            Stopwatch             watch = new Stopwatch();

            Console.WriteLine("\n");
            Console.WriteLine("Running inserts: ");
            for (int i = 0; i < numIterations; i++)
            {
                watch.Start();

                CustomerEntity item = new CustomerEntity()
                {
                    PartitionKey = Guid.NewGuid().ToString(),
                    RowKey       = Guid.NewGuid().ToString(),
                    Email        = $"{GetRandomString(6)}@contoso.com",
                    PhoneNumber  = "425-555-0102",
                    Bio          = GetRandomString(1000)
                };

                TableOperation insertOperation = TableOperation.Insert(item);
                table.Execute(insertOperation);
                double latencyInMs = watch.Elapsed.TotalMilliseconds;

                Console.Write($"\r\tInsert #{i + 1} completed in {latencyInMs} ms.");
                items.Add(item);

                watch.Reset();
            }

            Console.WriteLine("\n");
            Console.WriteLine("Running retrieves: ");

            for (int i = 0; i < numIterations; i++)
            {
                watch.Start();

                TableOperation retrieveOperation = TableOperation.Retrieve <CustomerEntity>(items[i].PartitionKey, items[i].RowKey);
                table.Execute(retrieveOperation);
                double latencyInMs = watch.Elapsed.TotalMilliseconds;

                Console.Write($"\r\tRetrieve #{i + 1} completed in {latencyInMs} ms");

                watch.Reset();
            }

            Console.WriteLine("\n");
            Console.WriteLine("Running replace: ");


            for (int i = 0; i < numIterations; i++)
            {
                watch.Start();

                // Same latency as inserts, p99 < 15ms, and p50 < 6ms
                items[i].PhoneNumber = "425-555-5555";
                TableOperation replaceOperation = TableOperation.Replace(items[i]);
                table.Execute(replaceOperation);

                double latencyInMs = watch.Elapsed.TotalMilliseconds;
                Console.Write($"\r\tReplace #{i + 1} completed in {latencyInMs} ms");

                watch.Reset();
            }
        }
示例#18
0
 public static CloudTable DeleteCloudTable(CloudTable table)
 {
     table.DeleteIfExists();
     return(table);
 }
示例#19
0
        public static void Main(string[] args)
        {
            Process currProc = Process.GetCurrentProcess();

            containerName = "testcontainer"; //Guid.NewGuid().ToString("N").ToLower();

            if (args.Length == 0)
            {
                args = new string[7];

                // the number of test iterations
                args[0] = "1";

                // the number of blobs
                args[1] = "10";

                // the number of concurrent test workers.
                args[2] = "2";

                // the blob size in KB
                args[3] = "1024";

                // the number of parallel requests per blob
                args[4] = "1";

                // use https or not
                args[5] = "false";

                // the result folder name
                args[6] = "folder1";
            }

            iterations              = Int32.Parse(args[0]);
            blobs                   = Int32.Parse(args[1]);
            concurrency             = Int32.Parse(args[2]);
            blobSizeInKB            = Int32.Parse(args[3]);
            parallelRequestsPerBlob = Int32.Parse(args[4]);
            useHttps                = bool.Parse(args[5]);
            resultFileFolderName    = args[6];

            if (!Directory.Exists(resultFileFolderName))
            {
                Directory.CreateDirectory(resultFileFolderName);
            }

            resultFile = string.Format(@"{6}\{0}_{1}_{2}_{3}_{4}_{5}.csv", blobSizeInKB, parallelRequestsPerBlob, concurrency, useHttps, iterations, blobs, resultFileFolderName);

            ThreadPool.SetMinThreads(concurrency * parallelRequestsPerBlob, concurrency * parallelRequestsPerBlob);

            accounts = Account.GetStorageAccounts(useHttps);
            ClientRegistry.Init(accounts, accounts[configAccountName]);

            configuration = new ReplicaConfiguration(containerName);
            ClientRegistry.AddConfiguration(configuration);

            if (firstClient)
            {
                // delete configuration blob and tables
                // ReplicaConfiguration.DeleteConfiguration(containerName);
                ConfigurationCloudStore backingStore = new ConfigurationCloudStore(accounts[configAccountName], configuration);
                backingStore.DeleteConfiguration();

                CloudTableClient ConfigurationCloudTableClient = accounts[configAccountName].CreateCloudTableClient();
                CloudTable       slaTable = ConfigurationCloudTableClient.GetTableReference(ConstPool.SLA_CONFIGURATION_TABLE_NAME);
                slaTable.DeleteIfExists();
                slaTable = ConfigurationCloudTableClient.GetTableReference(ConstPool.SESSION_STATE_CONFIGURATION_TABLE_NAME);
                slaTable.DeleteIfExists();

                Console.WriteLine("removed everything, wait 40 seconds ...");
                Thread.Sleep(40000);

                // recreate configuration
                configuration.PrimaryServers.Add("dbtsouthstorage");
                configuration.SyncWithCloud(accounts[configAccountName], false);
                Console.WriteLine("recreated configuration, wait 10 seconds ...");
                Thread.Sleep(10000);
            }
            else
            {
                // retrieve configuration from cloud
                configuration.SyncWithCloud(accounts[configAccountName]);
            }

            if (firstClient)
            {
                slaEngine = new ConsistencySLAEngine(CreateShoppingCartSla1(), configuration);
            }
            else
            {
                slaEngine = new ConsistencySLAEngine(CreateShoppingCartSla2(), configuration);
            }

            blobClient    = accounts["dbtsouthstorage"].CreateCloudBlobClient();
            blobContainer = blobClient.GetContainerReference(containerName);
            blobContainer.CreateIfNotExists();
            capContainer = new CapCloudBlobContainer(blobContainer);

            // Generate random data
            BlobDataBuffer = new byte[1024 * blobSizeInKB];
            Random random = new Random();

            random.NextBytes(BlobDataBuffer);

            //ServiceLevelAgreement sla = CreateShoppingCartSla();

            Stopwatch totalWatch = new Stopwatch();

            totalWatch.Start();
            for (int m = 0; m < concurrency; m++)
            {
                ThreadPool.QueueUserWorkItem((o) =>
                {
                    Interlocked.Increment(ref concurrentWorkers);
                    for (int i = 0; i < iterations; i++)
                    {
                        Console.WriteLine("Running thread " + m + "." + i);
                        Console.WriteLine("concurrent workers: " + concurrentWorkers);
                        try
                        {
                            // do upload blob test.
                            var blobsList = UploadBlob();
                            Console.WriteLine("Upload Finished ...\n");

                            // GET and DELETE.
                            DoGetAndDelete(blobsList);
                            Console.WriteLine("DoGetAndDelete Finished ...\n");

                            configure("client", containerName);
                            Console.WriteLine("Configure Finished ...\n");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.ToString());
                        }
                    }


                    Interlocked.Decrement(ref concurrentWorkers);
                });
            }
            Console.WriteLine("Program: Started to sleep");
            Thread.Sleep(5000);
            while (Interlocked.CompareExchange(ref concurrentWorkers, -1, 0) != -1)
            {
                if (concurrentWorkers < 0)
                {
                    break;
                }
                Console.WriteLine("Waiting for a thread because there are " + concurrentWorkers + " threads.");
                Thread.Sleep(5000);
            }

            Console.WriteLine("Finished execution. ");
            ClientRegistry.GetConfigurationContainer(containerName).Delete();
            blobContainer.DeleteIfExists();

            totalWatch.Stop();
            long totalTimeTaken = totalWatch.ElapsedMilliseconds;

            using (StreamWriter sw = new StreamWriter(resultFile))
            {
                sw.Write(String.Format("Total time taken to run the test in ms : {0}\n\n", totalTimeTaken));
                sw.Write(String.Format("Args:Concurrency: {0} BlobSizeInKB:{1} ParallelRequestsPerBlob:{2} UsingHttps:{3} \n", concurrency, blobSizeInKB, parallelRequestsPerBlob, useHttps));

                // display result
                DisplayResults(sw, "Insert", insertTimes);
                DisplayResults(sw, "Get", getTimes);
                DisplayResults(sw, "Delete", deleteTimes);

                float tmp = 0;
                foreach (SubSLA s in capContainer.SLA)
                {
                    tmp += s.Utility * s.NumberOfHits;
                }

                sw.Write(String.Format("Current utility ", tmp));


                // Display perf results
                PerfMetrics metrics = new PerfMetrics();
                metrics.Update(currProc);
                metrics.Print(sw);
            }

            Console.Read();
        }
 public static void MyClassCleanup()
 {
     currentTable.DeleteIfExists();
 }
示例#21
0
 public void Delete()
 {
     _table.DeleteIfExists();
 }
        public void TableGetSetPermissionTest()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                table.Create();

                TableServiceContext context = tableClient.GetTableServiceContext();
                context.AddObject(table.Name, new BaseEntity("PK", "RK"));
                context.SaveChangesWithRetries();

                TablePermissions expectedPermissions;
                TablePermissions testPermissions;

                // Test new table permissions.
                expectedPermissions = new TablePermissions();
                testPermissions     = table.GetPermissions();
                AssertPermissionsEqual(expectedPermissions, testPermissions);

                // Test setting empty permissions.
                table.SetPermissions(expectedPermissions);
                Thread.Sleep(30 * 1000);
                testPermissions = table.GetPermissions();
                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)
                });

                table.SetPermissions(expectedPermissions);
                Thread.Sleep(30 * 1000);
                testPermissions = table.GetPermissions();
                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)
                });

                table.SetPermissions(expectedPermissions);
                Thread.Sleep(30 * 1000);
                testPermissions = table.GetPermissions();
                AssertPermissionsEqual(expectedPermissions, testPermissions);

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

                table.SetPermissions(expectedPermissions);
                Thread.Sleep(30 * 1000);
                testPermissions = table.GetPermissions();
                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)
                });

                table.SetPermissions(expectedPermissions);
                Thread.Sleep(30 * 1000);
                testPermissions = table.GetPermissions();
                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)
                });

                table.SetPermissions(expectedPermissions);
                Thread.Sleep(30 * 1000);
                testPermissions = table.GetPermissions();
                AssertPermissionsEqual(expectedPermissions, testPermissions);
            }
            finally
            {
                table.DeleteIfExists();
            }
        }
示例#23
0
        /// <summary>
        /// Imports data of DataTable to table storage
        /// </summary>
        /// <param name="dtSheetInfo"></param>
        /// <param name="strSheetName"></param>
        private void ImportDataToTable(System.Data.DataTable dtSheetInfo, string strSheetName)
        {
            var        client = storageAccount.CreateCloudTableClient();
            CloudTable table  = client.GetTableReference(strPIITable);

            Response.Write(new string(' ', 1024));
            Response.Write(String.Format("<div>Deleting existing data"));
            Response.Flush();

            table.DeleteIfExists();

create:
            try
            {
                Response.Write(".");
                Response.Flush();
                table.Create();
            }
            catch (StorageException ex) when(ex.RequestInformation.ExtendedErrorInformation.ErrorCode.Equals(TableErrorCodeStrings.TableBeingDeleted))
            {
                Thread.Sleep(1000);
                goto create;
            }

            Response.Write(String.Format("</div><div>Uploading {0} rows for sheet {1}", dtSheetInfo.Rows.Count, strSheetName.Replace("$", "")));
            Response.Flush();

            // Create a new partition key for this data instead of overwriting old data.
            var partitionKey = strSheetName;

            var batch = new TableBatchOperation();

            for (int j = 0; j < dtSheetInfo.Rows.Count; j++)
            {
                ExcelTableEntity entity = new ExcelTableEntity(partitionKey, (j + 2).ToString("D5"));
                var hasContent          = false;
                for (int i = 0; i < dtSheetInfo.Columns.Count; i++)
                {
                    string strCloName = dtSheetInfo.Columns[i].ColumnName;
                    if (!(dtSheetInfo.Rows[j][i] is DBNull) && (dtSheetInfo.Rows[j][i] != null))
                    {
                        hasContent = true;
                        string strValue = dtSheetInfo.Rows[j][i].ToString().Trim();
                        if (!CheckPropertyExist(strCloName, strValue, entity))
                        {
                            EntityProperty property = entity.ConvertToEntityProperty(strCloName, dtSheetInfo.Rows[j][i]);
                            if (!entity.properties.ContainsKey(strCloName))
                            {
                                entity.properties.Add(strCloName, property);
                            }
                            else
                            {
                                entity.properties[strCloName] = property;
                            }
                        }
                    }
                }

                if (hasContent)
                {
                    batch.Add(TableOperation.InsertOrReplace(entity));
                }

                if (batch.Count >= 100)
                {
                    table.ExecuteBatch(batch);
                    Response.Write(".");
                    Response.Flush();
                    batch.Clear();
                }
            }

            if (batch.Count > 0)
            {
                table.ExecuteBatch(batch);
                Response.Write(".");
                Response.Flush();
            }

            Response.Write("</div><hr/>");
            Response.Flush();
        }
示例#24
0
 public void MyTestCleanup()
 {
     currentTable.DeleteIfExists();
 }
        /// <summary>
        /// remove specified container
        /// </summary>
        /// <param name="tableName">container name</param>
        public void RemoveTable(string tableName)
        {
            CloudTable table = client.GetTableReference(tableName);

            table.DeleteIfExists();
        }
示例#26
0
 public static void DeleteAzureTable(CloudTable table)
 {
     table.DeleteIfExists();
 }
        public void TableSetGetPermissionsAPM()
        {
            CloudTableClient tableClient = GenerateCloudTableClient();
            CloudTable       table       = tableClient.GetTableReference("T" + Guid.NewGuid().ToString("N"));

            try
            {
                table.Create();

                TableServiceContext context = tableClient.GetTableServiceContext();
                context.AddObject(table.Name, new BaseEntity("PK", "RK"));
                context.SaveChangesWithRetries();

                TablePermissions expectedPermissions = new TablePermissions();
                TablePermissions testPermissions     = table.GetPermissions();

                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)
                });

                using (ManualResetEvent evt = new ManualResetEvent(false))
                {
                    IAsyncResult result = null;
                    table.BeginSetPermissions(expectedPermissions, (res) =>
                    {
                        result = res;
                        evt.Set();
                    }, null);

                    evt.WaitOne();

                    table.EndSetPermissions(result);
                }

                Thread.Sleep(30 * 1000);

                using (ManualResetEvent evt = new ManualResetEvent(false))
                {
                    IAsyncResult result = null;
                    table.BeginGetPermissions((res) =>
                    {
                        result = res;
                        evt.Set();
                    }, null);

                    evt.WaitOne();

                    testPermissions = table.EndGetPermissions(result);
                }

                AssertPermissionsEqual(expectedPermissions, testPermissions);
            }
            finally
            {
                table.DeleteIfExists();
            }
        }