Build a C# (.NET) App with CockroachDB

This tutorial shows you how build a simple C# (.NET) application with CockroachDB using a PostgreSQL-compatible driver.

We have tested the .NET Npgsql driver enough to claim beta-level support, so that driver is featured here. If you encounter problems, please open an issue with details to help us make progress toward full support.

Before you begin

Step 1. Create a .NET project

  1. $ dotnet new console -o cockroachdb-test-app
  1. $ cd cockroachdb-test-app

The dotnet command creates a new app of type console. The -o parameter creates a directory named cockroachdb-test-app where your app will be stored and populates it with the required files. The cd cockroachdb-test-app command puts you into the newly created app directory.

Step 2. Install the Npgsql driver

Install the latest version of the Npgsql driver into the .NET project using the built-in nuget package manager:

  1. $ dotnet add package Npgsql

Step 3. Create the maxroach user and bank database

Start the built-in SQL client:

  1. $ cockroach sql --certs-dir=certs

In the SQL shell, issue the following statements to create the maxroach user and bank database:

  1. > CREATE USER IF NOT EXISTS maxroach;
  1. > CREATE DATABASE bank;

Give the maxroach user the necessary permissions:

  1. > GRANT ALL ON DATABASE bank TO maxroach;

Exit the SQL shell:

  1. > \q

Step 4. Generate a certificate for the maxroach user

Create a certificate and key for the maxroach user by running the following command. The code samples will run as this user.

  1. $ cockroach cert create-client maxroach --certs-dir=certs --ca-key=my-safe-directory/ca.key

Step 5. Convert the key file for use by C# programs

The private key generated for user maxroach by CockroachDB is PEM encoded. To read the key in a C# application, you will need to convert it into PKCS#12 format.

To convert the key to PKCS#12 format, run the following OpenSSL command on the maxroach user's key file in the directory where you stored your certificates:

  1. $ openssl pkcs12 -inkey client.maxroach.key -password pass: -in client.maxroach.crt -export -out client.maxroach.pfx

As of December 2018, you need to provide a password for this to work on macOS. See https://github.com/dotnet/corefx/issues/24225.

Step 6. Run the C# code

Now that you have created a database and set up encryption keys, in this section you will:

Basic example

Replace the contents of cockroachdb-test-app/Program.cs with the following code:

  1. using System;
  2. using System.Data;
  3. using System.Security.Cryptography.X509Certificates;
  4. using System.Net.Security;
  5. using Npgsql;
  6. namespace Cockroach
  7. {
  8. class MainClass
  9. {
  10. static void Main(string[] args)
  11. {
  12. var connStringBuilder = new NpgsqlConnectionStringBuilder();
  13. connStringBuilder.Host = "localhost";
  14. connStringBuilder.Port = 26257;
  15. connStringBuilder.SslMode = SslMode.Require;
  16. connStringBuilder.Username = "maxroach";
  17. connStringBuilder.Database = "bank";
  18. Simple(connStringBuilder.ConnectionString);
  19. }
  20. static void Simple(string connString)
  21. {
  22. using (var conn = new NpgsqlConnection(connString))
  23. {
  24. conn.ProvideClientCertificatesCallback += ProvideClientCertificatesCallback;
  25. conn.UserCertificateValidationCallback += UserCertificateValidationCallback;
  26. conn.Open();
  27. // Create the "accounts" table.
  28. new NpgsqlCommand("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)", conn).ExecuteNonQuery();
  29. // Insert two rows into the "accounts" table.
  30. using (var cmd = new NpgsqlCommand())
  31. {
  32. cmd.Connection = conn;
  33. cmd.CommandText = "UPSERT INTO accounts(id, balance) VALUES(@id1, @val1), (@id2, @val2)";
  34. cmd.Parameters.AddWithValue("id1", 1);
  35. cmd.Parameters.AddWithValue("val1", 1000);
  36. cmd.Parameters.AddWithValue("id2", 2);
  37. cmd.Parameters.AddWithValue("val2", 250);
  38. cmd.ExecuteNonQuery();
  39. }
  40. // Print out the balances.
  41. System.Console.WriteLine("Initial balances:");
  42. using (var cmd = new NpgsqlCommand("SELECT id, balance FROM accounts", conn))
  43. using (var reader = cmd.ExecuteReader())
  44. while (reader.Read())
  45. Console.Write("\taccount {0}: {1}\n", reader.GetValue(0), reader.GetValue(1));
  46. }
  47. }
  48. static void ProvideClientCertificatesCallback(X509CertificateCollection clientCerts)
  49. {
  50. // To be able to add a certificate with a private key included, we must convert it to
  51. // a PKCS #12 format. The following openssl command does this:
  52. // openssl pkcs12 -password pass: -inkey client.maxroach.key -in client.maxroach.crt -export -out client.maxroach.pfx
  53. // As of 2018-12-10, you need to provide a password for this to work on macOS.
  54. // See https://github.com/dotnet/corefx/issues/24225
  55. // Note that the password used during X509 cert creation below
  56. // must match the password used in the openssl command above.
  57. clientCerts.Add(new X509Certificate2("client.maxroach.pfx", "pass"));
  58. }
  59. // By default, .Net does all of its certificate verification using the system certificate store.
  60. // This callback is necessary to validate the server certificate against a CA certificate file.
  61. static bool UserCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain defaultChain, SslPolicyErrors defaultErrors)
  62. {
  63. X509Certificate2 caCert = new X509Certificate2("ca.crt");
  64. X509Chain caCertChain = new X509Chain();
  65. caCertChain.ChainPolicy = new X509ChainPolicy()
  66. {
  67. RevocationMode = X509RevocationMode.NoCheck,
  68. RevocationFlag = X509RevocationFlag.EntireChain
  69. };
  70. caCertChain.ChainPolicy.ExtraStore.Add(caCert);
  71. X509Certificate2 serverCert = new X509Certificate2(certificate);
  72. caCertChain.Build(serverCert);
  73. if (caCertChain.ChainStatus.Length == 0)
  74. {
  75. // No errors
  76. return true;
  77. }
  78. foreach (X509ChainStatus status in caCertChain.ChainStatus)
  79. {
  80. // Check if we got any errors other than UntrustedRoot (which we will always get if we don't install the CA cert to the system store)
  81. if (status.Status != X509ChainStatusFlags.UntrustedRoot)
  82. {
  83. return false;
  84. }
  85. }
  86. return true;
  87. }
  88. }
  89. }

