csharp Azure存储表

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp Azure存储表相关的知识,希望对你有一定的参考价值。

CloudStorageAccount storageAccount = CloudStorageAccount.Parse("storageConnectionString");

CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
// Also, if you already have a table...
CloudTableClient tableClient = table.ServiceClient;

// Create a table if it doesn't exist already
CloudTable table = tableClient.GetTableReference(tableName);
\!h await table.CreateIfNotExistsAsync()

// Model definition
namespace CosmosTableSamples.Model
{
    using Microsoft.Azure.Cosmos.Table;
    public class CustomerEntity : TableEntity
    {
        public CustomerEntity() {}
        public CustomerEntity(string lastName, string firstName)
        {
            PartitionKey = lastName;
            RowKey = firstName;
        }

        public string Email { get; set; }
        public string PhoneNumber { get; set; }
    }
}

// Create an instance of a customer entity
CustomerEntity customer = new CustomerEntity("Harp", "Walter")
{
    Email = "Walter@contoso.com",
    PhoneNumber = "425-555-0101"
};

// Insert
TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(customer);
\!h TableResult result = await table.ExecuteAsync(insertOrMergeOperation);
customer = result.Result as CustomerEntity;

// Update
customer.PhoneNumber = "425-555-0105";
TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(customer);
\!h TableResult result = await table.ExecuteAsync(insertOrMergeOperation);
customer = result.Result as CustomerEntity;

// Read the updated entity using a point query (use partitionKey & rowKey)
TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>(partitionKey, rowKey);
\!h TableResult result = await table.ExecuteAsync(retrieveOperation);
customer = result.Result as CustomerEntity;
Console.WriteLine("\t{0}\t{1}\t{2}\t{3}", customer.PartitionKey, customer.RowKey, customer.Email, customer.PhoneNumber);

// Delete table
\!h await table.DeleteIfExistsAsync();
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("storageConnectionString");
 
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
 
// Create a table if it doesn't exist already
CloudTable table = tableClient.GetTableReference(tableName);
\!h await table.CreateIfNotExistsAsync()

// Batch operations
TableBatchOperation batchOperation = new TableBatchOperation();
batchOperation.InsertOrMerge(customer); // repeat many times

\!h IList<TableResult> results = await table.ExecuteBatchAsync(batchOperation);
foreach (var res in results)
{
    var customerInserted = res.Result as CustomerEntity;
    Console.WriteLine("\t{0}\t{1}\t{2}", customerInserted.ETag, customerInserted.PartitionKey, customerInserted.RowKey);
}

// Query a range of data within a partition using a simple query
TableQuery<CustomerEntity> rangeQuery = new TableQuery<CustomerEntity>().Where(
    TableQuery.CombineFilters(
        TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey),
        TableOperators.And,
        TableQuery.CombineFilters(
            TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.GreaterThanOrEqual, startRowKey),
            TableOperators.And,
            TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.LessThanOrEqual, endRowKey)
        )
    )
);
        
\!h foreach (CustomerEntity entity in table.ExecuteQuery(rangeQuery))
{
    // ...
}

// Same query, but async, 50 entities at a time
TableContinuationToken token = null;
rangeQuery.TakeCount = 50;
do
{
\!h     TableQuerySegment<CustomerEntity> segment = await table.ExecuteQuerySegmentedAsync(rangeQuery, token);
    token = segment.ContinuationToken;
    foreach (CustomerEntity entity in segment)
    {
        // ...
    }
}
while (token != null);

// Query for all the data within a partition
TableQuery<CustomerEntity> partitionScanQuery = new TableQuery<CustomerEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey));
TableContinuationToken token = null;
do
{
\!h     TableQuerySegment<CustomerEntity> segment = await table.ExecuteQuerySegmentedAsync(partitionScanQuery, token);
    token = segment.ContinuationToken;
    foreach (CustomerEntity entity in segment)
    {
        // ...
    }
}
while (token != null);

