26

Using this code block

try
{
    StorageCredentials creds = new StorageCredentials(accountName, accountKey);
    CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);

    CloudTableClient client = account.CreateCloudTableClient();
    CloudTable table = client.GetTableReference("serviceAlerts");

    TableOperation retrieveOperation = TableOperation.Retrieve<ServiceAlertsEntity>("ServiceAlerts", "b9ccd839-dd99-4358-b90f-46781b87f933");

    TableResult query = table.Execute(retrieveOperation);

    if (query.Result != null)
    {
        outline = outline + ((ServiceAlertsEntity) query.Result).alertMessage + " * ";
    }
    else
    {
        Console.WriteLine("No Alerts");
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex);
}

I am able to retrieve the single record with the partition and rowkey mentioned in the retrieve.

Is there a way I can get all the records that are stored in the partition of ServiceAlerts?

I have tried a wildcard (*) for the second parameter

TableOperation retrieveOperation = TableOperation.Retrieve<ServiceAlertsEntity>(
      "ServiceAlerts","b9ccd839-dd99-4358-b90f-46781b87f933");

but it does not return anything.

5 Answers 5

20

You need to specify a TableQuery, this will give you all entities or you can specify a TableQuery.GenerateFilterCondition to filter the rows.

TableQuery<ServiceAlertsEntity> query = new TableQuery<ServiceAlertsEntity>();

foreach (ServiceAlertsEntity entity in table.ExecuteQuery(query))
{
    Console.WriteLine("{0}, {1}\t{2}\t{3}", entity.PartitionKey, entity.RowKey,
                        entity.Field1, entity.Field2);
}
3
  • 6
    table.ExecuteQuery returns an IEnumerable which means it will bring all the data across multiple partition server. This approach is not good
    – Dan Hunex
    Commented Sep 25, 2017 at 21:24
  • 3
    And what if 'CloudTable' does not contain a definition for 'Execute' ?
    – Trinitron
    Commented Feb 5, 2020 at 13:45
  • 1
    This answer is no longer relevant. This is for the old/retired Azure Table SDK Commented Mar 23, 2023 at 4:39
20

If you need further control over the records being returned, you can use ExecuteQuerySegmentedAsync to retrieve data a page (around 1,000 records) at a time.

    var alerts = new List<ServiceAlertsEntity>();

    var query = new TableQuery<ServiceAlertsEntity>();
    TableContinuationToken continuationToken = null;
    do
    {
        var page = await table.ExecuteQuerySegmentedAsync(query, continuationToken);
        continuationToken = page.ContinuationToken;
        alerts.AddRange(page.Results);
    }
    while (continuationToken != null);

Or if you need to restrict your results, e.g. by Partition Key, you can add a filter condition by adding a Where clause to the query in the above code.

    var pk = "abc";
    var filterPk = TableQuery.GenerateFilterCondition(
        nameof(ServiceAlertsEntity.PartitionKey),
        QueryComparisons.Equal, pk);

    var query = new TableQuery<ServiceAlertsEntity>().Where(filterPk);

MS Azure reference

2

With the newer Azure.Data.Tables SDK this is now much shorter, especially when using the System.Linq.Async nuget package. With that you can simplay write:

/// <summary>
/// Returns all rows in a given Partition
/// </summary>
/// <typeparam name="T">Implementation of ITableEntity</typeparam>
/// <param name="tableClient">The authenticated TableClient</param>
/// <param name="partitionKey">The PartitionKey</param>
/// <returns>List of all entities with specified PartitionKey</returns>
public static async Task<IList<T>> GetAllEntitiesByPartitionKeyAsync<T>(this TableClient tableClient, string partitionKey) where T : class, ITableEntity, new()
{
    return await tableClient.QueryAsync<T>(x => x.PartitionKey == partitionKey, maxPerPage: 1000).ToListAsync().ConfigureAwait(false);
}

