Example #1
0
        /// Returns a list of the entries that match the specified Global Secondary Index (GSI)
        /// @param secondaryIndexName - the name of the Global Secondary Index
        /// @param attributeKey the key of the column in the Database used as the GSI
        /// @param attributeValue the value to lookup on
        protected async Task <List <DatabaseItem> > GetEntriesBySecondaryIndex(string secondaryIndexName, string attributeKey, string attributeValue)
        {
            QueryRequest queryRequest = new QueryRequest
            {
                TableName = tableName,
                IndexName = secondaryIndexName,
                KeyConditionExpression   = "#attrKey = :v_value",
                ExpressionAttributeNames = new Dictionary <String, String> {
                    { "#attrKey", attributeKey }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":v_value", new AttributeValue {
                          S = attributeValue
                      } },
                },
                ScanIndexForward = true
            };

            try
            {
                var response = await client.QueryAsync(queryRequest);

                return(response.Items);
            }
            catch (Exception e)
            {
                log.WARN("DatabaseClient", "GetEntriesBySecondaryIndex", "EXCEPTION: " + e.Message);
            }

            return(new List <DatabaseItem>());
        }
Example #2
0
        private async void Sequential_Click(object sender, EventArgs e)
        {
            int k = 0;

            using (AmazonDynamoDBClient client = new AmazonDynamoDBClient(Amazon.RegionEndpoint.EUWest2))
            {
                while (k < 1000)
                {
                    Task queryResultsTask = Task.Run(async() =>
                    {
                        try
                        {
                            await client.QueryAsync(_queryRequest);
                            Debug.Print($"{k}");
                        }
                        catch (Exception ex)
                        {
                            Debug.Print(ex.Message);
                        }
                    });

                    await queryResultsTask;
                    k++;
                }
            }
        }
        private async Task <QueryResponse> GetByIdAsync(Guid id)
        {
            Logger.Log($"Scanning DynamoDB for aggregate: {id}");

            // Read events from DynamoDB
            var request = new QueryRequest
            {
                TableName = _tableName,
                KeyConditionExpression    = "Id = :v_Id and Version > :v_Version",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":v_Id", new AttributeValue {
                          S = $"\"{id.ToString()}\""
                      } },
                    { ":v_Version", new AttributeValue {
                          S = "0"
                      } }
                }
            };

            var response = await _dynamoDbClient.QueryAsync(request);

            Logger.Log($"Found items: {response.Items.Count}");

            return(response);
        }
        public static async void FindRepliesForAThread(AmazonDynamoDBClient client)
        {
            Console.WriteLine("*** Executing FindRepliesForAThread() ***");
            string replyId = ForumName + "#" + ThreadSubject;

            var request = new QueryRequest
            {
                TableName = "Reply",
                ReturnConsumedCapacity    = "TOTAL",
                KeyConditionExpression    = "Id = :v_replyId",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":v_replyId", new AttributeValue {
                          S = replyId
                      } }
                }
            };

            var response = await client.QueryAsync(request);

            Console.WriteLine("No. of reads used (by query in FindRepliesForAThread) {0}\n",
                              response.ConsumedCapacity.CapacityUnits);
            foreach (Dictionary <string, AttributeValue> item in response.Items)
            {
                PrintItem(item);
            }
            Console.WriteLine("To continue, press Enter");
            Console.ReadLine();
        }
        private async Task <List <DocumentDetails> > GetLettersWithStatus(LetterStatusEnum status)
        {
            var tableName    = _documentsTable.TableName;
            var queryRequest = new QueryRequest
            {
                TableName                = tableName,
                IndexName                = "Status",
                ScanIndexForward         = true,
                KeyConditionExpression   = "#status = :value",
                ExpressionAttributeNames = new Dictionary <string, string> {
                    { "#status", "Status" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":value", new AttributeValue {
                          S = status.ToString()
                      } },
                },
            };
            var results = await _databaseClient.QueryAsync(queryRequest);

            return(results.Items.Select(entry => new DocumentDetails
            {
                DocumentCreator = entry["DocumentCreatorUserName"].S?.ToString(),
                CominoDocumentNumber = entry["CominoDocumentNumber"].S?.ToString(),
                DocumentType = entry["DocumentType"].S?.ToString(),
                LetterType = entry["LetterType"].S?.ToString(),
                Id = entry["InitialTimestamp"].S?.ToString(),
                Date = entry["InitialTimestamp"].S?.ToString(),
                Status = Enum.Parse <LetterStatusEnum>(entry["Status"].S?.ToString()),
                GovNotifyNotificationId = entry.ContainsKey("GovNotifyNotificationId")
                    ? entry["GovNotifyNotificationId"].S?.ToString()
                    : null,
            }).ToList());
        }
