使用 Amazon SDK for .NET 的 Amazon Keyspaces 示例 - Amazon SDK for .NET
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 Amazon SDK for .NET 的 Amazon Keyspaces 示例

以下代码示例演示如何将 Amazon SDK for .NET 与 Amazon Keyspaces 结合使用来执行操作和实现常见场景。

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景和跨服务示例的上下文查看操作。

场景是指显示如何通过在同一服务中调用多个函数来完成特定任务的代码示例。

每个示例都包含一个指向的链接 GitHub,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

开始使用

以下代码示例演示如何开始使用 Amazon Keyspaces。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

namespace KeyspacesActions; public class HelloKeyspaces { private static ILogger logger = null!; static async Task Main(string[] args) { // Set up dependency injection for Amazon Keyspaces (for Apache Cassandra). using var host = Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => logging.AddFilter("System", LogLevel.Debug) .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information) .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace)) .ConfigureServices((_, services) => services.AddAWSService<IAmazonKeyspaces>() .AddTransient<KeyspacesWrapper>() ) .Build(); logger = LoggerFactory.Create(builder => { builder.AddConsole(); }) .CreateLogger<HelloKeyspaces>(); var keyspacesClient = host.Services.GetRequiredService<IAmazonKeyspaces>(); var keyspacesWrapper = new KeyspacesWrapper(keyspacesClient); Console.WriteLine("Hello, Amazon Keyspaces! Let's list your keyspaces:"); await keyspacesWrapper.ListKeyspaces(); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考ListKeyspaces中的。

操作

以下代码示例演示如何创建 Amazon Keyspaces 键空间。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <summary> /// Create a new keyspace. /// </summary> /// <param name="keyspaceName">The name for the new keyspace.</param> /// <returns>The Amazon Resource Name (ARN) of the new keyspace.</returns> public async Task<string> CreateKeyspace(string keyspaceName) { var response = await _amazonKeyspaces.CreateKeyspaceAsync( new CreateKeyspaceRequest { KeyspaceName = keyspaceName }); return response.ResourceArn; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考CreateKeyspace中的。

以下代码示例演示如何创建 Amazon Keyspaces 表。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <summary> /// Create a new Amazon Keyspaces table. /// </summary> /// <param name="keyspaceName">The keyspace where the table will be created.</param> /// <param name="schema">The schema for the new table.</param> /// <param name="tableName">The name of the new table.</param> /// <returns>The Amazon Resource Name (ARN) of the new table.</returns> public async Task<string> CreateTable(string keyspaceName, SchemaDefinition schema, string tableName) { var request = new CreateTableRequest { KeyspaceName = keyspaceName, SchemaDefinition = schema, TableName = tableName, PointInTimeRecovery = new PointInTimeRecovery { Status = PointInTimeRecoveryStatus.ENABLED } }; var response = await _amazonKeyspaces.CreateTableAsync(request); return response.ResourceArn; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考CreateTable中的。

以下代码示例演示如何删除 Amazon Keyspaces 键空间。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <summary> /// Delete an existing keyspace. /// </summary> /// <param name="keyspaceName"></param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DeleteKeyspace(string keyspaceName) { var response = await _amazonKeyspaces.DeleteKeyspaceAsync( new DeleteKeyspaceRequest { KeyspaceName = keyspaceName }); return response.HttpStatusCode == HttpStatusCode.OK; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考DeleteKeyspace中的。

以下代码示例演示如何删除 Amazon Keyspaces 表。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <summary> /// Delete an Amazon Keyspaces table. /// </summary> /// <param name="keyspaceName">The keyspace containing the table.</param> /// <param name="tableName">The name of the table to delete.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DeleteTable(string keyspaceName, string tableName) { var response = await _amazonKeyspaces.DeleteTableAsync( new DeleteTableRequest { KeyspaceName = keyspaceName, TableName = tableName }); return response.HttpStatusCode == HttpStatusCode.OK; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考DeleteTable中的。

以下代码示例演示如何获取 Amazon Keyspaces 键空间的相关数据。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <summary> /// Get data about a keyspace. /// </summary> /// <param name="keyspaceName">The name of the keyspace.</param> /// <returns>The Amazon Resource Name (ARN) of the keyspace.</returns> public async Task<string> GetKeyspace(string keyspaceName) { var response = await _amazonKeyspaces.GetKeyspaceAsync( new GetKeyspaceRequest { KeyspaceName = keyspaceName }); return response.ResourceArn; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考GetKeyspace中的。

以下代码示例演示如何获取 Amazon Keyspaces 表的相关数据。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <summary> /// Get information about an Amazon Keyspaces table. /// </summary> /// <param name="keyspaceName">The keyspace containing the table.</param> /// <param name="tableName">The name of the Amazon Keyspaces table.</param> /// <returns>The response containing data about the table.</returns> public async Task<GetTableResponse> GetTable(string keyspaceName, string tableName) { var response = await _amazonKeyspaces.GetTableAsync( new GetTableRequest { KeyspaceName = keyspaceName, TableName = tableName }); return response; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考GetTable中的。

以下代码示例演示如何列出 Amazon Keyspaces 键空间。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <summary> /// Lists all keyspaces for the account. /// </summary> /// <returns>Async task.</returns> public async Task ListKeyspaces() { var paginator = _amazonKeyspaces.Paginators.ListKeyspaces(new ListKeyspacesRequest()); Console.WriteLine("{0, -30}\t{1}", "Keyspace name", "Keyspace ARN"); Console.WriteLine(new string('-', Console.WindowWidth)); await foreach (var keyspace in paginator.Keyspaces) { Console.WriteLine($"{keyspace.KeyspaceName,-30}\t{keyspace.ResourceArn}"); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考ListKeyspaces中的。

以下代码示例演示如何列出键空间中的 Amazon Keyspaces 表。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <summary> /// Lists the Amazon Keyspaces tables in a keyspace. /// </summary> /// <param name="keyspaceName">The name of the keyspace.</param> /// <returns>A list of TableSummary objects.</returns> public async Task<List<TableSummary>> ListTables(string keyspaceName) { var response = await _amazonKeyspaces.ListTablesAsync(new ListTablesRequest { KeyspaceName = keyspaceName }); response.Tables.ForEach(table => { Console.WriteLine($"{table.KeyspaceName}\t{table.TableName}\t{table.ResourceArn}"); }); return response.Tables; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考ListTables中的。

以下代码示例演示如何将 Amazon Keyspaces 表还原到某个时间点。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <summary> /// Restores the specified table to the specified point in time. /// </summary> /// <param name="keyspaceName">The keyspace containing the table.</param> /// <param name="tableName">The name of the table to restore.</param> /// <param name="timestamp">The time to which the table will be restored.</param> /// <returns>The Amazon Resource Name (ARN) of the restored table.</returns> public async Task<string> RestoreTable(string keyspaceName, string tableName, string restoredTableName, DateTime timestamp) { var request = new RestoreTableRequest { RestoreTimestamp = timestamp, SourceKeyspaceName = keyspaceName, SourceTableName = tableName, TargetKeyspaceName = keyspaceName, TargetTableName = restoredTableName }; var response = await _amazonKeyspaces.RestoreTableAsync(request); return response.RestoredTableARN; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考RestoreTable中的。

以下代码示例演示如何更新 Amazon Keyspaces 表。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/// <summary> /// Updates the movie table to add a boolean column named watched. /// </summary> /// <param name="keyspaceName">The keyspace containing the table.</param> /// <param name="tableName">The name of the table to change.</param> /// <returns>The Amazon Resource Name (ARN) of the updated table.</returns> public async Task<string> UpdateTable(string keyspaceName, string tableName) { var newColumn = new ColumnDefinition { Name = "watched", Type = "boolean" }; var request = new UpdateTableRequest { KeyspaceName = keyspaceName, TableName = tableName, AddColumns = new List<ColumnDefinition> { newColumn } }; var response = await _amazonKeyspaces.UpdateTableAsync(request); return response.ResourceArn; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NETAPI 参考UpdateTable中的。

场景

以下代码示例演示了操作流程:

