Amazon QLDB driver for .NET – Quick start tutorial - Amazon Quantum Ledger Database (Amazon QLDB)

Amazon QLDB driver for .NET – Quick start tutorial

In this tutorial, you learn how to set up a simple application using the Amazon QLDB driver for .NET. This guide includes steps for installing the driver and short code examples of basic create, read, update, and delete (CRUD) operations.

Prerequisites

Before you get started, make sure that you do the following:

  1. Complete the Prerequisites for the .NET driver, if you haven't already done so. This includes signing up for AWS, getting an AWS access key for development, and installing the .NET Core SDK.

  2. Create a ledger named quick-start.

    To learn how to create a ledger, see Basic operations for Amazon QLDB ledgers or Step 1: Create a new ledger in Getting started with the console.

Step 1: Set up your project

First, set up your .NET project.

  1. To create and run a template application, enter the following dotnet commands on a terminal such as bash, PowerShell, or Command Prompt.

    $ dotnet new console --output Amazon.QLDB.QuickStartGuide $ dotnet run --project Amazon.QLDB.QuickStartGuide

    This template creates a folder named Amazon.QLDB.QuickStartGuide. In that folder, it creates a project with the same name and a file named Program.cs. The program contains code that displays the output Hello World!.

  2. Use the NuGet package manager to install the QLDB driver for .NET. We recommend using Visual Studio or an IDE of your choice to add dependencies to your project. The driver package name is Amazon.QLDB.Driver.

    • For example in Visual Studio, open the NuGet Package Manager Console on the Tools menu. Then, enter the following command at the PM> prompt.

      PM> Install-Package Amazon.QLDB.Driver
    • Or, you can enter the following commands on your terminal.

      $ cd Amazon.QLDB.QuickStartGuide $ dotnet add package Amazon.QLDB.Driver

    Installing the driver also installs its dependencies, including the AWS SDK for .NET and Amazon Ion libraries.

  3. Open the Program.cs file.

    Then, incrementally add the code examples in the following sections to try some basic CRUD operations. Or, you can skip the step-by-step tutorial and instead run the complete application.

Note

Choosing between synchronous and asynchronous APIs – The driver provides synchronous and asynchronous APIs. For high-demand applications that handle multiple requests without blocking, we recommend using the asynchronous APIs for improved performance. The driver offers synchronous APIs as an added convenience for existing code bases that are written synchronously.

This tutorial includes both synchronous and asynchronous code examples. For more information on the APIs, see the IQldbDriver and IAsyncQldbDriver interfaces in the API documentation.

Step 2: Initialize the driver

Initialize an instance of the driver that connects to the ledger named quick-start. Add the following code to your Program.cs file.

Async
using System; using System.Threading.Tasks; using Amazon.IonDotnet.Tree; using Amazon.IonDotnet.Tree.Impl; using Amazon.QLDB.Driver; using IAsyncResult = Amazon.QLDB.Driver.IAsyncResult; namespace Amazon.QLDB.QuickStartGuide { class Program { static IValueFactory valueFactory = new ValueFactory(); static async Task Main(string[] args) { Console.WriteLine("Create the async QLDB driver"); IAsyncQldbDriver driver = AsyncQldbDriver.Builder() .WithLedger("quick-start") .Build(); } } }
Sync
using System; using Amazon.IonDotnet.Tree; using Amazon.IonDotnet.Tree.Impl; using Amazon.QLDB.Driver; namespace Amazon.QLDB.QuickStartGuide { class Program { static IValueFactory valueFactory = new ValueFactory(); static void Main(string[] args) { Console.WriteLine("Create the sync QLDB Driver"); IQldbDriver driver = QldbDriver.Builder() .WithLedger("quick-start") .Build(); } } }

Step 3: Create a table and an index

For the rest of this tutorial through Step 6, you need to append the following code examples to the previous code example.

In this step, the following code shows how to run CREATE TABLE and CREATE INDEX statements. It creates a table named Person and an index for the firstName field on that table. Indexes can improve your query performance and help to limit optimistic concurrency control (OCC) conflict exceptions.

Async
Console.WriteLine("Creating the table and index"); // Creates the table and the index in the same transaction. // Note: Any code within the lambda can potentially execute multiple times due to retries. // For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy await driver.Execute(async txn => { await txn.Execute("CREATE TABLE Person"); await txn.Execute("CREATE INDEX ON Person(firstName)"); });
Sync
Console.WriteLine("Creating the tables and index"); // Creates the table and the index in the same transaction. // Note: Any code within the lambda can potentially execute multiple times due to retries. // For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy driver.Execute(txn => { txn.Execute("CREATE TABLE Person"); txn.Execute("CREATE INDEX ON Person(firstName)"); });

Step 4: Insert a document

The following code example shows how to run an INSERT statement. QLDB supports the PartiQL query language (SQL compatible) and the Amazon Ion data format (superset of JSON).

Add the following code that inserts a document into the Person table.

