public List <string> GetTables()
        {
            var response = aws.ListTablesAsync();

            return(response.Result.TableNames);
        }
        public void Init()
        {
            ListTablesResponse tableListResponse = null;

            tableListResponse = _client.ListTablesAsync().Result;

            if (tableListResponse == null || !tableListResponse.TableNames.Any(x => x == "Network"))
            {
                CreateTable("Network");
            }

            if (tableListResponse == null || !tableListResponse.TableNames.Any(x => x == "Station"))
            {
                CreateTable("Station");
            }

            if (tableListResponse == null || !tableListResponse.TableNames.Any(x => x == "Show"))
            {
                CreateTable("Show");
            }

            var table = Table.LoadTable(_client, "Network");

            /*
             * if (table.GlobalSecondaryIndexes.Any(x => x.Key == "Network_Global_Index_01"))
             * {
             *  var updateTableRequest = new UpdateTableRequest()
             *  {
             *      TableName = "Network",
             *      GlobalSecondaryIndexUpdates = new List<GlobalSecondaryIndexUpdate>()
             *      {
             *          new GlobalSecondaryIndexUpdate()
             *          {
             *              Delete = new DeleteGlobalSecondaryIndexAction
             *              {
             *                  IndexName = "Network_Global_Index_01"
             *              }
             *          }
             *      }
             *  };
             *
             *  var response = _client.UpdateTableAsync(updateTableRequest).Result;
             *  var status = response.HttpStatusCode;
             * }
             */

            if (!table.GlobalSecondaryIndexes.Any(x => x.Key == "Network_Global_Index_01"))
            {
                var updateTableRequest = new UpdateTableRequest()
                {
                    TableName            = "Network",
                    AttributeDefinitions = new List <AttributeDefinition>()
                    {
                        new AttributeDefinition
                        {
                            AttributeName = "MasterId",
                            AttributeType = "S"
                        },
                        new AttributeDefinition
                        {
                            AttributeName = "Id",
                            AttributeType = "S"
                        }
                    },
                    GlobalSecondaryIndexUpdates = new List <GlobalSecondaryIndexUpdate>()
                    {
                        new GlobalSecondaryIndexUpdate()
                        {
                            Create = new CreateGlobalSecondaryIndexAction()
                            {
                                IndexName = "Network_Global_Index_01",
                                KeySchema = new List <KeySchemaElement>()
                                {
                                    new KeySchemaElement()
                                    {
                                        AttributeName = "MasterId",
                                        KeyType       = "HASH"
                                    },
                                    new KeySchemaElement()
                                    {
                                        AttributeName = "Id",
                                        KeyType       = "RANGE"
                                    }
                                },
                                Projection = new Projection()
                                {
                                    ProjectionType = ProjectionType.ALL
                                },
                                ProvisionedThroughput = new ProvisionedThroughput()
                                {
                                    ReadCapacityUnits = 10, WriteCapacityUnits = 10
                                }
                            }
                        }
                    }
                };

                var response = _client.UpdateTableAsync(updateTableRequest).Result;
                var status   = response.HttpStatusCode;
            }
        }
