Simple Key-Value storage usage in AWS::DynamoDB

Many times, all you need is a simple storage in the cloud to store a typical Key-Value pair (which is usually very handy for many applications). The example below does that using AWS Dynamo DB. To exemplify I'm storing there all the lottery numbers since 2002. I'm removing my access ID and secret key - those you need to get from AWS. I find the syntax fairly straightforward and intuitive. Although I didn't try Azure, AWS didn't perform as fast as I expected for the insertion, taking several minutes to add just few thousand records. But it worked, and the code is down below, cheers, ACC.


using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using System.IO;
class Program
{
 private static readonly string AccessKeyId = "HIDDEN";
 private static readonly string SecretAccessKey = "HIDDEN";
 private static readonly string TableName = "KeyValueStore";
 private static AmazonDynamoDBClient client;
 static async Task Main(string[] args)
 {
 try
 {
 InitializeDynamoDBClient();
 await CreateTableIfNotExistsAsync();
 Console.WriteLine("Populating Key-Value with all Lottery Numbers since 2002...");
 FileInfo fi = new FileInfo("Lottery_Mega_Millions_Winning_Numbers__Beginning_2002.csv");
 StreamReader sr = fi.OpenText();
 int count = 0;
 while (!sr.EndOfStream)
 {
 string line = sr.ReadLine();
 string[] parts = line.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
 string key = parts[0];
 string value = parts[1];
 await AddKeyValuePair(key, value);
 count++;
 }
 sr.Close();
 Console.WriteLine("Done. Added: {0} records", count);
 while (true)
 {
 Console.WriteLine("\nChoose an operation:");
 Console.WriteLine("1. Add a key-value pair");
 Console.WriteLine("2. Get a value by key");
 Console.WriteLine("3. Exit");
 string choice = Console.ReadLine();
 switch (choice)
 {
 case "1":
 await AddKeyValuePair();
 break;
 case "2":
 await GetValueByKey();
 break;
 case "3":
 return;
 default:
 Console.WriteLine("Invalid choice. Please try again.");
 break;
 }
 }
 }
 catch (AmazonDynamoDBException e)
 {
 Console.WriteLine($"DynamoDB Error: {e.Message}");
 }
 catch (Exception e)
 {
 Console.WriteLine($"Error: {e.Message}");
 }
 }
 private static void InitializeDynamoDBClient()
 {
 var config = new AmazonDynamoDBConfig
 {
 RegionEndpoint = RegionEndpoint.USWest1
 };
 client = new AmazonDynamoDBClient(AccessKeyId, SecretAccessKey, config);
 }
 private static async Task CreateTableIfNotExistsAsync()
 {
 try
 {
 await client.DescribeTableAsync(TableName);
 }
 catch (ResourceNotFoundException)
 {
 var request = new CreateTableRequest
 {
 TableName = TableName,
 AttributeDefinitions = new List
 {
 new AttributeDefinition { AttributeName = "Key", AttributeType = "S" }
 },
 KeySchema = new List
 {
 new KeySchemaElement { AttributeName = "Key", KeyType = "HASH" }
 },
 ProvisionedThroughput = new ProvisionedThroughput
 {
 ReadCapacityUnits = 5,
 WriteCapacityUnits = 5
 }
 };
 await client.CreateTableAsync(request);
 await WaitForTableToBeReadyAsync();
 }
 }
 private static async Task WaitForTableToBeReadyAsync()
 {
 bool isTableReady = false;
 while (!isTableReady)
 {
 var response = await client.DescribeTableAsync(TableName);
 isTableReady = response.Table.TableStatus == TableStatus.ACTIVE;
 if (!isTableReady) await Task.Delay(1000);
 }
 }
 private static async Task AddKeyValuePair(string key, string value)
 {
 var request = new PutItemRequest
 {
 TableName = TableName,
 Item = new Dictionary
 {
 { "Key", new AttributeValue { S = key } },
 { "Value", new AttributeValue { S = value } }
 }
 };
 await client.PutItemAsync(request);
 }
 private static async Task AddKeyValuePair()
 {
 Console.Write("Enter key: ");
 string key = Console.ReadLine();
 Console.Write("Enter value: ");
 string value = Console.ReadLine();
 var request = new PutItemRequest
 {
 TableName = TableName,
 Item = new Dictionary
 {
 { "Key", new AttributeValue { S = key } },
 { "Value", new AttributeValue { S = value } }
 }
 };
 await client.PutItemAsync(request);
 Console.WriteLine("Key-value pair added successfully.");
 }
 private static async Task GetValueByKey()
 {
 Console.Write("Enter key to retrieve: ");
 string key = Console.ReadLine();
 var request = new GetItemRequest
 {
 TableName = TableName,
 Key = new Dictionary
 {
 { "Key", new AttributeValue { S = key } }
 }
 };
 var response = await client.GetItemAsync(request);
 if (response.Item.ContainsKey("Value"))
 {
 Console.WriteLine($"Value: {response.Item["Value"].S}");
 }
 else
 {
 Console.WriteLine("Key not found.");
 }
 }
}

Comments

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...