Then, run the code to connect as the maxroach user. This time, execute a batch of statements as an atomic transaction to transfer funds from one account to another, where all included statements are either committed or aborted:

  1. $ dotnet run

The output should be:

  1. Initial balances:
  2. account 1: 1000
  3. account 2: 250

Transaction example (with retry logic)

Open cockroachdb-test-app/Program.cs again and replace the contents with the code shown below.

Note:

With the default SERIALIZABLE isolation level, CockroachDB may require the client to retry a transaction in case of read/write contention. CockroachDB provides a generic retry function that runs inside a transaction and retries it as needed. The code sample below shows how it is used.

  1. using System;
  2. using System.Data;
  3. using System.Security.Cryptography.X509Certificates;
  4. using System.Net.Security;
  5. using Npgsql;
  6. namespace Cockroach
  7. {
  8. class MainClass
  9. {
  10. static void Main(string[] args)
  11. {
  12. var connStringBuilder = new NpgsqlConnectionStringBuilder();
  13. connStringBuilder.Host = "localhost";
  14. connStringBuilder.Port = 26257;
  15. connStringBuilder.SslMode = SslMode.Require;
  16. connStringBuilder.Username = "maxroach";
  17. connStringBuilder.Database = "bank";
  18. TxnSample(connStringBuilder.ConnectionString);
  19. }
  20. static void TransferFunds(NpgsqlConnection conn, NpgsqlTransaction tran, int from, int to, int amount)
  21. {
  22. int balance = 0;
  23. using (var cmd = new NpgsqlCommand(String.Format("SELECT balance FROM accounts WHERE id = {0}", from), conn, tran))
  24. using (var reader = cmd.ExecuteReader())
  25. {
  26. if (reader.Read())
  27. {
  28. balance = reader.GetInt32(0);
  29. }
  30. else
  31. {
  32. throw new DataException(String.Format("Account id={0} not found", from));
  33. }
  34. }
  35. if (balance < amount)
  36. {
  37. throw new DataException(String.Format("Insufficient balance in account id={0}", from));
  38. }
  39. using (var cmd = new NpgsqlCommand(String.Format("UPDATE accounts SET balance = balance - {0} where id = {1}", amount, from), conn, tran))
  40. {
  41. cmd.ExecuteNonQuery();
  42. }
  43. using (var cmd = new NpgsqlCommand(String.Format("UPDATE accounts SET balance = balance + {0} where id = {1}", amount, to), conn, tran))
  44. {
  45. cmd.ExecuteNonQuery();
  46. }
  47. }
  48. static void TxnSample(string connString)
  49. {
  50. using (var conn = new NpgsqlConnection(connString))
  51. {
  52. conn.ProvideClientCertificatesCallback += ProvideClientCertificatesCallback;
  53. conn.UserCertificateValidationCallback += UserCertificateValidationCallback;
  54. conn.Open();
  55. // Create the "accounts" table.
  56. new NpgsqlCommand("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)", conn).ExecuteNonQuery();
  57. // Insert two rows into the "accounts" table.
  58. using (var cmd = new NpgsqlCommand())
  59. {
  60. cmd.Connection = conn;
  61. cmd.CommandText = "UPSERT INTO accounts(id, balance) VALUES(@id1, @val1), (@id2, @val2)";
  62. cmd.Parameters.AddWithValue("id1", 1);
  63. cmd.Parameters.AddWithValue("val1", 1000);
  64. cmd.Parameters.AddWithValue("id2", 2);
  65. cmd.Parameters.AddWithValue("val2", 250);
  66. cmd.ExecuteNonQuery();
  67. }
  68. // Print out the balances.
  69. System.Console.WriteLine("Initial balances:");
  70. using (var cmd = new NpgsqlCommand("SELECT id, balance FROM accounts", conn))
  71. using (var reader = cmd.ExecuteReader())
  72. while (reader.Read())
  73. Console.Write("\taccount {0}: {1}\n", reader.GetValue(0), reader.GetValue(1));
  74. try
  75. {
  76. using (var tran = conn.BeginTransaction())
  77. {
  78. tran.Save("cockroach_restart");
  79. while (true)
  80. {
  81. try
  82. {
  83. TransferFunds(conn, tran, 1, 2, 100);
  84. tran.Commit();
  85. break;
  86. }
  87. catch (NpgsqlException e)
  88. {
  89. // Check if the error code indicates a SERIALIZATION_FAILURE.
  90. if (e.ErrorCode == 40001)
  91. {
  92. // Signal the database that we will attempt a retry.
  93. tran.Rollback("cockroach_restart");
  94. }
  95. else
  96. {
  97. throw;
  98. }
  99. }
  100. }
  101. }
  102. }
  103. catch (DataException e)
  104. {
  105. Console.WriteLine(e.Message);
  106. }
  107. // Now printout the results.
  108. Console.WriteLine("Final balances:");
  109. using (var cmd = new NpgsqlCommand("SELECT id, balance FROM accounts", conn))
  110. using (var reader = cmd.ExecuteReader())
  111. while (reader.Read())
  112. Console.Write("\taccount {0}: {1}\n", reader.GetValue(0), reader.GetValue(1));
  113. }
  114. }
  115. static void ProvideClientCertificatesCallback(X509CertificateCollection clientCerts)
  116. {
  117. // To be able to add a certificate with a private key included, we must convert it to
  118. // a PKCS #12 format. The following openssl command does this:
  119. // openssl pkcs12 -inkey client.maxroach.key -in client.maxroach.crt -export -out client.maxroach.pfx
  120. // As of 2018-12-10, you need to provide a password for this to work on macOS.
  121. // See https://github.com/dotnet/corefx/issues/24225
  122. clientCerts.Add(new X509Certificate2("client.maxroach.pfx", "pass"));
  123. }
  124. // By default, .Net does all of its certificate verification using the system certificate store.
  125. // This callback is necessary to validate the server certificate against a CA certificate file.
  126. static bool UserCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain defaultChain, SslPolicyErrors defaultErrors)
  127. {
  128. X509Certificate2 caCert = new X509Certificate2("ca.crt");
  129. X509Chain caCertChain = new X509Chain();
  130. caCertChain.ChainPolicy = new X509ChainPolicy()
  131. {
  132. RevocationMode = X509RevocationMode.NoCheck,
  133. RevocationFlag = X509RevocationFlag.EntireChain
  134. };
  135. caCertChain.ChainPolicy.ExtraStore.Add(caCert);
  136. X509Certificate2 serverCert = new X509Certificate2(certificate);
  137. caCertChain.Build(serverCert);
  138. if (caCertChain.ChainStatus.Length == 0)
  139. {
  140. // No errors
  141. return true;
  142. }
  143. foreach (X509ChainStatus status in caCertChain.ChainStatus)
  144. {
  145. // Check if we got any errors other than UntrustedRoot (which we will always get if we don't install the CA cert to the system store)
  146. if (status.Status != X509ChainStatusFlags.UntrustedRoot)
  147. {
  148. return false;
  149. }
  150. }
  151. return true;
  152. }
  153. }
  154. }