Пример #3
0
        public Program(ILoggerFactory loggerFactory,
                       DynamoUserStore <DynamoIdentityUser, DynamoIdentityRole> userStore,
                       DynamoRoleStore <DynamoIdentityRole> roleStore,
                       DynamoRoleUsersStore <DynamoIdentityRole, DynamoIdentityUser> roleUsersStore,
                       ILookupNormalizer keyNormalizer,
                       string dbUrl,
                       string regionName,
                       string tableNamePrefix)
        {
            this.logger         = loggerFactory.CreateLogger <Program>();
            this.userStore      = userStore;
            this.roleStore      = roleStore;
            this.roleUsersStore = roleUsersStore;
            this.keyNormalizer  = keyNormalizer;

            var dbConfig = new AmazonDynamoDBConfig
            {
                ServiceURL = dbUrl
            };

            if (regionName != null)
            {
                var region = RegionEndpoint.GetBySystemName(regionName);
                dbConfig.RegionEndpoint = region;
            }

            var client = new AmazonDynamoDBClient(dbConfig);

            var contextConfig = new DynamoDBContextConfig
            {
                TableNamePrefix = tableNamePrefix
            };

            var context = new DynamoDBContext(client, contextConfig);

            var prefix = tableNamePrefix ?? "";

            roleUsersTableName = $"{prefix}roleUsers";
            usersTableName     = $"{prefix}users";
            rolesTableName     = $"{prefix}roles";

            var tables = client.ListTablesAsync().Result;

            if (!tables.TableNames.Contains(usersTableName))
            {
                throw new Exception($"can't find table {usersTableName}");
            }

            if (!tables.TableNames.Contains(rolesTableName))
            {
                throw new Exception($"can't find table {rolesTableName}");
            }

            if (!tables.TableNames.Contains(roleUsersTableName))
            {
                throw new Exception($"can't find table {roleUsersTableName}");
            }

            roleUsersStore.EnsureInitializedAsync(client, context, roleUsersTableName).Wait();
            userStore.EnsureInitializedAsync(client, context, usersTableName).Wait();
            roleStore.EnsureInitializedAsync(client, context, rolesTableName).Wait();
        }
Пример #4
0
        /// <summary>
        /// Method to create table in Dynamo DB
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns>RequestId is not empty it means table is created or table doesnot exists</returns>
        public string FuncCreateTableDynamoDBAsync(string tableName)
        {
            string requestId = string.Empty;

            try
            {
                System.Threading.Tasks.Task <ListTablesResponse> currentTablesAsync = client.ListTablesAsync();
                List <string> lstTableNames = currentTablesAsync.Result.TableNames;
                if (!lstTableNames.Contains(tableName))
                {
                    CreateTableRequest request = new CreateTableRequest
                    {
                        TableName            = "TBL_SPLITWISEBOTCONFIGVALUES",
                        AttributeDefinitions = new List <AttributeDefinition>
                        {
                            new AttributeDefinition
                            {
                                AttributeName = "KEY",
                                // "S" = string, "N" = number, and so on.
                                AttributeType = "S"
                            },
                            new AttributeDefinition
                            {
                                AttributeName = "TYPE",
                                AttributeType = "S"
                            }
                        },
                        KeySchema = new List <KeySchemaElement>
                        {
                            new KeySchemaElement
                            {
                                AttributeName = "KEY",
                                // "HASH" = hash key, "RANGE" = range key.
                                KeyType = "HASH"
                            },
                            new KeySchemaElement
                            {
                                AttributeName = "TYPE",
                                KeyType       = "RANGE"
                            },
                        },
                        ProvisionedThroughput = new ProvisionedThroughput
                        {
                            ReadCapacityUnits  = 10,
                            WriteCapacityUnits = 5
                        },
                    };

                    System.Threading.Tasks.Task <CreateTableResponse> response = client.CreateTableAsync(request);

                    requestId = response.Result.ResponseMetadata.RequestId.ToString();
                }
                return(requestId);
            }
            catch (Exception)
            {
                return(requestId);
            }
        }