Example #6
0
        private async Task <string> GetUserFromSession(string session)
        {
            // Update Database counter so we have to get user from dynamod db (from session)
            AmazonDynamoDBClient clientDynamoDB = new AmazonDynamoDBClient(
                new BasicAWSCredentials(_settings.AWSAccessKey, _settings.AWSSecretKey),
                RegionEndpoint.EUWest1
                );

            var request = new QueryRequest
            {
                TableName = _settings.SessionTableName,
                KeyConditionExpression    = "sessions = :s1",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":s1", new AttributeValue {
                          S = session
                      } }
                }
            };

            var response = await clientDynamoDB.QueryAsync(request);

            var sessionInfo = response.Items.FirstOrDefault();

            if (sessionInfo != null)
            {
                return(sessionInfo["user"].N);
            }

            return("");
        }
Example #7
0
        public Customer GetCustomer(string id)
        {
            var dynamoDbClient = new AmazonDynamoDBClient();

            string tableName = "Customer";

            var request = new QueryRequest
            {
                TableName = tableName,
                KeyConditionExpression    = "Id = :v_Id",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":v_Id", new AttributeValue {
                          S = id
                      } }
                }
            };

            var response = dynamoDbClient.QueryAsync(request).Result;
            var item     = response.Items.First();

            var customerName = item["CustomerName"].S;

            return(new Customer {
                Id = id, CustomerName = customerName
            });
        }
Example #8
0
        public static async Task GetBatchRequest(string tableName)
        {
            var request = new QueryRequest
            {
                TableName = "service-list",
                IndexName = "service-list-gsi",
                KeyConditionExpression    = "ItemType = :v_ItemType",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":v_ItemType", new AttributeValue {
                          S = "product#master"
                      } }
                }
            };

            try
            {
                var response = await client.QueryAsync(request);

                foreach (Dictionary <string, AttributeValue> item in response.Items)
                {
                    // Process the result.
                    Console.WriteLine(item.Values.ToString());
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }
        public async Task <ActionResult> Get(string game)
        {
            Console.WriteLine("Leaderboard: GET");

            var request = new QueryRequest
            {
                TableName = "leaderboard",
                KeyConditionExpression    = "Game = :v_Game",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":v_Game", new AttributeValue {
                          S = game
                      } }
                }
            };
            var response = await _client.QueryAsync(request);

            if (response.Items.Count == 0)
            {
                return(NotFound());
            }

            List <LeaderboardEntry> output = new List <LeaderboardEntry>();

            foreach (var item in response.Items)
            {
                output.Add(new LeaderboardEntry()
                {
                    Game   = item["Game"].S,
                    Player = item["Name"].S,
                    Rank   = int.Parse(item["Rank"].N)
                });
            }

            return(new JsonResult(output));
        }
Example #10
0
        public async Task <int> ObtenerPrioridadLocal()
        {
            AmazonDynamoDBClient client = new AmazonDynamoDBClient();
            string tableName            = "Configuracion";

            var request = new QueryRequest
            {
                TableName = tableName,
                KeyConditionExpression    = "nombre = :v_nombre",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":v_nombre", new AttributeValue {
                          S = "prioridad"
                      } }
                }
            };

            var response = await client.QueryAsync(request);

            int prioridad = 0;

            foreach (Dictionary <string, AttributeValue> item in response.Items)
            {
                AttributeValue cellValue = item["valor"];
                prioridad = Convert.ToInt32(cellValue.N);
            }

            return(prioridad);
        }
