web-dev-qa-db-fra.com

Obtenir tous les enregistrements du stockage de table Azure

Utilisation de ce bloc de code

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

Je suis en mesure de récupérer l'enregistrement unique avec la partition et la clé de ligne mentionnées dans la récupération.

Existe-t-il un moyen d'obtenir tous les enregistrements stockés dans la partition de ServiceAlerts?

J'ai essayé un caractère générique (*) pour le deuxième paramètre

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

mais il ne retourne rien.

13
pithhelmet

Vous devez spécifier une TableQuery, cela vous donnera toutes les entités ou vous pouvez spécifier un TableQuery.GenerateFilterCondition pour filtrer les lignes.

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);
}
8
Murray Foxcroft

Si vous avez besoin d'un contrôle supplémentaire sur les enregistrements renvoyés, vous pouvez utiliser ExecuteQuerySegmentedAsync pour récupérer les données une page (environ 1 000 enregistrements) à la fois.

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

Ou si vous devez restreindre vos résultats, par exemple par Partition Key, vous pouvez ajouter une condition de filtre en ajoutant une clause Where à la requête dans le code ci-dessus.

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

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

référence MS Azure

8
richaux

Vous utilisez une mauvaise classe. Utilisez TableQuery pour récupérer plusieurs résultats. https://msdn.Microsoft.com/en-us/library/Azure/Microsoft.windowsazure.storage.table.tablequery.aspx

1
unconnected

J'ai fait le même processus en utilisant une classe générique. En utilisant l'application de fonction, j'ai atteint cet objectif. veuillez trouver les codes suivants. J'ai d'abord créé une application de fonction 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());
            }
        }
    }
}

Maintenant, j'ai créé un stockage de table dans le compte de stockage Azure. Et ajoutez le même champ dans un fichier de propriétés. qui est 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; }
    }
}

Maintenant, j'ai créé une classe qui peut prendre n'importe quelle classe de propriétés TableEntity et effectuer l'opération suivante Get/insert/Update. Recherchez le code suivant pour 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;
            }

        }

    }
}
0
Sapnandu