Async
Console.WriteLine("Inserting a document"); // This is one way of creating Ion values. We can also use an IonLoader. // For more details, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-cookbook-dotnet.html#cookbook-dotnet.ion IIonValue ionPerson = valueFactory.NewEmptyStruct(); ionPerson.SetField("firstName", valueFactory.NewString("John")); ionPerson.SetField("lastName", valueFactory.NewString("Doe")); ionPerson.SetField("age", valueFactory.NewInt(32)); await driver.Execute(async txn => { await txn.Execute("INSERT INTO Person ?", person); });
Sync
Console.WriteLine("Inserting a document"); // This is one way of creating Ion values, we can also use an IonLoader. // For more details, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-cookbook-dotnet.html#cookbook-dotnet.ion IIonValue ionPerson = valueFactory.NewEmptyStruct(); ionPerson.SetField("firstName", valueFactory.NewString("John")); ionPerson.SetField("lastName", valueFactory.NewString("Doe")); ionPerson.SetField("age", valueFactory.NewInt(32)); driver.Execute(txn => { txn.Execute("INSERT INTO Person ?", ionPerson); });
Tip

To insert multiple documents by using a single INSERT statement, you can pass an Ion list type parameter to the statement as follows.

// people is an Ion list txn.Execute("INSERT INTO Person ?", people);

You don't enclose the variable placeholder (?) in double angle brackets ( <<...>> ) when passing an Ion list. In manual PartiQL statements, double angle brackets denote an unordered collection known as a bag.

Step 5: Query the document

The following code example shows how to run a SELECT statement.

Add the following code that queries a document from the Person table.

Async
Console.WriteLine("Querying the table"); IIonValue ionFirstName = valueFactory.NewString("John"); // The result from driver.Execute() is buffered into memory because once the // transaction is committed, streaming the result is no longer possible. IAsyncResult selectResult = await driver.Execute(async txn => { return await txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName); }); await foreach (IIonValue row in selectResult) { Console.WriteLine(row.GetField("firstName").StringValue); Console.WriteLine(row.GetField("lastName").StringValue); Console.WriteLine(row.GetField("age").IntValue); }
Sync
Console.WriteLine("Querying the table"); IIonValue ionFirstName = valueFactory.NewString("John"); // The result from driver.Execute() is buffered into memory because once the // transaction is committed, streaming the result is no longer possible. IResult selectResult = driver.Execute(txn => { return txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName); }); foreach (IIonValue row in selectResult) { Console.WriteLine(row.GetField("firstName").StringValue); Console.WriteLine(row.GetField("lastName").StringValue); Console.WriteLine(row.GetField("age").IntValue); }

This example uses a question mark (?) as a variable placeholder to pass the document information to the statement. When you use placeholders, you must pass a value of type IonValue.

Step 6: Update the document

The following code example shows how to run an UPDATE statement.

  1. Add the following code that updates a document in the Person table by updating age to 42.

    Async
    Console.WriteLine("Updating the document"); IIonValue ionIntAge = valueFactory.NewInt(42); IIonValue ionFirstName2 = valueFactory.NewString("John"); await driver.Execute(async txn => { await txn.Execute("UPDATE Person SET age = ? WHERE firstName = ?", ionIntAge, ionFirstName2); });
    Sync
    Console.WriteLine("Updating a document"); IIonValue ionIntAge = valueFactory.NewInt(42); IIonValue ionFirstName2 = valueFactory.NewString("John"); driver.Execute(txn => { txn.Execute("UPDATE Person SET age = ? WHERE firstName = ?", ionIntAge, ionFirstName2); });
  2. Query the document again to see the updated value.

    Async
    Console.WriteLine("Querying the table for the updated document"); IIonValue ionFirstName3 = valueFactory.NewString("John"); IAsyncResult updateResult = await driver.Execute(async txn => { return await txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName3 ); }); await foreach (IIonValue row in updateResult) { Console.WriteLine(row.GetField("firstName").StringValue); Console.WriteLine(row.GetField("lastName").StringValue); Console.WriteLine(row.GetField("age").IntValue); }
    Sync
    Console.WriteLine("Querying the table for the updated document"); IIonValue ionFirstName3 = valueFactory.NewString("John"); IResult updateResult = driver.Execute(txn => { return txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName3); }); foreach (IIonValue row in updateResult) { Console.WriteLine(row.GetField("firstName").StringValue); Console.WriteLine(row.GetField("lastName").StringValue); Console.WriteLine(row.GetField("age").IntValue); }
  3. To run the application, enter the following command from the parent directory of your Amazon.QLDB.QuickStartGuide project directory.

    $ dotnet run --project Amazon.QLDB.QuickStartGuide

Running the complete application

The following code example is the complete version of the Program.cs application. Instead of doing the previous steps individually, you can also copy and run this code example end to end. This application demonstrates some basic CRUD operations on the ledger named quick-start.

Note

Before you run this code, make sure that you don't already have an active table named Person in the quick-start ledger.