Example #11
0
        private async Task <AlbumFull> GetAlbumFull(string albums_table, string album_key)
        {
            var client = new AmazonDynamoDBClient();

            var conditions = new Dictionary <string, Condition> {
                // Hash key condition
                {
                    "partition_key",
                    new Condition {
                        ComparisonOperator = "EQ",
                        AttributeValueList = new List <AttributeValue> {
                            new AttributeValue {
                                S = album_key
                            }
                        }
                    }
                }
            };

            var db_request = new QueryRequest
            {
                TableName     = albums_table,
                KeyConditions = conditions
            };

            AlbumFull album = new AlbumFull {
                Photos = new List <Photo>()
            };


            var result = await client.QueryAsync(db_request);

            Console.WriteLine($"album docs: [{result.Items?.Count}]");

            result.Items.ForEach((ph) => {
                if (ph["sort_key"].S == "alb")
                {
                    album.Album = Album.DocToObject(ph);
                }
                else
                {
                    var photo = new Photo {
                        PartitionKey     = ph["partition_key"].S,
                        SortKey          = ph["sort_key"].S,
                        DateCreated      = ph["datecreated"].S,
                        Filename         = ph.ContainsKey("filename") ? ph["filename"].S: "",
                        LastModifiedDate = !ph.ContainsKey("last_modified_date") ? "": ph["last_modified_date"].S,
                        OriginalFilename = !ph.ContainsKey("original_filename") ? "":ph["original_filename"].S,
                        Size             = !ph.ContainsKey("size") ? 0:Convert.ToDouble(ph["size"].N),
                        Type             = !ph.ContainsKey("type") ? "":ph["type"].S,
                        Comment          = !ph.ContainsKey("comment") ? "": ph["comment"].S,
                        EventDate        = !ph.ContainsKey("event_date") ? "": ph["event_date"].S
                    };

                    album.Photos.Add(photo);
                }
            });

            return(album);
        }
Example #12
0
        public async Task <int> GetNextPostIdAsync()
        {
            using (_logger.BeginScope("Getting next post id"))
            {
                var request = new QueryRequest(TableName)
                {
                    Limit = 1,
                    KeyConditionExpression    = "id = :v_Id",
                    ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                    {
                        [":v_Id"] = new AttributeValue("post")
                    },
                    ProjectionExpression = "postId",
                    ScanIndexForward     = false
                };
                var sw     = Stopwatch.StartNew();
                var result = await _client.QueryAsync(request);

                _logger.LogInformation($"response status = {result.HttpStatusCode}; time = {(int) sw.ElapsedMilliseconds} ms");
                if (result.HttpStatusCode != HttpStatusCode.OK)
                {
                    throw new Exception($"Failed to get next post id. Response status {result.HttpStatusCode}");
                }

                var lastPost  = result.Items.Single();
                var newPostId = int.Parse(lastPost["postId"].N) + 1;
                _logger.LogInformation($"Providing next post id = {newPostId}");
                return(newPostId);
            }
        }
 public async Task<List<AdminAuditRecord>> GetAuditByUser(string user, int recordLimit)
 {
     var tableName = _documentsTable.TableName;
     var queryRequest = new QueryRequest
     {
         TableName = tableName,
         Limit = recordLimit,
         ScanIndexForward = false,
         KeyConditionExpression = "#User = :value",
         ExpressionAttributeNames = new Dictionary<string, string> { { "#User", "User" } },
         ExpressionAttributeValues = new Dictionary<string, AttributeValue>
         {
             {":value", new AttributeValue {S = user}},
         },
     };
     var results = await _databaseClient.QueryAsync(queryRequest);
     return results.Items.Select(entry => new AdminAuditRecord
     {
         User = entry["User"].S?.ToString(),
         RentAccountNumber = entry["RentAccountNumber"].S?.ToString(),
         TimeStamp = entry["TimeStamp"].S?.ToString(),
         CSSOLogin = entry["CSSOLogin"].S?.ToString(),
         AuditAction = entry["AuditAction"].S?.ToString()
     }).ToList(); //TODO: how do we deal with database entries that have empty columns? i.e. records created prior to a new column being added.
 }