// List tables beginning with the specified prefix. Passing in null for the maxResults parameter returns the maximum number of results (up to 5000).
\!h TableResultSegment resultSegment = await tableClient.ListTablesSegmentedAsync(prefix, null, continuationToken, null, null);
foreach (var table in resultSegment.Results)
{
  // ...
}
// Or, all tables synchronously
foreach (var table in tableClient.ListTables())
{
  // ...
}
// Create ad hoc SAS and retrieve token
SharedAccessTablePolicy adHocPolicy = new SharedAccessTablePolicy()
{
    // Permissions enable users to add, update, query, and delete entities in the table.
    SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
    Permissions = SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Update |
        SharedAccessTablePermissions.Query | SharedAccessTablePermissions.Delete
};

// Generate the shared access signature on the table, setting the constraints directly on the signature.
string sasTableToken = table.GetSharedAccessSignature(adHocPolicy, null);

// Retrieve token for a named access policy
string sasTableToken = table.GetSharedAccessSignature(null, storedPolicyName);

// Use SAS token to get a table
CustomerEntity customer = new CustomerEntity("Johnson", "Mary")
{
   Email = "mary@contoso.com",
   PhoneNumber = "425-555-0105"
};
// Return a reference to the table using the SAS URI.
CloudTable table = new CloudTable(new Uri(sasTableToken));
// Then use CRUD as previously, e.g.
TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(customer);
\!h TableResult result = await table.ExecuteAsync(insertOrMergeOperation);
customer = result.Result as CustomerEntity;

// Manage the properties of the Table service
\!h ServiceProperties props = await tableClient.GetServicePropertiesAsync();
props.Logging.LoggingOperations = LoggingOperations.Read | LoggingOperations.Write;
props.Logging.RetentionDays = 5; // etc.
\!h await tableClient.SetServicePropertiesAsync(props);

// CORS
CorsRule corsRule = new CorsRule
{
    AllowedHeaders = new List<string> { "*" },
    AllowedMethods = CorsHttpMethods.Get,
    AllowedOrigins = new List<string> { "*" },
    ExposedHeaders = new List<string> { "*" },
    MaxAgeInSeconds = 3600
};
\!h ServiceProperties serviceProperties = await tableClient.GetServicePropertiesAsync();
serviceProperties.Cors.CorsRules.Add(corsRule);
\!h await tableClient.SetServicePropertiesAsync(serviceProperties);

// Service statistics - only works on RA-GRS
tableClient.DefaultRequestOptions.LocationMode = LocationMode.SecondaryOnly;
\!h ServiceStats stats = await tableClient.GetServiceStatsAsync();
Console.WriteLine("Last sync time: {0}", stats.GeoReplication.LastSyncTime);
Console.WriteLine("Status: {0}", stats.GeoReplication.Status);

// Set table permissions
SharedAccessTablePolicy accessTablePolicy = new SharedAccessTablePolicy
{
    SharedAccessStartTime = new DateTimeOffset(DateTime.Now),
    SharedAccessExpiryTime = new DateTimeOffset(DateTime.Now.AddMinutes(10)),
    Permissions = SharedAccessTablePermissions.Update
};
// Get the table's existing permissions, ready to add new policy
\!h TablePermissions permissions = await table.GetPermissionsAsync();
permissions.SharedAccessPolicies.Add("policyName", accessTablePolicy);
\!h await table.SetPermissionsAsync(permissions);

以上是关于csharp Azure存储表的主要内容,如果未能解决你的问题,请参考以下文章

csharp Azure存储队列

csharp Azure存储公共容器列出所有图像

csharp 通过.net WebAPI将Azure存储专用容器blob下载/流式传输到AngularJS

使用 Azure MSI 访问 Azure 表存储

为啥不能配置 Azure 诊断以通过新的 Azure 门户使用 Azure 表存储?

使用 azure 数据工厂管道将 json 对象存储到 azure 表存储实体