Note: by requesting 1000 rows at once (max) the total amount of requests can be drastically reduced.

Source

3
  • 1
    This is the correct and current answer. Thanks @Thomas Commented Mar 23, 2023 at 4:38
  • @MauricioAviles you answer is working fine but I have 5000 data in my parition key how to get all of the data because if I specify 1000 as max limit it will give only 1000 data is there any option to get rest of the data using some feature like continution token
    – Utpal
    Commented Oct 16, 2023 at 6:47
  • the .ToListAsync() will download all available rows in blocks of 1000. if you have 5000 rows it should download all of them as you can see here github.com/ThomasPe/Azure.Data.Tables-Extensions/blob/main/src/…
    – Thomas
    Commented Oct 16, 2023 at 13:48
1

You're using wrong class. Use TableQuery to retrieve multiple results. https://msdn.microsoft.com/en-us/library/azure/microsoft.windowsazure.storage.table.tablequery.aspx

1

I have done the same process using generic class. Using function app i have achieved this. please find the following codes. First i have created a function app MyEventhubTrigger.cs

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.ServiceBus;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using AzureMonitorFunctions.WebHook;



namespace MyFunctions
{
    public static class MyEventhubTrigger
    {               

        [FunctionName("MyEventhubTrigger")]       
       public static async void Run([EventHubTrigger("%EventHubName%", Connection = "EventHubConnectionString", ConsumerGroup = "devicestatuscg")] string myEventHubMessage, DateTime enqueuedTimeUtc, Int64 sequenceNumber, string offset, ILogger log)
        {           
            log.LogInformation($"C# Event Hub trigger function processed a message: {myEventHubMessage}");
            try
            {                 
                StorageTableOperation<StorageTable> tableObj = new StorageTableOperation<StorageTable>("EventhubMessages");
                Eventhubstorage Eventhubdada = tableObj.GetTableData("Eventhub", "DeviceStatus");
                if (Eventhubdada.EnqueuedTime < enqueuedTimeUtc)
                {                    
                        Eventhubdada.EnqueuedTime = enqueuedTimeUtc;
                        Eventhubdada.Offset = offset;
                        Eventhubdada.Sequence = sequenceNumber;
                        await tableObj.UpdateTableData("Eventhub", "DeviceStatus", Eventhubdada);
                    }
                }

            }
            catch (Exception ex)
            {
                log.LogInformation(ex.ToString());
            }
        }
    }
}

Now i have create table storage in azure storage account. And add the same field in a property file. which is StorageTable.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Table;

namespace MyFunctions
{
    public class StorageTable : TableEntity
    {
        public StorageTable()
        {
        }
        public StorageTable(string PKey, string RKey)
        {
            PartitionKey = PKey;
            RowKey = RKey;
        }

        public DateTime EnqueuedTime { get; set; }
        public Int64 Sequence { get; set; }
        public string Offset { get; set; }
    }
}

Now I have created a class which can take any TableEntity property class and do the following operation Get/insert/Update. Find the following code for StorageTableOperation.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System.Threading.Tasks;


namespace MyFunctions
{
    public class StorageTableOperation<T> where T : ITableEntity
    {       
        internal CloudTable cloudTable;        

        public StorageTableOperation(string tableName)
        {
            string connectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
            CloudTableClient client = storageAccount.CreateCloudTableClient();
            cloudTable = client.GetTableReference(tableName);
        }
        public T GetTableData(string PartitionKey,string RowKey)
        {           
            TableOperation retOp = TableOperation.Retrieve<T>(PartitionKey, RowKey);
            TableResult result = cloudTable.Execute(retOp);
            T tableData = (T)result.Result;


            return tableData;
        }

        public async Task<bool> UpdateTableData(string PartitionKey, string RowKey, T tableData)
        {
            try
            {               
                TableOperation operation = TableOperation.InsertOrMerge(tableData);
                TableResult tableResult = await cloudTable.ExecuteAsync(operation);
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }

        }

    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.