Example #14
0
        public async Task <User> GetUser(string username)
        {
            var query = new QueryRequest("Users");

            query.KeyConditionExpression = "UserName = :un";
            var userAttrs = new Dictionary <string, AttributeValue>
            {
                { ":un", new AttributeValue(username) },
            };

            query.ExpressionAttributeValues = userAttrs;
            var queryResult = await Client.QueryAsync(query);

            if (queryResult.Count == 0)
            {
                return(null);
            }
            var firstUser = queryResult.Items[0];

            return(new User
            {
                Username = firstUser["UserName"].S,
                Password = firstUser["Password"].S,
                SecondayPassword = firstUser.ContainsKey("SecondayPassword") ? firstUser["SecondayPassword"].S : null,
                UserId = firstUser.ContainsKey("UserID") ? int.Parse(firstUser["UserID"].N) : (int?)null,
            });
        }
        public void Run(APIGatewayProxyRequest request, APIGatewayProxyResponse response)
        {
            var source       = request.QueryStringParameters["source"];
            var pageId       = request.QueryStringParameters["pageId"];
            var queryRequest = new QueryRequest(new ClassificationModel().GetTable())
            {
                ScanIndexForward          = true,
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":source", new AttributeValue {
                          S = source
                      } },
                    { ":pageId", new AttributeValue {
                          S = pageId
                      } }
                },
                ExpressionAttributeNames = new Dictionary <string, string>
                {
                    { "#source", "source" },
                    { "#pageId", "pageId" }
                },
                KeyConditionExpression = "#source = :source AND #pageId = :pageId",
                Limit = 1
            };
            var client        = new AmazonDynamoDBClient();
            var queryResponse = client.QueryAsync(queryRequest).Result;
            var item          = queryResponse.Items.FirstOrDefault();

            response.Body = Document.FromAttributeMap(item).ToJson();
        }