  • 创建键空间和表。表架构保存电影数据并启用了 point-in-time 恢复。

  • 使用带有 Sigv4 身份验证的安全 TLS 连接,连接到键空间。

  • 查询表。添加、检索和更新电影数据。

  • 更新表。添加一列来跟踪观看的电影。

  • 将表还原到以前的状态并清理资源。

Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

global using System.Security.Cryptography.X509Certificates; global using Amazon.Keyspaces; global using Amazon.Keyspaces.Model; global using KeyspacesActions; global using KeyspacesScenario; global using Microsoft.Extensions.Configuration; global using Microsoft.Extensions.DependencyInjection; global using Microsoft.Extensions.Hosting; global using Microsoft.Extensions.Logging; global using Microsoft.Extensions.Logging.Console; global using Microsoft.Extensions.Logging.Debug; global using Newtonsoft.Json; namespace KeyspacesBasics; /// <summary> /// Amazon Keyspaces (for Apache Cassandra) scenario. Shows some of the basic /// actions performed with Amazon Keyspaces. /// </summary> public class KeyspacesBasics { private static ILogger logger = null!; static async Task Main(string[] args) { // Set up dependency injection for the Amazon service. using var host = Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => logging.AddFilter("System", LogLevel.Debug) .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information) .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace)) .ConfigureServices((_, services) => services.AddAWSService<IAmazonKeyspaces>() .AddTransient<KeyspacesWrapper>() .AddTransient<CassandraWrapper>() ) .Build(); logger = LoggerFactory.Create(builder => { builder.AddConsole(); }) .CreateLogger<KeyspacesBasics>(); var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("settings.json") // Load test settings from .json file. .AddJsonFile("settings.local.json", true) // Optionally load local settings. .Build(); var keyspacesWrapper = host.Services.GetRequiredService<KeyspacesWrapper>(); var uiMethods = new UiMethods(); var keyspaceName = configuration["KeyspaceName"]; var tableName = configuration["TableName"]; bool success; // Used to track the results of some operations. uiMethods.DisplayOverview(); uiMethods.PressEnter(); // Create the keyspace. var keyspaceArn = await keyspacesWrapper.CreateKeyspace(keyspaceName); // Wait for the keyspace to be available. GetKeyspace results in a // resource not found error until it is ready for use. try { var getKeyspaceArn = ""; Console.Write($"Created {keyspaceName}. Waiting for it to become available. "); do { getKeyspaceArn = await keyspacesWrapper.GetKeyspace(keyspaceName); Console.Write(". "); } while (getKeyspaceArn != keyspaceArn); } catch (ResourceNotFoundException) { Console.WriteLine("Waiting for keyspace to be created."); } Console.WriteLine($"\nThe keyspace {keyspaceName} is ready for use."); uiMethods.PressEnter(); // Create the table. // First define the schema. var allColumns = new List<ColumnDefinition> { new ColumnDefinition { Name = "title", Type = "text" }, new ColumnDefinition { Name = "year", Type = "int" }, new ColumnDefinition { Name = "release_date", Type = "timestamp" }, new ColumnDefinition { Name = "plot", Type = "text" }, }; var partitionKeys = new List<PartitionKey> { new PartitionKey { Name = "year", }, new PartitionKey { Name = "title" }, }; var tableSchema = new SchemaDefinition { AllColumns = allColumns, PartitionKeys = partitionKeys, }; var tableArn = await keyspacesWrapper.CreateTable(keyspaceName, tableSchema, tableName); // Wait for the table to be active. try { var resp = new GetTableResponse(); Console.Write("Waiting for the new table to be active. "); do { try { resp = await keyspacesWrapper.GetTable(keyspaceName, tableName); Console.Write("."); } catch (ResourceNotFoundException) { Console.Write("."); } } while (resp.Status != TableStatus.ACTIVE); // Display the table's schema. Console.WriteLine($"\nTable {tableName} has been created in {keyspaceName}"); Console.WriteLine("Let's take a look at the schema."); uiMethods.DisplayTitle("All columns"); resp.SchemaDefinition.AllColumns.ForEach(column => { Console.WriteLine($"{column.Name,-40}\t{column.Type,-20}"); }); uiMethods.DisplayTitle("Cluster keys"); resp.SchemaDefinition.ClusteringKeys.ForEach(clusterKey => { Console.WriteLine($"{clusterKey.Name,-40}\t{clusterKey.OrderBy,-20}"); }); uiMethods.DisplayTitle("Partition keys"); resp.SchemaDefinition.PartitionKeys.ForEach(partitionKey => { Console.WriteLine($"{partitionKey.Name}"); }); uiMethods.PressEnter(); } catch (ResourceNotFoundException ex) { Console.WriteLine($"Error: {ex.Message}"); } // Access Apache Cassandra using the Cassandra drive for C#. var cassandraWrapper = host.Services.GetRequiredService<CassandraWrapper>(); var movieFilePath = configuration["MovieFile"]; Console.WriteLine("Let's add some movies to the table we created."); var inserted = await cassandraWrapper.InsertIntoMovieTable(keyspaceName, tableName, movieFilePath); uiMethods.PressEnter(); Console.WriteLine("Added the following movies to the table:"); var rows = await cassandraWrapper.GetMovies(keyspaceName, tableName); uiMethods.DisplayTitle("All Movies"); foreach (var row in rows) { var title = row.GetValue<string>("title"); var year = row.GetValue<int>("year"); var plot = row.GetValue<string>("plot"); var release_date = row.GetValue<DateTime>("release_date"); Console.WriteLine($"{release_date}\t{title}\t{year}\n{plot}"); Console.WriteLine(uiMethods.SepBar); } // Update the table schema uiMethods.DisplayTitle("Update table schema"); Console.WriteLine("Now we will update the table to add a boolean field called watched."); // First save the current time as a UTC Date so the original // table can be restored later. var timeChanged = DateTime.UtcNow; // Now update the schema. var resourceArn = await keyspacesWrapper.UpdateTable(keyspaceName, tableName); uiMethods.PressEnter(); Console.WriteLine("Now let's mark some of the movies as watched."); // Pick some files to mark as watched. var movieToWatch = rows[2].GetValue<string>("title"); var watchedMovieYear = rows[2].GetValue<int>("year"); var changedRows = await cassandraWrapper.MarkMovieAsWatched(keyspaceName, tableName, movieToWatch, watchedMovieYear); movieToWatch = rows[6].GetValue<string>("title"); watchedMovieYear = rows[6].GetValue<int>("year"); changedRows = await cassandraWrapper.MarkMovieAsWatched(keyspaceName, tableName, movieToWatch, watchedMovieYear); movieToWatch = rows[9].GetValue<string>("title"); watchedMovieYear = rows[9].GetValue<int>("year"); changedRows = await cassandraWrapper.MarkMovieAsWatched(keyspaceName, tableName, movieToWatch, watchedMovieYear); movieToWatch = rows[10].GetValue<string>("title"); watchedMovieYear = rows[10].GetValue<int>("year"); changedRows = await cassandraWrapper.MarkMovieAsWatched(keyspaceName, tableName, movieToWatch, watchedMovieYear); movieToWatch = rows[13].GetValue<string>("title"); watchedMovieYear = rows[13].GetValue<int>("year"); changedRows = await cassandraWrapper.MarkMovieAsWatched(keyspaceName, tableName, movieToWatch, watchedMovieYear); uiMethods.DisplayTitle("Watched movies"); Console.WriteLine("These movies have been marked as watched:"); rows = await cassandraWrapper.GetWatchedMovies(keyspaceName, tableName); foreach (var row in rows) { var title = row.GetValue<string>("title"); var year = row.GetValue<int>("year"); Console.WriteLine($"{title,-40}\t{year,8}"); } uiMethods.PressEnter(); Console.WriteLine("We can restore the table to its previous state but that can take up to 20 minutes to complete."); string answer; do { Console.WriteLine("Do you want to restore the table? (y/n)"); answer = Console.ReadLine(); } while (answer.ToLower() != "y" && answer.ToLower() != "n"); if (answer == "y") { var restoredTableName = $"{tableName}_restored"; var restoredTableArn = await keyspacesWrapper.RestoreTable( keyspaceName, tableName, restoredTableName, timeChanged); // Loop and call GetTable until the table is gone. Once it has been // deleted completely, GetTable will raise a ResourceNotFoundException. bool wasRestored = false; try { do { var resp = await keyspacesWrapper.GetTable(keyspaceName, restoredTableName); wasRestored = (resp.Status == TableStatus.ACTIVE); } while (!wasRestored); } catch (ResourceNotFoundException) { // If the restored table raised an error, it isn't // ready yet. Console.Write("."); } } uiMethods.DisplayTitle("Clean up resources."); // Delete the table. success = await keyspacesWrapper.DeleteTable(keyspaceName, tableName); Console.WriteLine($"Table {tableName} successfully deleted from {keyspaceName}."); Console.WriteLine("Waiting for the table to be removed completely. "); // Loop and call GetTable until the table is gone. Once it has been // deleted completely, GetTable will raise a ResourceNotFoundException. bool wasDeleted = false; try { do { var resp = await keyspacesWrapper.GetTable(keyspaceName, tableName); } while (!wasDeleted); } catch (ResourceNotFoundException ex) { wasDeleted = true; Console.WriteLine($"{ex.Message} indicates that the table has been deleted."); } // Delete the keyspace. success = await keyspacesWrapper.DeleteKeyspace(keyspaceName); Console.WriteLine("The keyspace has been deleted and the demo is now complete."); } }
namespace KeyspacesActions; /// <summary> /// Performs Amazon Keyspaces (for Apache Cassandra) actions. /// </summary> public class KeyspacesWrapper { private readonly IAmazonKeyspaces _amazonKeyspaces; /// <summary> /// Constructor for the KeyspaceWrapper. /// </summary> /// <param name="amazonKeyspaces">An Amazon Keyspaces client object.</param> public KeyspacesWrapper(IAmazonKeyspaces amazonKeyspaces) { _amazonKeyspaces = amazonKeyspaces; } /// <summary> /// Create a new keyspace. /// </summary> /// <param name="keyspaceName">The name for the new keyspace.</param> /// <returns>The Amazon Resource Name (ARN) of the new keyspace.</returns> public async Task<string> CreateKeyspace(string keyspaceName) { var response = await _amazonKeyspaces.CreateKeyspaceAsync( new CreateKeyspaceRequest { KeyspaceName = keyspaceName }); return response.ResourceArn; } /// <summary> /// Create a new Amazon Keyspaces table. /// </summary> /// <param name="keyspaceName">The keyspace where the table will be created.</param> /// <param name="schema">The schema for the new table.</param> /// <param name="tableName">The name of the new table.</param> /// <returns>The Amazon Resource Name (ARN) of the new table.</returns> public async Task<string> CreateTable(string keyspaceName, SchemaDefinition schema, string tableName) { var request = new CreateTableRequest { KeyspaceName = keyspaceName, SchemaDefinition = schema, TableName = tableName, PointInTimeRecovery = new PointInTimeRecovery { Status = PointInTimeRecoveryStatus.ENABLED } }; var response = await _amazonKeyspaces.CreateTableAsync(request); return response.ResourceArn; } /// <summary> /// Delete an existing keyspace. /// </summary> /// <param name="keyspaceName"></param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DeleteKeyspace(string keyspaceName) { var response = await _amazonKeyspaces.DeleteKeyspaceAsync( new DeleteKeyspaceRequest { KeyspaceName = keyspaceName }); return response.HttpStatusCode == HttpStatusCode.OK; } /// <summary> /// Delete an Amazon Keyspaces table. /// </summary> /// <param name="keyspaceName">The keyspace containing the table.</param> /// <param name="tableName">The name of the table to delete.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DeleteTable(string keyspaceName, string tableName) { var response = await _amazonKeyspaces.DeleteTableAsync( new DeleteTableRequest { KeyspaceName = keyspaceName, TableName = tableName }); return response.HttpStatusCode == HttpStatusCode.OK; } /// <summary> /// Get data about a keyspace. /// </summary> /// <param name="keyspaceName">The name of the keyspace.</param> /// <returns>The Amazon Resource Name (ARN) of the keyspace.</returns> public async Task<string> GetKeyspace(string keyspaceName) { var response = await _amazonKeyspaces.GetKeyspaceAsync( new GetKeyspaceRequest { KeyspaceName = keyspaceName }); return response.ResourceArn; } /// <summary> /// Get information about an Amazon Keyspaces table. /// </summary> /// <param name="keyspaceName">The keyspace containing the table.</param> /// <param name="tableName">The name of the Amazon Keyspaces table.</param> /// <returns>The response containing data about the table.</returns> public async Task<GetTableResponse> GetTable(string keyspaceName, string tableName) { var response = await _amazonKeyspaces.GetTableAsync( new GetTableRequest { KeyspaceName = keyspaceName, TableName = tableName }); return response; } /// <summary> /// Lists all keyspaces for the account. /// </summary> /// <returns>Async task.</returns> public async Task ListKeyspaces() { var paginator = _amazonKeyspaces.Paginators.ListKeyspaces(new ListKeyspacesRequest()); Console.WriteLine("{0, -30}\t{1}", "Keyspace name", "Keyspace ARN"); Console.WriteLine(new string('-', Console.WindowWidth)); await foreach (var keyspace in paginator.Keyspaces) { Console.WriteLine($"{keyspace.KeyspaceName,-30}\t{keyspace.ResourceArn}"); } } /// <summary> /// Lists the Amazon Keyspaces tables in a keyspace. /// </summary> /// <param name="keyspaceName">The name of the keyspace.</param> /// <returns>A list of TableSummary objects.</returns> public async Task<List<TableSummary>> ListTables(string keyspaceName) { var response = await _amazonKeyspaces.ListTablesAsync(new ListTablesRequest { KeyspaceName = keyspaceName }); response.Tables.ForEach(table => { Console.WriteLine($"{table.KeyspaceName}\t{table.TableName}\t{table.ResourceArn}"); }); return response.Tables; } /// <summary> /// Restores the specified table to the specified point in time. /// </summary> /// <param name="keyspaceName">The keyspace containing the table.</param> /// <param name="tableName">The name of the table to restore.</param> /// <param name="timestamp">The time to which the table will be restored.</param> /// <returns>The Amazon Resource Name (ARN) of the restored table.</returns> public async Task<string> RestoreTable(string keyspaceName, string tableName, string restoredTableName, DateTime timestamp) { var request = new RestoreTableRequest { RestoreTimestamp = timestamp, SourceKeyspaceName = keyspaceName, SourceTableName = tableName, TargetKeyspaceName = keyspaceName, TargetTableName = restoredTableName }; var response = await _amazonKeyspaces.RestoreTableAsync(request); return response.RestoredTableARN; } /// <summary> /// Updates the movie table to add a boolean column named watched. /// </summary> /// <param name="keyspaceName">The keyspace containing the table.</param> /// <param name="tableName">The name of the table to change.</param> /// <returns>The Amazon Resource Name (ARN) of the updated table.</returns> public async Task<string> UpdateTable(string keyspaceName, string tableName) { var newColumn = new ColumnDefinition { Name = "watched", Type = "boolean" }; var request = new UpdateTableRequest { KeyspaceName = keyspaceName, TableName = tableName, AddColumns = new List<ColumnDefinition> { newColumn } }; var response = await _amazonKeyspaces.UpdateTableAsync(request); return response.ResourceArn; } }
using System.Net; using Cassandra; namespace KeyspacesScenario; /// <summary> /// Class to perform CRUD methods on an Amazon Keyspaces (for Apache Cassandra) database. /// /// NOTE: This sample uses a plain text authenticator for example purposes only. /// Recommended best practice is to use a SigV4 authentication plugin, if available. /// </summary> public class CassandraWrapper { private readonly IConfiguration _configuration; private readonly string _localPathToFile; private const string _certLocation = "https://certs.secureserver.net/repository/sf-class2-root.crt"; private const string _certFileName = "sf-class2-root.crt"; private readonly X509Certificate2Collection _certCollection; private X509Certificate2 _amazoncert; private Cluster _cluster; // User name and password for the service. private string _userName = null!; private string _pwd = null!; public CassandraWrapper() { _configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("settings.json") // Load test settings from .json file. .AddJsonFile("settings.local.json", true) // Optionally load local settings. .Build(); _localPathToFile = Path.GetTempPath(); // Get the Starfield digital certificate and save it locally. var client = new WebClient(); client.DownloadFile(_certLocation, $"{_localPathToFile}/{_certFileName}"); //var httpClient = new HttpClient(); //var httpResult = httpClient.Get(fileUrl); //using var resultStream = await httpResult.Content.ReadAsStreamAsync(); //using var fileStream = File.Create(pathToSave); //resultStream.CopyTo(fileStream); _certCollection = new X509Certificate2Collection(); _amazoncert = new X509Certificate2($"{_localPathToFile}/{_certFileName}"); // Get the user name and password stored in the configuration file. _userName = _configuration["UserName"]!; _pwd = _configuration["Password"]!; // For a list of Service Endpoints for Amazon Keyspaces, see: // https://docs.aws.amazon.com/keyspaces/latest/devguide/programmatic.endpoints.html var awsEndpoint = _configuration["ServiceEndpoint"]; _cluster = Cluster.Builder() .AddContactPoints(awsEndpoint) .WithPort(9142) .WithAuthProvider(new PlainTextAuthProvider(_userName, _pwd)) .WithSSL(new SSLOptions().SetCertificateCollection(_certCollection)) .WithQueryOptions( new QueryOptions() .SetConsistencyLevel(ConsistencyLevel.LocalQuorum) .SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial)) .Build(); } /// <summary> /// Loads the contents of a JSON file into a list of movies to be /// added to the Apache Cassandra table. /// </summary> /// <param name="movieFileName">The full path to the JSON file.</param> /// <returns>A list of movie objects.</returns> public List<Movie> ImportMoviesFromJson(string movieFileName, int numToImport = 0) { if (!File.Exists(movieFileName)) { return null!; } using var sr = new StreamReader(movieFileName); string json = sr.ReadToEnd(); var allMovies = JsonConvert.DeserializeObject<List<Movie>>(json); // If numToImport = 0, return all movies in the collection. if (numToImport == 0) { // Now return the entire list of movies. return allMovies; } else { // Now return the first numToImport entries. return allMovies.GetRange(0, numToImport); } } /// <summary> /// Insert movies into the movie table. /// </summary> /// <param name="keyspaceName">The keyspace containing the table.</param> /// <param name="movieTableName">The Amazon Keyspaces table.</param> /// <param name="movieFilePath">The path to the resource file containing /// movie data to insert into the table.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> InsertIntoMovieTable(string keyspaceName, string movieTableName, string movieFilePath, int numToImport = 20) { // Get some movie data from the movies.json file var movies = ImportMoviesFromJson(movieFilePath, numToImport); var session = _cluster.Connect(keyspaceName); string insertCql; RowSet rs; // Now we insert the numToImport movies into the table. foreach (var movie in movies) { // Escape single quote characters in the plot. insertCql = $"INSERT INTO {keyspaceName}.{movieTableName} (title, year, release_date, plot) values($${movie.Title}$$, {movie.Year}, '{movie.Info.Release_Date.ToString("yyyy-MM-dd")}', $${movie.Info.Plot}$$)"; rs = await session.ExecuteAsync(new SimpleStatement(insertCql)); } return true; } /// <summary> /// Gets all of the movies in the movies table. /// </summary> /// <param name="keyspaceName">The keyspace containing the table.</param> /// <param name="tableName">The name of the table.</param> /// <returns>A list of row objects containing movie data.</returns> public async Task<List<Row>> GetMovies(string keyspaceName, string tableName) { var session = _cluster.Connect(); RowSet rs; try { rs = await session.ExecuteAsync(new SimpleStatement($"SELECT * FROM {keyspaceName}.{tableName}")); // Extract the row data from the returned RowSet. var rows = rs.GetRows().ToList(); return rows; } catch (Exception ex) { Console.WriteLine(ex.Message); return null!; } } /// <summary> /// Mark a movie in the movie table as watched. /// </summary> /// <param name="keyspaceName">The keyspace containing the table.</param> /// <param name="tableName">The name of the table.</param> /// <param name="title">The title of the movie to mark as watched.</param> /// <param name="year">The year the movie was released.</param> /// <returns>A set of rows containing the changed data.</returns> public async Task<List<Row>> MarkMovieAsWatched(string keyspaceName, string tableName, string title, int year) { var session = _cluster.Connect(); string updateCql = $"UPDATE {keyspaceName}.{tableName} SET watched=true WHERE title = $${title}$$ AND year = {year};"; var rs = await session.ExecuteAsync(new SimpleStatement(updateCql)); var rows = rs.GetRows().ToList(); return rows; } /// <summary> /// Retrieve the movies in the movies table where watched is true. /// </summary> /// <param name="keyspaceName">The keyspace containing the table.</param> /// <param name="tableName">The name of the table.</param> /// <returns>A list of row objects containing information about movies /// where watched is true.</returns> public async Task<List<Row>> GetWatchedMovies(string keyspaceName, string tableName) { var session = _cluster.Connect(); RowSet rs; try { rs = await session.ExecuteAsync(new SimpleStatement($"SELECT title, year, plot FROM {keyspaceName}.{tableName} WHERE watched = true ALLOW FILTERING")); // Extract the row data from the returned RowSet. var rows = rs.GetRows().ToList(); return rows; } catch (Exception ex) { Console.WriteLine(ex.Message); return null!; } } }