Then, run the code to connect as the maxroach user. This time, execute a batch of statements as an atomic transaction to transfer funds from one account to another, where all included statements are either committed or aborted:

  1. $ dotnet run

The output should be:

  1. Initial balances:
  2. account 1: 1000
  3. account 2: 250
  4. Final balances:
  5. account 1: 900
  6. account 2: 350

However, if you want to verify that funds were transferred from one account to another, use the built-in SQL client:

  1. $ cockroach sql --certs-dir=certs --database=bank -e 'SELECT id, balance FROM accounts'
  1. id | balance
  2. +----+---------+
  3. 1 | 900
  4. 2 | 350
  5. (2 rows)

Step 3. Create the maxroach user and bank database

Start the built-in SQL client:

  1. $ cockroach sql --insecure

In the SQL shell, issue the following statements to create the maxroach user and bank database:

  1. > CREATE USER IF NOT EXISTS maxroach;
  1. > CREATE DATABASE bank;

Give the maxroach user the necessary permissions:

  1. > GRANT ALL ON DATABASE bank TO maxroach;

Exit the SQL shell:

  1. > \q

Step 4. Run the C# code

Now that you have created a database and set up encryption keys, in this section you will:

Basic example

Replace the contents of cockroachdb-test-app/Program.cs with the following code:

  1. using System;
  2. using System.Data;
  3. using Npgsql;
  4. namespace Cockroach
  5. {
  6. class MainClass
  7. {
  8. static void Main(string[] args)
  9. {
  10. var connStringBuilder = new NpgsqlConnectionStringBuilder();
  11. connStringBuilder.Host = "localhost";
  12. connStringBuilder.Port = 26257;
  13. connStringBuilder.SslMode = SslMode.Disable;
  14. connStringBuilder.Username = "maxroach";
  15. connStringBuilder.Database = "bank";
  16. Simple(connStringBuilder.ConnectionString);
  17. }
  18. static void Simple(string connString)
  19. {
  20. using (var conn = new NpgsqlConnection(connString))
  21. {
  22. conn.Open();
  23. // Create the "accounts" table.
  24. new NpgsqlCommand("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)", conn).ExecuteNonQuery();
  25. // Insert two rows into the "accounts" table.
  26. using (var cmd = new NpgsqlCommand())
  27. {
  28. cmd.Connection = conn;
  29. cmd.CommandText = "UPSERT INTO accounts(id, balance) VALUES(@id1, @val1), (@id2, @val2)";
  30. cmd.Parameters.AddWithValue("id1", 1);
  31. cmd.Parameters.AddWithValue("val1", 1000);
  32. cmd.Parameters.AddWithValue("id2", 2);
  33. cmd.Parameters.AddWithValue("val2", 250);
  34. cmd.ExecuteNonQuery();
  35. }
  36. // Print out the balances.
  37. System.Console.WriteLine("Initial balances:");
  38. using (var cmd = new NpgsqlCommand("SELECT id, balance FROM accounts", conn))
  39. using (var reader = cmd.ExecuteReader())
  40. while (reader.Read())
  41. Console.Write("\taccount {0}: {1}\n", reader.GetValue(0), reader.GetValue(1));
  42. }
  43. }
  44. }
  45. }