Example #16
0
        public async Task <int> GetOrderId()
        {
            AmazonDynamoDBClient client = new AmazonDynamoDBClient();
            string tableName            = "Secuencias";


            var request = new QueryRequest
            {
                TableName = tableName,
                KeyConditionExpression    = "Id = :v_Id",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":v_Id", new AttributeValue {
                          S = "Orden"
                      } }
                }
            };

            var response = await client.QueryAsync(request);

            int nextOrderId = 0;

            foreach (Dictionary <string, AttributeValue> item in response.Items)
            {
                AttributeValue avSecuencia = item["nextSecuencia"];
                nextOrderId = Convert.ToInt32(avSecuencia.N);
            }

            var requestUpdate = new UpdateItemRequest
            {
                TableName = tableName,
                Key       = new Dictionary <string, AttributeValue>()
                {
                    { "Id", new AttributeValue {
                          S = "Orden"
                      } }
                },
                ExpressionAttributeNames = new Dictionary <string, string>()
                {
                    { "#NS", "nextSecuencia" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>()
                {
                    { ":NS", new AttributeValue {
                          N = (nextOrderId + 1).ToString()
                      } },
                    { ":OS", new AttributeValue {
                          N = (nextOrderId).ToString()
                      } }
                },
                ConditionExpression = "#NS = :OS",

                UpdateExpression = "SET #NS = :NS"
            };

            var responseUpdate = await client.UpdateItemAsync(requestUpdate);

            return(nextOrderId);
        }
Example #17
0
        /// <summary>
        /// Click do botão Login
        /// </summary>
        private async Task ObterRelacaoServicosAsync()
        {
            try
            {
                // Mostra a tela de aguarde
                MessagingCenterHelper.TelaAguardeMostrar(this);

                // Verifica se o token do usuário logado ainda é válido
                await LoginService.VerifyIdToken();

                // Obtém dados do DynamoDB
                AmazonDynamoDBClient client  = AwsHelper.AmazonDynamoDBClient;
                DynamoDBContext      context = AwsHelper.DynamoDBContext;

                QueryRequest request = new QueryRequest
                {
                    TableName = Servico.TabelaNome,
                    KeyConditionExpression    = "(PK = :v_PK) AND begins_with(SK, :v_SK)",
                    ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                    {
                        { ":v_PK", new AttributeValue {
                              S = Servico.PkChave
                          } },
                        { ":v_SK", new AttributeValue {
                              S = Servico.SkChave
                          } }
                    }
                };

                // Retorno
                QueryResponse response = await client.QueryAsync(request);

                // Converte o retorno para lista de objetos
                List <Servico> listaRetorno = new List <Servico>();
                foreach (Dictionary <string, AttributeValue> item in response.Items)
                {
                    listaRetorno.Add(context.FromDocument <Servico>(Document.FromAttributeMap(item)));
                }

                // Atualiza a lista
                this.ListaServicos.AddRange(listaRetorno.OrderBy(x => x.Descricao));
            }
            catch (MobileErrorException e)
            {
                MessagingCenterHelper.ExibirMensagem(MobileErrorException.GetMessageFull(e), MessageBox.TipoMensagem.Atencao);
            }
            catch (Exception e)
            {
                MobileErrorException.EnviarErroAppCenter(e);
                MessagingCenterHelper.ExibirMensagem(MobileErrorException.GetMessageFull(e, true), MessageBox.TipoMensagem.Erro);
            }
            finally
            {
                MessagingCenterHelper.TelaAguardeFechar(this);
            }
        }
Example #18
0
        public async Task <APIGatewayProxyResponse> GetAlbum(APIGatewayProxyRequest req, ILambdaContext context)
        {
            var logger = context.Logger;

            logger.LogLine($"request {JsonConvert.SerializeObject(req)}");
            logger.LogLine($"context {JsonConvert.SerializeObject(context)}");

            var albumsTablename = Environment.GetEnvironmentVariable("ALBUMS_TABLE");

            logger.LogLine($"albumsTablename {albumsTablename}");

            var partition_key = req.PathParameters["PartitionKey"];

            var client = new AmazonDynamoDBClient();

            var db_request = new QueryRequest
            {
                TableName = albumsTablename,
                KeyConditionExpression    = "partition_key = :v_Id AND sort_key = :alb",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":v_Id", new AttributeValue {
                          S = partition_key
                      } },
                    { ":alb", new AttributeValue {
                          S = "alb"
                      } }
                }
            };

            Album album;
            var   result = await client.QueryAsync(db_request);

            if (result.Items.Count > 0)
            {
                logger.LogLine($"album result: [{JsonConvert.SerializeObject(result)}]");

                // Get first item
                var item = result.Items[0];
                album = Album.DocToObject(item);
            }
            else
            {
                throw new KeyNotFoundException($"No items received for partition_key [{partition_key}]");
            }

            return(new APIGatewayProxyResponse {
                StatusCode = 200,
                Headers = new Dictionary <string, string> ()
                {
                    { "Access-Control-Allow-Origin", "*" },
                    { "Access-Control-Allow-Credentials", "true" }
                },
                Body = JsonConvert.SerializeObject(album)
            });
        }
        public static Dictionary <string, string> GetDynamoDbAttributesTable(string dynamoDbName)
        {
            try
            {
                var client = new AmazonDynamoDBClient(
                    new AmazonDynamoDBConfig
                {
                    RegionEndpoint   = RegionEndpoint.EUWest1,
                    ProxyCredentials = CredentialCache.DefaultCredentials
                });

                var query = new QueryRequest
                {
                    TableName = dynamoDbName,
                    KeyConditionExpression   = "#datetimeAttribute = :datetimeValue",
                    ExpressionAttributeNames =
                        new Dictionary <string, string> {
                        { "#datetimeAttribute", "Datetime" }
                    },
                    ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                    {
                        {
                            ":datetimeValue",
                            new AttributeValue(dynamoDbName)
                        }
                    },
                    ScanIndexForward = false
                };

                var attributes = new Dictionary <string, string>();
                var response   = client.QueryAsync(query).Result;
                if (response.Items.Any())
                {
                    foreach (var item in response.Items.First())
                    {
                        if (!string.IsNullOrWhiteSpace(item.Value.S) && !string.Equals(
                                item.Key,
                                "Datetime",
                                StringComparison.InvariantCultureIgnoreCase))
                        {
                            attributes[item.Key] = item.Value.S;
                        }
                    }
                }

                return(attributes);
            }
            catch (Exception ex)
            {
                Logger?.Error(ex, "Error while loading dynamo configuration.");
            }

            return(new Dictionary <string, string>());
        }