Пример #5
0
        public static async Task MainAsync(string[] args)
        {
            Console.WriteLine("Start to connect ddb in container!");
            var clientConfig = new AmazonDynamoDBConfig();

            clientConfig.ServiceURL = "http://dynamodb-local:8000";
            var client = new AmazonDynamoDBClient(clientConfig);

            try
            {
                var tableName = "HistoryRecord";
                var hashKey   = "UserId";
                // Low Level API: client
                Console.WriteLine("-------Low Level API--------");
                Console.WriteLine("Verify table => " + tableName);
                var tableResponse = await client.ListTablesAsync();

                if (!tableResponse.TableNames.Contains(tableName))
                {
                    Console.WriteLine("Table not found, creating table => " + tableName);
                    await client.CreateTableAsync(new CreateTableRequest
                    {
                        TableName             = tableName,
                        ProvisionedThroughput = new ProvisionedThroughput
                        {
                            ReadCapacityUnits  = 3,
                            WriteCapacityUnits = 1
                        },
                        KeySchema = new List <KeySchemaElement>
                        {
                            new KeySchemaElement
                            {
                                AttributeName = hashKey,
                                KeyType       = KeyType.HASH
                            }
                        },
                        AttributeDefinitions = new List <AttributeDefinition>
                        {
                            new AttributeDefinition {
                                AttributeName = hashKey, AttributeType = ScalarAttributeType.S
                            }
                        }
                    });

                    bool isTableAvailable = false;
                    while (!isTableAvailable)
                    {
                        Console.WriteLine("Waiting for table to be active...");
                        Thread.Sleep(2000);
                        var tableStatus = await client.DescribeTableAsync(tableName);

                        isTableAvailable = tableStatus.Table.TableStatus == "ACTIVE";
                    }
                }
                Console.WriteLine("low-lavel. Save data to table");
                var itemDict = new Dictionary <String, AttributeValue>();
                itemDict.Add("UserId", new AttributeValue()
                {
                    S = "1"
                });
                itemDict.Add("Birthday", new AttributeValue()
                {
                    S = "1997-7-1"
                });


                var request = new PutItemRequest()
                {
                    TableName = tableName, Item = itemDict
                };
                var result = await client.PutItemAsync(request);

                Console.WriteLine("low-lavel. Save result: " + result.HttpStatusCode);


                // Document Model: Table
                Console.WriteLine("-------Document Model--------");
                var table = Table.LoadTable(client, tableName);
                var item  = new Document();
                item["UserId"] = "2";
                //item["Birthday"] = ???
                await table.PutItemAsync(item);

                var getConfig = new GetItemOperationConfig()
                {
                    AttributesToGet = new List <string>()
                    {
                        "UserId", "Birthday"
                    },
                    ConsistentRead = true
                };
                var doc = await table.GetItemAsync("1", getConfig);

                Console.WriteLine("table. get 1st item birthday: " + doc["Birthday"]);

                // Persistence Model: Context
                Console.WriteLine("-------Persistence Model--------");
                var context = new DynamoDBContext(client);

                var newRecord = new HistoryRecord
                {
                    UserId = "3",
                    Line   = new RecordLine()
                    {
                        Token    = "awesomeToken",
                        Index    = 0,
                        Finished = true,
                        StuffIds = new List <int> {
                            0, 1
                        }
                    }
                };

                await context.SaveAsync <HistoryRecord>(newRecord);

                Console.WriteLine("context. getting 3nd HistoryRecord object");
                List <ScanCondition> conditions = new List <ScanCondition>();
                conditions.Add(new ScanCondition("UserId", ScanOperator.Equal, newRecord.UserId));
                var allDocs = await context.ScanAsync <HistoryRecord>(conditions).GetRemainingAsync();

                var savedState = allDocs.FirstOrDefault();

                // ToDocument
                var docFromP = context.ToDocument <HistoryRecord>(savedState);

                if (JsonConvert.SerializeObject(savedState) == JsonConvert.SerializeObject(newRecord))
                {
                    Console.WriteLine("Retrieved is: " + savedState.Line.Token);
                }
                else
                {
                    Console.WriteLine("Oops, saved item is differnt");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("!!!!!! ");
                Console.WriteLine(e.Message);
            }
        }
Пример #6
0
        public async Task InitializeAsync()
        {
            var listTablesResponse = await _client.ListTablesAsync();

            if (listTablesResponse.TableNames.Contains(OutboxTableName))
            {
                await _client.DeleteTableAsync(OutboxTableName);
            }

            var tableDescription = await GetTableStatus(OutboxTableName);

            while (tableDescription == null || tableDescription.TableStatus != "NOT FOUND")
            {
                await Task.Delay(100);

                tableDescription = await GetTableStatus(OutboxTableName);
            }

            if (listTablesResponse.TableNames.Contains(OrgsTableName))
            {
                await _client.DeleteTableAsync(OrgsTableName);
            }
            tableDescription = await GetTableStatus(OrgsTableName);

            while (tableDescription == null || tableDescription.TableStatus != "NOT FOUND")
            {
                await Task.Delay(100);

                tableDescription = await GetTableStatus(OrgsTableName);
            }

            var createOutBoxTableRequest = new CreateTableRequest
            {
                TableName = OutboxTableName,
                KeySchema = new List <KeySchemaElement>
                {
                    new KeySchemaElement("Id", KeyType.HASH),
                    new KeySchemaElement("Created", KeyType.RANGE)
                },
                AttributeDefinitions = new List <AttributeDefinition>
                {
                    new AttributeDefinition("Id", ScalarAttributeType.S),
                    new AttributeDefinition("Created", ScalarAttributeType.N),
                },
                BillingMode         = BillingMode.PAY_PER_REQUEST,
                StreamSpecification = new StreamSpecification
                {
                    StreamEnabled  = true,
                    StreamViewType = StreamViewType.NEW_IMAGE
                }
            };
            await _client.CreateTableAsync(createOutBoxTableRequest);

            var describeTableResponse = await _client.DescribeTableAsync(OutboxTableName);

            _tableLatestStreamArn = describeTableResponse.Table.LatestStreamArn;

            var updateTimeToLiveRequest = new UpdateTimeToLiveRequest
            {
                TableName = OutboxTableName,
                TimeToLiveSpecification = new TimeToLiveSpecification
                {
                    AttributeName = "Expiration", // Must be epoch seconds
                    Enabled       = true
                }
            };
            await _client.UpdateTimeToLiveAsync(updateTimeToLiveRequest);

            var createOrgsTableRequest = new CreateTableRequest
            {
                TableName = OrgsTableName,
                KeySchema = new List <KeySchemaElement>
                {
                    new KeySchemaElement("Id", KeyType.HASH),
                    new KeySchemaElement("Name", KeyType.RANGE)
                },
                AttributeDefinitions = new List <AttributeDefinition>
                {
                    new AttributeDefinition("Id", ScalarAttributeType.N),
                    new AttributeDefinition("Name", ScalarAttributeType.S),
                },
                BillingMode = BillingMode.PAY_PER_REQUEST,
            };
            await _client.CreateTableAsync(createOrgsTableRequest);
        }
Пример #7
0
        private static Table PrepareTable()
        {
            var client = new AmazonDynamoDBClient(new AmazonDynamoDBConfig
            {
                ServiceURL = "http://localhost:8000"
            });

            var tables = client.ListTablesAsync().GetAwaiter().GetResult();

            if (!tables.TableNames.Contains("AggregateStore"))
            {
                var response = client.CreateTableAsync(new CreateTableRequest(
                                                           tableName: "AggregateStore",
                                                           keySchema: new List <KeySchemaElement>
                {
                    new KeySchemaElement(KnownTableAttributes.PartitionKey, KeyType.HASH),
                    new KeySchemaElement(KnownTableAttributes.SortKey, KeyType.RANGE)
                },
                                                           attributeDefinitions: new List <AttributeDefinition>
                {
                    new AttributeDefinition(KnownTableAttributes.PartitionKey, ScalarAttributeType.S),
                    new AttributeDefinition(KnownTableAttributes.SortKey, ScalarAttributeType.S),
                },
                                                           provisionedThroughput: new ProvisionedThroughput(1, 1)))
                               .GetAwaiter()
                               .GetResult();

                var createIndex = new UpdateTableRequest();
                createIndex.TableName = "AggregateStore";

                createIndex.AttributeDefinitions = new List <AttributeDefinition>
                {
                    new AttributeDefinition("TaskProjectId", ScalarAttributeType.N)
                };

                createIndex.GlobalSecondaryIndexUpdates = new List <GlobalSecondaryIndexUpdate>();
                createIndex.GlobalSecondaryIndexUpdates.Add(new GlobalSecondaryIndexUpdate
                {
                    Create = new CreateGlobalSecondaryIndexAction
                    {
                        IndexName  = "TaskProjectIdIndex",
                        Projection = new Projection
                        {
                            ProjectionType   = ProjectionType.INCLUDE,
                            NonKeyAttributes = new List <string>
                            {
                                KnownTableAttributes.AggregateId,
                                KnownTableAttributes.AggregateType
                            }
                        },
                        KeySchema = new List <KeySchemaElement>
                        {
                            new KeySchemaElement("TaskProjectId", KeyType.HASH)
                        },
                        ProvisionedThroughput = new ProvisionedThroughput(1, 1)
                    }
                });

                client.UpdateTableAsync(createIndex).GetAwaiter().GetResult();
            }

            return(Table.LoadTable(client, "AggregateStore"));
        }
Пример #8
0
        public static async Task MainAsync(string[] args)
        {
            string tableName = "AlexaAudioStates";
            string hashKey   = "UserId";

            Console.WriteLine("Creating credentials and initializing DynamoDB client");
            var credentials = new BasicAWSCredentials(accessKey, secretKey);
            var client      = new AmazonDynamoDBClient(credentials, RegionEndpoint.USEast1);

            Console.WriteLine("Verify table => " + tableName);
            var tableResponse = await client.ListTablesAsync();

            if (!tableResponse.TableNames.Contains(tableName))
            {
                Console.WriteLine("Table not found, creating table => " + tableName);
                await client.CreateTableAsync(new CreateTableRequest
                {
                    TableName             = tableName,
                    ProvisionedThroughput = new ProvisionedThroughput
                    {
                        ReadCapacityUnits  = 3,
                        WriteCapacityUnits = 1
                    },
                    KeySchema = new List <KeySchemaElement>
                    {
                        new KeySchemaElement
                        {
                            AttributeName = hashKey,
                            KeyType       = KeyType.HASH
                        }
                    },
                    AttributeDefinitions = new List <AttributeDefinition>
                    {
                        new AttributeDefinition {
                            AttributeName = hashKey, AttributeType = ScalarAttributeType.S
                        }
                    }
                });

                bool isTableAvailable = false;
                while (!isTableAvailable)
                {
                    Console.WriteLine("Waiting for table to be active...");
                    Thread.Sleep(5000);
                    var tableStatus = await client.DescribeTableAsync(tableName);

                    isTableAvailable = tableStatus.Table.TableStatus == "ACTIVE";
                }
            }

            Console.WriteLine("Set a local DB context");
            var context = new DynamoDBContext(client);

            Console.WriteLine("Create an AlexaAudioState object to save");
            AlexaAudioState currentState = new AlexaAudioState
            {
                UserId = "someAwesomeUser",
                State  = new StateMap()
                {
                    EnqueuedToken        = "awesomeAudioPart2",
                    Index                = 0,
                    Loop                 = true,
                    OffsetInMS           = 123456,
                    PlaybackFinished     = false,
                    PlaybackIndexChanged = false,
                    playOrder            = new List <int> {
                        0, 1
                    },
                    Shuffle = false,
                    State   = "PLAY_MODE",
                    Token   = "awesomeAudioPart1"
                }
            };

            Console.WriteLine("Save an AlexaAudioState object");
            await context.SaveAsync <AlexaAudioState>(currentState);

            Console.WriteLine("Getting an AlexaAudioState object");
            List <ScanCondition> conditions = new List <ScanCondition>();

            conditions.Add(new ScanCondition("UserId", ScanOperator.Equal, currentState.UserId));
            var allDocs = await context.ScanAsync <AlexaAudioState>(conditions).GetRemainingAsync();

            var savedState = allDocs.FirstOrDefault();

            Console.WriteLine("Verifying object...");
            if (JsonConvert.SerializeObject(savedState) == JsonConvert.SerializeObject(currentState))
            {
                Console.WriteLine("Object verified");
            }
            else
            {
                Console.WriteLine("oops, something went wrong");
            }

            //Console.WriteLine("Delete table => " + tableName);
            //context.Dispose();
            //await client.DeleteTableAsync(new DeleteTableRequest() { TableName = tableName });
        }
Пример #9
0
        public async Task <int> CreateAsync(Core.Excercise item)
        {
            var dynamoDBConfig = new AmazonDynamoDBConfig();

            dynamoDBConfig.ServiceURL = "http://localhost:8000/";
            var client = new AmazonDynamoDBClient(dynamoDBConfig);

            var tables = await client.ListTablesAsync();

            var currentTables = tables.TableNames;

            if (!currentTables.Contains(Excercises))
            {
                var request = new CreateTableRequest
                {
                    TableName            = Excercises,
                    AttributeDefinitions = new List <AttributeDefinition>
                    {
                        new AttributeDefinition
                        {
                            AttributeName = "Id",
                            AttributeType = "N"
                        },
                        new AttributeDefinition
                        {
                            AttributeName = "Name",
                            AttributeType = "S"
                        }
                    },
                    KeySchema = new List <KeySchemaElement>
                    {
                        new KeySchemaElement
                        {
                            AttributeName = "Id",
                            KeyType       = "HASH"
                        },
                        new KeySchemaElement
                        {
                            AttributeName = "Name",
                            KeyType       = "RANGE"
                        },
                    },
                    ProvisionedThroughput = new ProvisionedThroughput
                    {
                        ReadCapacityUnits  = 10,
                        WriteCapacityUnits = 5
                    },
                };

                var response = await client.CreateTableAsync(request, new System.Threading.CancellationToken());
            }

            Table excerciseCatalog = Table.LoadTable(client, Excercises);
            var   excercise        = new Document();

            excercise["Id"]   = item.Id;
            excercise["Name"] = item.Name;
            var excerciseEntry = await excerciseCatalog.PutItemAsync(excercise);

            return(1);
        }
Пример #10
0
        /// <summary>
        /// init DynamoDB table
        /// </summary>
        private void CreateTable()
        {
            var dynamoDbConfig = Configuration.GetSection("DynamoDb");

            var clientConfig = new AmazonDynamoDBConfig
            {
                ServiceURL = dynamoDbConfig.GetValue <string>("ServiceURL")
            };
            var client = new AmazonDynamoDBClient(clientConfig);

            CreateTable("Card", "EntityId");
            CreateTable("Audience", "EntityId");

            void CreateTable(string tableName, string hashKey)
            {
                // Low Level API: client
                Console.WriteLine("Verify table => " + tableName);
                var tableResponse = client.ListTablesAsync().Result;

                // client.DeleteTableAsync(tableName);
                // return;

                if (!tableResponse.TableNames.Contains(tableName))
                {
                    Console.WriteLine("Table not found, creating table => " + tableName);
                    client.CreateTableAsync(new CreateTableRequest
                    {
                        TableName             = tableName,
                        ProvisionedThroughput = new ProvisionedThroughput
                        {
                            ReadCapacityUnits  = 3,
                            WriteCapacityUnits = 1
                        },
                        KeySchema = new List <KeySchemaElement>
                        {
                            new KeySchemaElement
                            {
                                AttributeName = hashKey,
                                KeyType       = KeyType.HASH
                            }
                        },
                        AttributeDefinitions = new List <AttributeDefinition>
                        {
                            new AttributeDefinition
                            {
                                AttributeName = hashKey,
                                AttributeType = ScalarAttributeType.S
                            }
                        }
                    });

                    var isTableAvailable = false;
                    while (!isTableAvailable)
                    {
                        Console.WriteLine("Waiting for table to be active...");
                        Thread.Sleep(2000);
                        var tableStatus = client.DescribeTableAsync(tableName).Result;
                        isTableAvailable = tableStatus.Table.TableStatus == "ACTIVE";
                    }
                }
            }
        }
Пример #11
0
 internal static async Task <ListTablesResponse> Build(AmazonDynamoDBClient dynamodbClient)
 {
     return(await dynamodbClient.ListTablesAsync(new ListTablesRequest()));
 }