Then, run the code to connect as the maxroach user and execute some basic SQL statements: creating a table, inserting rows, and reading and printing the rows:

  1. $ dotnet run

The output should be:

  1. Initial balances:
  2. account 1: 1000
  3. account 2: 250

Transaction example (with retry logic)

Open cockroachdb-test-app/Program.cs again and replace the contents with the code shown below.

Note:

With the default SERIALIZABLE isolation level, CockroachDB may require the client to retry a transaction in case of read/write contention. CockroachDB provides a generic retry function that runs inside a transaction and retries it as needed. The code sample below shows how it is used.

  1. using System;
  2. using System.Data;
  3. using Npgsql;
  4. namespace Cockroach
  5. {
  6. class MainClass
  7. {
  8. static void Main(string[] args)
  9. {
  10. var connStringBuilder = new NpgsqlConnectionStringBuilder();
  11. connStringBuilder.Host = "localhost";
  12. connStringBuilder.Port = 26257;
  13. connStringBuilder.SslMode = SslMode.Disable;
  14. connStringBuilder.Username = "maxroach";
  15. connStringBuilder.Database = "bank";
  16. TxnSample(connStringBuilder.ConnectionString);
  17. }
  18. static void TransferFunds(NpgsqlConnection conn, NpgsqlTransaction tran, int from, int to, int amount)
  19. {
  20. int balance = 0;
  21. using (var cmd = new NpgsqlCommand(String.Format("SELECT balance FROM accounts WHERE id = {0}", from), conn, tran))
  22. using (var reader = cmd.ExecuteReader())
  23. {
  24. if (reader.Read())
  25. {
  26. balance = reader.GetInt32(0);
  27. }
  28. else
  29. {
  30. throw new DataException(String.Format("Account id={0} not found", from));
  31. }
  32. }
  33. if (balance < amount)
  34. {
  35. throw new DataException(String.Format("Insufficient balance in account id={0}", from));
  36. }
  37. using (var cmd = new NpgsqlCommand(String.Format("UPDATE accounts SET balance = balance - {0} where id = {1}", amount, from), conn, tran))
  38. {
  39. cmd.ExecuteNonQuery();
  40. }
  41. using (var cmd = new NpgsqlCommand(String.Format("UPDATE accounts SET balance = balance + {0} where id = {1}", amount, to), conn, tran))
  42. {
  43. cmd.ExecuteNonQuery();
  44. }
  45. }
  46. static void TxnSample(string connString)
  47. {
  48. using (var conn = new NpgsqlConnection(connString))
  49. {
  50. conn.Open();
  51. // Create the "accounts" table.
  52. new NpgsqlCommand("CREATE TABLE IF NOT EXISTS accounts (id INT PRIMARY KEY, balance INT)", conn).ExecuteNonQuery();
  53. // Insert two rows into the "accounts" table.
  54. using (var cmd = new NpgsqlCommand())
  55. {
  56. cmd.Connection = conn;
  57. cmd.CommandText = "UPSERT INTO accounts(id, balance) VALUES(@id1, @val1), (@id2, @val2)";
  58. cmd.Parameters.AddWithValue("id1", 1);
  59. cmd.Parameters.AddWithValue("val1", 1000);
  60. cmd.Parameters.AddWithValue("id2", 2);
  61. cmd.Parameters.AddWithValue("val2", 250);
  62. cmd.ExecuteNonQuery();
  63. }
  64. // Print out the balances.
  65. System.Console.WriteLine("Initial balances:");
  66. using (var cmd = new NpgsqlCommand("SELECT id, balance FROM accounts", conn))
  67. using (var reader = cmd.ExecuteReader())
  68. while (reader.Read())
  69. Console.Write("\taccount {0}: {1}\n", reader.GetValue(0), reader.GetValue(1));
  70. try
  71. {
  72. using (var tran = conn.BeginTransaction())
  73. {
  74. tran.Save("cockroach_restart");
  75. while (true)
  76. {
  77. try
  78. {
  79. TransferFunds(conn, tran, 1, 2, 100);
  80. tran.Commit();
  81. break;
  82. }
  83. catch (NpgsqlException e)
  84. {
  85. // Check if the error code indicates a SERIALIZATION_FAILURE.
  86. if (e.ErrorCode == 40001)
  87. {
  88. // Signal the database that we will attempt a retry.
  89. tran.Rollback("cockroach_restart");
  90. }
  91. else
  92. {
  93. throw;
  94. }
  95. }
  96. }
  97. }
  98. }
  99. catch (DataException e)
  100. {
  101. Console.WriteLine(e.Message);
  102. }
  103. // Now printout the results.
  104. Console.WriteLine("Final balances:");
  105. using (var cmd = new NpgsqlCommand("SELECT id, balance FROM accounts", conn))
  106. using (var reader = cmd.ExecuteReader())
  107. while (reader.Read())
  108. Console.Write("\taccount {0}: {1}\n", reader.GetValue(0), reader.GetValue(1));
  109. }
  110. }
  111. }
  112. }

Then, run the code to connect as the maxroach user. This time, execute a batch of statements as an atomic transaction to transfer funds from one account to another, where all included statements are either committed or aborted:

  1. $ dotnet run

The output should be:

  1. Initial balances:
  2. account 1: 1000
  3. account 2: 250
  4. Final balances:
  5. account 1: 900
  6. account 2: 350

However, if you want to verify that funds were transferred from one account to another, use the built-in SQL client:

  1. $ cockroach sql --insecure --database=bank -e 'SELECT id, balance FROM accounts'
  1. id | balance
  2. +----+---------+
  3. 1 | 900
  4. 2 | 350
  5. (2 rows)

What's next?

Read more about using the .NET Npgsql driver.

You might also be interested in using a local cluster to explore the following CockroachDB benefits:

Was this page helpful?
YesNo