Async
using System; using System.Threading.Tasks; using Amazon.IonDotnet.Tree; using Amazon.IonDotnet.Tree.Impl; using Amazon.QLDB.Driver; using IAsyncResult = Amazon.QLDB.Driver.IAsyncResult; namespace Amazon.QLDB.QuickStartGuide { class Program { static IValueFactory valueFactory = new ValueFactory(); static async Task Main(string[] args) { Console.WriteLine("Create the async QLDB driver"); IAsyncQldbDriver driver = AsyncQldbDriver.Builder() .WithLedger("quick-start") .Build(); Console.WriteLine("Creating the table and index"); // Creates the table and the index in the same transaction. // Note: Any code within the lambda can potentially execute multiple times due to retries. // For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy await driver.Execute(async txn => { await txn.Execute("CREATE TABLE Person"); await txn.Execute("CREATE INDEX ON Person(firstName)"); }); Console.WriteLine("Inserting a document"); // This is one way of creating Ion values. We can also use an IonLoader. // For more details, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-cookbook-dotnet.html#cookbook-dotnet.ion IIonValue ionPerson = valueFactory.NewEmptyStruct(); ionPerson.SetField("firstName", valueFactory.NewString("John")); ionPerson.SetField("lastName", valueFactory.NewString("Doe")); ionPerson.SetField("age", valueFactory.NewInt(32)); await driver.Execute(async txn => { await txn.Execute("INSERT INTO Person ?", ionPerson); }); Console.WriteLine("Querying the table"); IIonValue ionFirstName = valueFactory.NewString("John"); // The result from driver.Execute() is buffered into memory because once the // transaction is committed, streaming the result is no longer possible. IAsyncResult selectResult = await driver.Execute(async txn => { return await txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName); }); await foreach (IIonValue row in selectResult) { Console.WriteLine(row.GetField("firstName").StringValue); Console.WriteLine(row.GetField("lastName").StringValue); Console.WriteLine(row.GetField("age").IntValue); } Console.WriteLine("Updating the document"); IIonValue ionIntAge = valueFactory.NewInt(42); IIonValue ionFirstName2 = valueFactory.NewString("John"); await driver.Execute(async txn => { await txn.Execute("UPDATE Person SET age = ? WHERE firstName = ?", ionIntAge, ionFirstName2); }); Console.WriteLine("Querying the table for the updated document"); IIonValue ionFirstName3 = valueFactory.NewString("John"); IAsyncResult updateResult = await driver.Execute(async txn => { return await txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName3); }); await foreach (IIonValue row in updateResult) { Console.WriteLine(row.GetField("firstName").StringValue); Console.WriteLine(row.GetField("lastName").StringValue); Console.WriteLine(row.GetField("age").IntValue); } } } }
Sync
using System; using Amazon.IonDotnet.Tree; using Amazon.IonDotnet.Tree.Impl; using Amazon.QLDB.Driver; namespace Amazon.QLDB.QuickStartGuide { class Program { static IValueFactory valueFactory = new ValueFactory(); static void Main(string[] args) { Console.WriteLine("Create the sync QLDB Driver"); IQldbDriver driver = QldbDriver.Builder() .WithLedger("quick-start") .Build(); Console.WriteLine("Creating the tables and index"); // Creates the table and the index in the same transaction. // Note: Any code within the lambda can potentially execute multiple times due to retries. // For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy driver.Execute(txn => { txn.Execute("CREATE TABLE Person"); txn.Execute("CREATE INDEX ON Person(firstName)"); }); Console.WriteLine("Inserting a document"); // This is one way of creating Ion values. We can also use an IonLoader. // For more details, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-cookbook-dotnet.html#cookbook-dotnet.ion IIonValue ionPerson = valueFactory.NewEmptyStruct(); ionPerson.SetField("firstName", valueFactory.NewString("John")); ionPerson.SetField("lastName", valueFactory.NewString("Doe")); ionPerson.SetField("age", valueFactory.NewInt(32)); driver.Execute(txn => { txn.Execute("INSERT INTO Person ?", ionPerson); }); Console.WriteLine("Querying the table"); IIonValue ionFirstName = valueFactory.NewString("John"); // The result from driver.Execute() is buffered into memory because once the // transaction is committed, streaming the result is no longer possible. IResult selectResult = driver.Execute(txn => { return txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName); }); foreach (IIonValue row in selectResult) { Console.WriteLine(row.GetField("firstName").StringValue); Console.WriteLine(row.GetField("lastName").StringValue); Console.WriteLine(row.GetField("age").IntValue); } Console.WriteLine("Updating a document"); IIonValue ionIntAge = valueFactory.NewInt(42); IIonValue ionFirstName2 = valueFactory.NewString("John"); driver.Execute(txn => { txn.Execute("UPDATE Person SET age = ? WHERE firstName = ?", ionIntAge, ionFirstName2); }); Console.WriteLine("Querying the table for the updated document"); IIonValue ionFirstName3 = valueFactory.NewString("John"); IResult updateResult = driver.Execute(txn => { return txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName3); }); foreach (IIonValue row in updateResult) { Console.WriteLine(row.GetField("firstName").StringValue); Console.WriteLine(row.GetField("lastName").StringValue); Console.WriteLine(row.GetField("age").IntValue); } } } }

To run the complete application, enter the following command from the parent directory of your Amazon.QLDB.QuickStartGuide project directory.

$ dotnet run --project Amazon.QLDB.QuickStartGuide