Example #20
0
        public List <Quote> GetAllQuotesByQuotee(string quotee)
        {
            var result = _db.QueryAsync(new QueryRequest
            {
                TableName = TableName,
                ExpressionAttributeValues = { [":quotee"] = new AttributeValue(quotee) },
                KeyConditionExpression    = "Quotee = :quotee"
            }).Result;

            return(result.Items.Select(item => ParseQuote(item)).ToList());
        }
Example #21
0
        public async System.Threading.Tasks.Task <List <ResponseModel> > HelloAsync(Request request)
        {
            var DBClient = new AmazonDynamoDBClient();

            var result = new QueryRequest
            {
                TableName = "qa-device-data",
                KeyConditionExpression    = "dserial = :v_DeviceSerial",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":v_DeviceSerial", new AttributeValue {
                          S = request.DeviceSerial.ToString()
                      } }
                },
                ProjectionExpression = "dserial, dtype,con",
                ConsistentRead       = true
            };
            var Response = await DBClient.QueryAsync(result);

            Console.WriteLine(Response);
            var getResult  = new ResponseModel();
            var Deviceinfo = new List <ResponseModel>();

            foreach (Dictionary <string, AttributeValue> item in Response.Items)
            {
                foreach (KeyValuePair <string, AttributeValue> key in item)
                {
                    string         attributeName = key.Key;
                    AttributeValue value         = key.Value;
                    getResult.dserial = value.S;
                    getResult.con     = value.N;
                    getResult.dtype   = value.N;
                    Deviceinfo.Add(getResult);
                    //Console.WriteLine(
                    //    attributeName + " " +
                    //    (value.S == null ? "" : "S=[" + value.S + "]") +
                    //    (value.N == null ? "" : "N=[" + value.N + "]") +
                    //    (value.SS == null ? "" : "SS=[" + string.Join(",", value.SS.ToArray()) + "]") +
                    //    (value.NS == null ? "" : "NS=[" + string.Join(",", value.NS.ToArray()) + "]")
                    //);
                }
            }
            Console.WriteLine("************************************************");

            /*  var ListofMsgs = new List<Response>();
             *    Dictionary<string, AttributeValue> list = new Dictionary<string, AttributeValue>();
             * foreach (Dictionary<string,AttributeValue> item in Response.Items)
             * {
             *    list.Add(item,value
             * }
             *
             * return new Response("Go Serverless v1.0! Your function executed successfully!", request.DeviceSerial);*/
            return(Deviceinfo);
        }
        private async Task ReadSeries(int?rowCount, string seriesKey, bool useGroupedTable)
        {
            using (var client = new AmazonDynamoDBClient(credentials, config))
            {
                var readFromTableName = useGroupedTable
                    ? groupedTableName
                    : tableName;

                var count = 0;

                Dictionary <string, AttributeValue> lastReadKey = null;

                while (true)
                {
                    var request = new QueryRequest
                    {
                        TableName                 = readFromTableName,
                        ConsistentRead            = false,
                        ExclusiveStartKey         = lastReadKey,
                        KeyConditionExpression    = "seriesKey=:seriesKey",
                        ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                        {
                            [":seriesKey"] = new AttributeValue {
                                S = seriesKey
                            }
                        },
                    };

                    try
                    {
                        var response = await client.QueryAsync(request);

                        count += response.Items.Count;
                        Interlocked.Add(ref totalCount, response.Items.Count);

                        await output.WriteLineAsync($"Read {count} records from dataset '{seriesKey}' in: {readFromTableName}");

                        if (response.LastEvaluatedKey.Any() && count <= rowCount.GetValueOrDefault(int.MaxValue))
                        {
                            lastReadKey = response.LastEvaluatedKey;
                        }
                        else
                        {
                            break;
                        }
                    }
                    catch (AmazonDynamoDBException ex)
                    {
                        await output.WriteLineAsync(ex.Message);
                    }
                }
            }
        }
