Saturday, November 19, 2022

Creating an Reading Ledger Entries in Azure Confidential Ledger

In my previous article I gave an introduction to Azure Confidential Ledger. In this article I am trying to publish a .NET code sample. There is already an example in MSDN which is not working as expected. Therefore I tried to build one while exploring API.  

I have created a .Net 6.0 based console application and will be using the default Program.cs class. 

Following Nuget packages are required to be installed. 

First get the ledger Uri, Collection Id and a console input as a message to be published. 

var ledgerUri = "https://azledger1.confidential-ledger.azure.com";
var collectionId = "col2";

Console.WriteLine("Enter Message");
var message = Console.ReadLine();
Console.WriteLine($"Message: {message}");

Make sure you have contribute or admin access to the ledger instance and configure Visual Studio to access Azure services via the same account. That way we can authorise ledger client with the identity. 

var ledgerClient = new ConfidentialLedgerClient(new Uri(ledgerUri), new DefaultAzureCredential());

Now we can use the ledger client to post the message to the collection defined above. 

Operation postOperation = ledgerClient.PostLedgerEntry(
    waitUntil: WaitUntil.Completed,
    RequestContent.Create(
        new { contents = message }),
    collectionId);

WaitUntil ensures the response is received after writing to the ledger. 

Next we can list down all the entries within the collection including the message just posted. 

var ledgerEntries = ledgerClient.GetLedgerEntries(collectionId);
Console.WriteLine("****");
foreach (var item in ledgerEntries)
{
    Console.WriteLine(item);
}

Also you can get the transaction id and read item by transaction id as well. 

No comments:

Post a Comment