Example #23
0
        public async Task <APIGatewayProxyResponse> GetArchiveAlbums(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var logger = context.Logger;

            logger.LogLine($"request {JsonConvert.SerializeObject(request)}");
            logger.LogLine($"context {JsonConvert.SerializeObject(context)}");

            var archiveTablename = Environment.GetEnvironmentVariable("ARCHIVE_TABLE");

            logger.LogLine($"archiveTablename {archiveTablename}");


            var client = new AmazonDynamoDBClient();
            var table  = Table.LoadTable(client, archiveTablename);

            var db_request = new QueryRequest
            {
                TableName = archiveTablename,
                IndexName = "gsiAlbums",
                KeyConditionExpression    = "sort_key = :v_Id",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":v_Id", new AttributeValue {
                          S = "alb"
                      } }
                }
            };

            var albumList = new List <ArchiveAlbum>();
            var result    = await client.QueryAsync(db_request);

            result.Items.ForEach(item => {
                var album = new ArchiveAlbum {
                    Name         = item["name"].S,
                    Owner        = item["owner"].S,
                    Year         = Convert.ToInt32(item["year"].N),
                    Id           = new Guid(item["id"].S),
                    DateCreated  = item["datecreated"].S,
                    DateArchived = item["date_archived"].S
                };
                albumList.Add(album);
            });

            return(new APIGatewayProxyResponse {
                StatusCode = 200,
                Headers = new Dictionary <string, string> ()
                {
                    { "Access-Control-Allow-Origin", "*" },
                    { "Access-Control-Allow-Credentials", "true" }
                },
                Body = JsonConvert.SerializeObject(albumList)
            });
        }
        private IDictionary <string, string> FetchEc2Data(string environmentClientId)
        {
            var client = new AmazonDynamoDBClient(
                new AmazonDynamoDBConfig
            {
                RegionEndpoint = RegionEndpoint.EUWest1, ProxyCredentials = CredentialCache.DefaultCredentials
            });

            var query = new QueryRequest
            {
                TableName = DynamoDbTable,
                KeyConditionExpression   = "#NameAttribute = :NameValue",
                ExpressionAttributeNames = new Dictionary <string, string> {
                    { "#NameAttribute", "name" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":NameValue", new AttributeValue(environmentClientId) }
                }
            };

            var attributes = new Dictionary <string, string>();

            try
            {
                var response = client.QueryAsync(query).Result;

                if (response.Items.Any())
                {
                    foreach (var item in response.Items.First())
                    {
                        if (!string.IsNullOrWhiteSpace(item.Value.S))
                        {
                            attributes[item.Key] = item.Value.S;
                        }
                    }
                }

                this._hasFetchedEc2Data = true;
                var casedAttributes = attributes.ToDictionary(i => i.Key?.ToLower(), i => i.Value);

                return(casedAttributes);
            }
            catch (Exception ex)
            {
                Logger?.Error(ex, "Error while loading dynamo configuration.");
                this._hasFetchedEc2Data = true;
            }

            return(new Dictionary <string, string>());
        }
Example #25
0
        public async Task <DateTime> GetLastReplyTime()
        {
            DateTime lastReplyTime = new DateTime();

            var request = new QueryRequest
            {
                TableName = "RepliesOfAvasarala",
                IndexName = "dummy-replyTime-index",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":vDummy", new AttributeValue {
                          N = "1"
                      } }
                },
                KeyConditionExpression = "dummy = :vDummy",
                ScanIndexForward       = false,
                Limit = 1
            };

            var response = await _client.QueryAsync(request);

            LambdaLogger.Log($"Items Count: {response.Items.Count}\n");

            Boolean found           = false;
            Int64   replyTimeNumber = 0;

            foreach (Dictionary <string, AttributeValue> item in response.Items)
            {
                found = Int64.TryParse(item["replyTime"].N, out replyTimeNumber);
            }

            if (found)
            {
                //20210131235959
                Int32 second = (Int32)(replyTimeNumber % 100);
                replyTimeNumber /= 100;
                Int32 minute = (Int32)(replyTimeNumber % 100);
                replyTimeNumber /= 100;
                Int32 hour = (Int32)(replyTimeNumber % 100);
                replyTimeNumber /= 100;
                Int32 day = (Int32)(replyTimeNumber % 100);
                replyTimeNumber /= 100;
                Int32 month = (Int32)(replyTimeNumber % 100);
                replyTimeNumber /= 100;
                Int32 year = (Int32)(replyTimeNumber);
                lastReplyTime = new DateTime(year, month, day, hour, minute, second);
                LambdaLogger.Log($"Year {year}, month {month}, day {day}, hour {hour}, minute {minute}, second {second}\n");
            }

            return(lastReplyTime);
        }
Example #26
0
        public async Task <IEnumerable <string> > GetRunnableInstances(DateTime asAt)
        {
            var result = new List <string>();
            var now    = asAt.ToUniversalTime().Ticks;

            var request = new QueryRequest()
            {
                TableName                 = $"{_tablePrefix}-{WORKFLOW_TABLE}",
                IndexName                 = "ix_runnable",
                ProjectionExpression      = "id",
                KeyConditionExpression    = "runnable = :r and next_execution <= :effective_date",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    {
                        ":r", new AttributeValue()
                        {
                            N = 1.ToString()
                        }
                    },
                    {
                        ":effective_date", new AttributeValue()
                        {
                            N = Convert.ToString(now)
                        }
                    }
                },
                ScanIndexForward = true
            };

            var response = await _client.QueryAsync(request);

            foreach (var item in response.Items)
            {
                result.Add(item["id"].S);
            }

            return(result);
        }
Example #27
0
 public Task <QueryResponse> QueryAsync(QueryRequest request, CancellationToken cancellationToken = default)
 {
     Guard.ArgumentNotNull(request, "request can not be null");
     try
     {
         AmazonDynamoDBClient client = GetAmazonDynamoDbClient();
         var result = client.QueryAsync(request);
         return(result);
     }
     catch (AmazonDynamoDBException ex)
     {
         throw ex;
     }
 }
        public async Task RequestSquad(SquadRequestDTO squadDTO)
        {
            var request = new QueryRequest
            {
                TableName = "GameTable",
                KeyConditionExpression    = "SquadId = :v_SquadId",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":v_SquadId", new AttributeValue {
                          S = squadDTO.SquadId
                      } }
                }
            };
            var results = await _client.QueryAsync(request);

            SquadRequestReceived(this, results.Items);
        }
Example #29
0
        private static int GetTableNextKeyIndex(AmazonDynamoDBClient client, string env, string key)
        {
            var tableName = "LLC-Meta" + env;
            var resp      = client.QueryAsync(new QueryRequest
            {
                TableName = tableName,
                KeyConditionExpression    = "Id = :v_Id",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":v_Id", new AttributeValue {
                          S = key
                      } }
                }
            }).Result;

            return(int.Parse(resp.Items[0]["Key"].N));
        }
        public async Task <APIGatewayProxyResponse> Hello(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var clientConfig = new AmazonDynamoDBConfig()
            {
                RegionEndpoint = Amazon.RegionEndpoint.USWest2
            };

            var client = new AmazonDynamoDBClient(clientConfig);
            var query  = new QueryRequest
            {
                TableName = System.Environment.GetEnvironmentVariable("DYNAMODB_TABLE"),
                IndexName = System.Environment.GetEnvironmentVariable("DYNAMODB_GSI_USERID_NOTEID"),
                KeyConditionExpression   = "userId = :userId",
                ProjectionExpression     = "userId, noteId, notebook, #note_text",
                ExpressionAttributeNames = new Dictionary <string, string> {
                    { "#note_text", "text" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":userId", new AttributeValue {
                          S = "arbiter"
                      } }
                },
                ScanIndexForward = desc
            };

            var cleaned = new Dictionary <string, AttributeValue>();

            QueryResponse results = null;

            results = await client.QueryAsync(query);

            foreach (var item in results.Items)
            {
                item.ToList().ForEach(x => cleaned[x.Key] = x.Value);
            }

            var headers = new Dictionary <string, string>();

            headers.Add("Content-Type", "application/json");

            return(await Task.Run(() => new APIGatewayProxyResponse()
            {
                StatusCode = (int)HttpStatusCode.OK,
                Headers = headers,
                Body = JsonConvert.SerializeObject(new { results = cleaned })
            }));
        }