Exemplo n.º 1
0
        public async Task <List <Quote> > GetAllStatements()
        {
            var statements = new List <Quote>();

            var request = new ScanRequest
            {
                TableName = "WisdomOfAvasarala",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":s", new AttributeValue {
                          S = "1"
                      } },
                    { ":t", new AttributeValue {
                          S = "0"
                      } }
                },
                FilterExpression = "statement = :s AND tweeted = :t"
            };

            var resp = await _client.ScanAsync(request);

            foreach (Dictionary <string, AttributeValue> item in resp.Items)
            {
                var quote = new Quote();
                quote.medium = item["medium"].S;
                if (quote.medium == "TV")
                {
                    quote.uuid        = item["uuid"].S;
                    quote.season      = item["season"].S;
                    quote.episode     = item["episode"].S;
                    quote.runningTime = item["runningTime"].S;
                }
                Boolean found;
                if (quote.medium == "Book")
                {
                    found         = Int32.TryParse(item["page"].S, out Int32 page);
                    quote.uuid    = item["uuid"].S;
                    quote.book    = item["book"].S;
                    quote.chapter = item["chapter"].S;
                    quote.page    = (found ? page : 0);
                }

                found           = Int32.TryParse(item["quality"].S, out Int32 quality);
                quote.quality   = (found ? quality : 0);
                quote.polite    = item["polite"].S == "1";
                quote.statement = item["statement"].S == "1";
                quote.reply     = item["reply"].S == "1";
                quote.tweeted   = item["tweeted"].S == "1";
                quote.quoteText = item["quote"].S;

                statements.Add(quote);
            }

            LambdaLogger.Log($"Statements Count: {statements.Count}\n");

            return(statements);
        }
Exemplo n.º 2
0
        private static List <string> ReadCustomerTable()
        {
            var result        = new List <string>();
            var tableName     = "SummitCustomer"; //"gracecustomer";
            var customerTable = Table.LoadTable(dynamoclient, tableName);

            var request = new ScanRequest
            {
                TableName = tableName
            };

            var scanResult = dynamoclient.ScanAsync(request).Result;

            foreach (Dictionary <string, AttributeValue> item in scanResult.Items)
            {
                // Process the result.
                var dtid      = Int32.Parse(item["DTID"].N);
                var lastName  = item["LastName"].S;
                var firstName = item["FirstName"].S;
                var id        = Int32.Parse(item["Id"].N);
                var address   = item["Address"].M;
                var addr1     = address["Addr1"].S;
                var city      = address["City"].S;
                var state     = address["State"].S;
                var zip       = address["Zip"].S;
                var contacts  = item["Contacts"].M; // this doesn't work - how do you get contacts out? it's not recognized as a valid key
                var emails    = contacts["Email_addresses"].SS ?? new List <string>();
                var mobile    = contacts.ContainsKey("Mobile") ? (contacts["Mobile"].S ?? string.Empty) : string.Empty;
                var homephone = contacts.ContainsKey("Homephone") ? (contacts["Homephone"].S ?? string.Empty) : string.Empty;
                var workphone = contacts.ContainsKey("Workphone") ? (contacts["Workphone"].S ?? string.Empty) : string.Empty;
                var employer  = contacts.ContainsKey("Employer") ? (contacts["Employer"].S ?? string.Empty) : string.Empty;

                var customerObj = new Customer
                {
                    LastName       = lastName,
                    FirstName      = firstName,
                    Id             = id,
                    DTID           = dtid,
                    Address1       = addr1,
                    City           = city,
                    State          = state,
                    Zip            = zip,
                    EmailAddresses = emails,
                    MobilePhone    = mobile,
                    WorkPhone      = workphone,
                    HomePhone      = homephone,
                    Employer       = employer
                };
                result.Add(JsonConvert.SerializeObject(customerObj));
                // var deserialized = JsonConvert.DeserializeObject<SomeObject>(jsonString);
            }

            return(result);
        }
Exemplo n.º 3
0
        public void GetAllItmes(string tableName)
        {
            var request = new ScanRequest
            {
                TableName = tableName,
            };
            //var context = new DynamoDBContext(DynomoClient);
            var response = DynomoClient.ScanAsync(request);

            foreach (var item in response.Result.Items)
            {
                PrintItem(item);
                Console.WriteLine("=====");
            }
        }
        public async Task <APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context)
        {
            APIGatewayProxyResponse resp = new APIGatewayProxyResponse();

            var client = new AmazonDynamoDBClient();

            GetItemRequest getItemRequest = new GetItemRequest()
            {
                TableName = "endearing-otter-blocks",
            };
            var blocks =
                await client.ScanAsync(new ScanRequest()
            {
                TableName       = "endearing-otter-blocks",
                AttributesToGet =
                {
                    "block_id",
                    "block_name"
                }
            });

            resp.Body = "";

            foreach (var item in blocks.Items)
            {
                resp.Body += $"Block {item["block_id"].N} - {item["block_name"].S}_-_";
            }

            var locations =
                await client.ScanAsync(new ScanRequest()
            {
                TableName       = "endearing-otter-locations",
                AttributesToGet =
                {
                    "location_id",
                    "location_name"
                }
            });

            foreach (var item in locations.Items)
            {
                resp.Body += $"Location {item["location_id"].N} - {item["location_name"].S}_-_";
            }



            return(resp);
        }
        public async Task <List <GamesListItem> > GetList(CancellationToken cancellationToken)
        {
            var request = new ScanRequest
            {
                TableName = _tableName
            };

            var response = await _dbClient.ScanAsync(request, cancellationToken);

            var games = response.Items.Select(r =>
            {
                var g              = new GamesListItem();
                g.Id               = r["id"].S;
                g.Status           = r["status"].S;
                g.Result           = r["result"].S;
                g.WaitingForPlayer = r["waiting_for_player"].S;
                var create_utc_str = r["create_utc"].S;
                if (DateTimeOffset.TryParse(create_utc_str, out DateTimeOffset createdUtc))
                {
                    g.CreatedUtc = createdUtc;
                }

                var updated_utc_str = r["update_utc"].S;
                if (DateTimeOffset.TryParse(updated_utc_str, out DateTimeOffset updatedUtc))
                {
                    g.LastUpdatedUtc = updatedUtc;
                }

                return(g);
            });

            return(games.ToList());
        }
        public async Task RequestOtherSquads(string gameId, string playerId)
        {
            var request = new ScanRequest
            {
                TableName = "GameTable",
                ExpressionAttributeNames = new Dictionary <string, string>
                {
                    { "#gameId", "GameId" },
                    { "#playerId", "PlayerId" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":v_GameId", new AttributeValue {
                          S = gameId
                      } },
                    { ":v_PlayerId", new AttributeValue {
                          S = playerId
                      } }
                },
                FilterExpression     = "#gameId = :v_GameId and #playerId <> :v_PlayerId",
                ProjectionExpression = "#gameId, SquadId, PlayerId, SquadData"
            };

            var results = await _client.ScanAsync(request);

            SquadsRequestReceived(this, results.Items);
        }
Exemplo n.º 7
0
        public bool Exists(Name driverName)
        {
            var request = new ScanRequest
            {
                TableName = _targetTableName,
                //AttributesToGet = new List<string> {nameof(Driver.Id)},
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":firstName", new AttributeValue {
                          S = driverName.FirstName
                      } },
                    { ":lastName", new AttributeValue {
                          S = driverName.LastName
                      } }
                },
                ExpressionAttributeNames = new Dictionary <string, string>
                {
                    { "#n", "Name" }
                },
                FilterExpression = "#n.FirstName = :firstName and #n.LastName = :lastName",
                Limit            = 1
            };

            using (var client = new AmazonDynamoDBClient(_region))
            {
                var response = client.ScanAsync(request).Result;
                return(response.Count > 0);
            }
        }
Exemplo n.º 8
0
        internal static void Cleanup()
        {
            Logging.LogDebug("Cleaning catchup");
            AmazonDynamoDBClient client    = new AmazonDynamoDBClient();
            DateTime             threshold = DateTime.UtcNow.AddMinutes(-30);

            Logging.LogDebug("TS:" + threshold.Ticks.ToString());
            ScanRequest request = new ScanRequest
            {
                TableName                 = "catchup",
                FilterExpression          = "ts < :ts",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":ts", new AttributeValue {
                          N = threshold.Ticks.ToString()
                      } }
                },
                ProjectionExpression = "room"
            };
            ScanResponse response = client.ScanAsync(request).Result;

            Logging.LogDebug("Pending Delete Count:" + response.Items.Count.ToString());

            Logging.LogDebug(Newtonsoft.Json.JsonConvert.SerializeObject(response.Items));

            Table catchupTable = Table.LoadTable(client, "catchup");

            foreach (Dictionary <string, AttributeValue> item in response.Items)
            {
                Delete(item["room"].S);
            }
        }
Exemplo n.º 9
0
        public static async void FindProductsForPriceLessThanZero(AmazonDynamoDBClient client)
        {
            Dictionary <string, AttributeValue> lastKeyEvaluated = null;

            do
            {
                var request = new ScanRequest
                {
                    TableName                 = "ProductCatalog",
                    Limit                     = 2,
                    ExclusiveStartKey         = lastKeyEvaluated,
                    ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                        { ":val", new AttributeValue {
                              N = "0"
                          } }
                    },
                    FilterExpression = "Price < :val",

                    ProjectionExpression = "Id, Title, Price"
                };

                var response = await client.ScanAsync(request);

                foreach (Dictionary <string, AttributeValue> item
                         in response.Items)
                {
                    Console.WriteLine("\nScanThreadTableUsePaging - printing.....");
                    PrintItem(item);
                }

                lastKeyEvaluated = response.LastEvaluatedKey;
            } while (lastKeyEvaluated != null && lastKeyEvaluated.Count != 0);
        }
Exemplo n.º 10
0
        private async Task <IEnumerable <AwsDotnetCsharp.Models.User> > getUsers()
        {
            /*          var bevanList = await GetBevanList();
             *        List<string> bevanUsers = new List<string>();
             *        List<SlackAPI.User> Users;
             *
             *        bevanList.ToList().Select(t => {
             *            bevanUsers.Add(t.ReceiverId);
             *            bevanUsers.Add(t.GiverId);
             *        }).Distinct();
             *
             *        var slackMsg = new SlackMessage(new DynamoRepository());
             *        Users = slackMsg.GetUsers(ids.Distinct().ToList());
             *        Console.WriteLine();
             */
            using (var client = new AmazonDynamoDBClient())
            {
                var response = await client.ScanAsync(new ScanRequest("user"));

                return(response?.Items?.Select(i => new User
                {
                    guid = i["guid"].S,
                    id = i["id"].S,
                    name = i["name"].S,
                    userimage = i["userimage"].S,
                    totalbevans = 0
                }).Distinct().ToList());
            }
        }
Exemplo n.º 11
0
        public static void SetName(string apiUrl, string connectionId, JObject data)
        {
            string name = data["displayName"].ToString();

            AmazonDynamoDBClient client  = new AmazonDynamoDBClient();
            ScanRequest          request = new ScanRequest
            {
                TableName                 = "connections",
                FilterExpression          = "connectionId = :connectionId",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":connectionId", new AttributeValue {
                          S = connectionId
                      } }
                },
                ProjectionExpression = "room, connectionId"
            };
            ScanResponse response = client.ScanAsync(request).Result;

            List <Task> tasks = new List <Task>();

            foreach (Dictionary <string, AttributeValue> item in response.Items)
            {
                tasks.Add(SetName(apiUrl, item["connectionId"].S, item["room"].S, name));
            }

            Task.WaitAll(tasks.ToArray());
        }
        /**
         * Admin country service methods.
         */
        #region Admin country service

        /**
         * Get countries.
         */
        public static async Task <List <Country> > GetCountries(AmazonDynamoDBClient dbClient)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);

            // Check that the system is not locked.
            await SystemHelper.CheckSystemNotLocked(dbClient);

            //
            List <string> attributes = new List <string>();

            attributes.Add(FIELD_COUNTRIES_CODE);
            attributes.Add(FIELD_COUNTRIES_NAME);
            attributes.Add(FIELD_COUNTRIES_CURRENCIES);
            attributes.Add(FIELD_COUNTRIES_AVAILABLE);
            ScanResponse response = await dbClient.ScanAsync(DATASET_COUNTRIES, attributes);

            Debug.AssertValid(response);
            //??++CHECK RESPONSE?
            LoggingHelper.LogMessage($"Get countries: {response.Count} items");
            List <Country> countries = new List <Country>();

            foreach (var item in response.Items)
            {
                Debug.AssertValid(item);
                countries.Add(new Country {
                    Code       = item[FIELD_COUNTRIES_CODE].S,
                    Name       = item[FIELD_COUNTRIES_NAME].S,
                    Currencies = item[FIELD_COUNTRIES_CURRENCIES].SS,
                    Available  = item[FIELD_COUNTRIES_AVAILABLE].BOOL
                });
            }
            return(countries);
        }
Exemplo n.º 13
0
        private async Task <SkillResponse> HandleUnknownUser(IntentRequest intentRequest, AmazonDynamoDBClient dynamoDbClient, string name)
        {
            var allUsers = await dynamoDbClient.ScanAsync(new ScanRequest
            {
                TableName            = _TableName,
                ProjectionExpression = "Username"
            });

            if (allUsers != null && allUsers.Count > 0)
            {
                var l = new Levenshtein();

                var bestMatchedName = allUsers.Items
                                      .Select(x => x["Username"].S)
                                      .OrderBy(x => l.Distance(x, name))
                                      .FirstOrDefault();

                if (bestMatchedName != null)
                {
                    intentRequest.Intent.Slots.TryAdd("name", new Slot {
                        Value = bestMatchedName
                    });
                    intentRequest.Intent.Slots["name"].Value = bestMatchedName;
                    return(ResponseBuilder.DialogConfirmIntent(new PlainTextOutputSpeech
                    {
                        Text = $"I did not find {name}, do you mean {bestMatchedName}"
                    }, intentRequest.Intent));
                }
            }

            return(null);
        }
Exemplo n.º 14
0
        private async Task <List <string> > GetMobIds()
        {
            Dictionary <string, AttributeValue> startKeys = null;

            const string tableName = "mobs1";
            const string keyName   = "id";
            const int    limit     = 10;
            var          request   = new ScanRequest
            {
                TableName = tableName,
                Limit     = limit
            };
            var keyList = new List <string>();

            do
            {
                request.ExclusiveStartKey = startKeys;
                var response = await _client.ScanAsync(request);

                response.Items.ForEach(
                    item => keyList.AddRange(item.Where(x => x.Key == keyName)
                                             .Select(y => y.Value.S)
                                             .ToList()));

                startKeys = response.LastEvaluatedKey;
            } while (startKeys != null && startKeys.Count != 0);

            return(keyList);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Scan a DynamoDB table by querying the entry fields.
        /// </summary>
        /// <typeparam name="TResult">The result type</typeparam>
        /// <param name="tableName">The name of the table to search for the entries</param>
        /// <param name="attributes">The attributes used on the expression</param>
        /// <param name="expression">The filter expression</param>
        /// <param name="resolver">Function that will be called to translate the returned fields into a concrete type. This Function is only called if the result is != null and will be called for each entry that match the query and added to the results list</param>
        /// <returns>The collection containing a list of objects translated by the resolver function</returns>
        public async Task <List <TResult> > ScanAsync <TResult>(string tableName, Dictionary <string, AttributeValue> attributes, string expression, Func <Dictionary <string, AttributeValue>, TResult> resolver) where TResult : class
        {
            try
            {
                var request = new ScanRequest
                {
                    TableName                 = tableName,
                    ConsistentRead            = true,
                    FilterExpression          = expression,
                    ExpressionAttributeValues = attributes,
                    Select = Select.ALL_ATTRIBUTES
                };

                var response = await ddbClient.ScanAsync(request);

                var resultList = new List <TResult>();
                foreach (var item in response.Items)
                {
                    resultList.Add(resolver(item));
                }
                return(resultList);
            }
            catch (Exception exc)
            {
                var errorMsg = $"Failed to read table {tableName}: {exc.Message}";
                Logger.Warn(ErrorCode.StorageProviderBase, errorMsg, exc);
                throw new OrleansException(errorMsg, exc);
            }
        }
        public async Task <bool> ContainsItemMatchingRoom(Classtime classtime)
        {
            ScanRequest scanRequest = new ScanRequest()
            {
                TableName = tableName,
                Limit     = 5,
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>()
                {
                    { ":v_" + ClasstimeAsString.building, new AttributeValue()
                      {
                          S = classtime.building
                      } },
                    { ":v_" + ClasstimeAsString.roomNumber, new AttributeValue()
                      {
                          S = classtime.roomNumber
                      } }
                },
                FilterExpression = ClasstimeAsString.building + " = " + ":v_" + ClasstimeAsString.building
                                   + " and " + ClasstimeAsString.roomNumber + " = " + ":v_" + ClasstimeAsString.roomNumber
            };

            ScanResponse scanResponse = await dynamodbClient.ScanAsync(scanRequest);

            return(scanResponse.Count > 0);
        }
Exemplo n.º 17
0
        public List <Employee> List(int page_size, int page)
        {
            ScanResponse returnIWant = null;
            string       KeyToStart  = string.Empty;
            Dictionary <string, AttributeValue> lastKey = null;

            for (int p = 1; p <= page; p++)
            {
                var query = new ScanRequest()
                {
                    TableName         = "employee",
                    Limit             = page_size,
                    ExclusiveStartKey = lastKey != null? lastKey : null,
                };

                returnIWant = dynamodbClient.ScanAsync(query).Result;
                lastKey     = returnIWant.LastEvaluatedKey;
            }

            var employees = returnIWant?.Items.ConvertAll(new Converter <Dictionary <string, AttributeValue>, Employee>(itemRetorno =>
            {
                return(new Employee()
                {
                    name = itemRetorno["name"].S,
                    department = itemRetorno["department"].S,
                    email = itemRetorno["email"].S,
                    id = long.Parse(itemRetorno["id"].S)
                });
            }));

            return(employees);
        }
        public static async void ScanSegment(AmazonDynamoDBClient client, int totalSegments, int segment)
        {
            Console.WriteLine("*** Starting to Scan Segment {0} of {1} out of {2} total segments ***", segment, _tableName, totalSegments);
            Dictionary <string, AttributeValue> lastEvaluatedKey = null;
            int totalScannedItemCount = 0;
            int totalScanRequestCount = 0;

            do
            {
                var request = new ScanRequest
                {
                    TableName         = _tableName,
                    Limit             = _scanItemLimit,
                    ExclusiveStartKey = lastEvaluatedKey,
                    Segment           = segment,
                    TotalSegments     = totalSegments
                };

                var response = await client.ScanAsync(request);

                lastEvaluatedKey = response.LastEvaluatedKey;
                totalScanRequestCount++;
                totalScannedItemCount += response.ScannedCount;
                foreach (var item in response.Items)
                {
                    Console.WriteLine("Segment: {0}, Scanned Item with Title: {1}", segment, item["Title"].S);
                }
            } while (lastEvaluatedKey.Count != 0);

            Console.WriteLine("*** Completed Scan Segment {0} of {1}. TotalScanRequestCount: {2}, TotalScannedItemCount: {3} ***", segment, _tableName, totalScanRequestCount, totalScannedItemCount);
        }
Exemplo n.º 19
0
        public static void WipeMeasurements()
        {
            AmazonDynamoDBClient client      = new AmazonDynamoDBClient();
            DynamoDBContext      context     = new DynamoDBContext(client);
            ScanRequest          scanRequest = new ScanRequest("Measurements");

            var scan = client.ScanAsync(scanRequest);

            foreach (Dictionary <string, AttributeValue> item in scan.Result.Items)
            {
                string id    = "";
                string range = "";
                foreach (var keyValuePair in item)
                {
                    if (keyValuePair.Key == "Id")
                    {
                        id = keyValuePair.Value.S;
                    }
                    else if (keyValuePair.Key == "DeviceSerialNumber")
                    {
                        range = keyValuePair.Value.S;
                    }
                }
                context.DeleteAsync <DDBMeasurement>(id, range);
            }
        }
Exemplo n.º 20
0
        private async Task SaveChannel(string id)
        {
            Console.WriteLine("Save Channel started for " + id);
            var client   = new AmazonDynamoDBClient();
            var response = await client.ScanAsync(new ScanRequest("channel"));

            var channelFromDb = response.Items?.Find(i => (i["id"].S == id));

            if (channelFromDb == null)
            {
                //get channel name from slack
                var slackMsg = new SlackMessage(new DynamoRepository());
                List <AwsDotnetCsharp.Models.Channel> channels = slackMsg.GetChannels(new List <string>()
                {
                    id
                }).ToList();

                //add channel to channel table
                if (channels?.Count > 0)
                {
                    Console.WriteLine("Adding new channel to db : Name " + channels[0]?.name);
                    var newChannel = new Document
                    {
                        ["guid"] = Guid.NewGuid().ToString(),
                        ["id"]   = id,
                        ["name"] = channels[0]?.name
                    };
                    var table = Table.LoadTable(client, "channel");
                    await table.PutItemAsync(newChannel);

                    Console.WriteLine("Channel saved");
                }
            }
        }
        /// <summary>
        /// Returns all documents from DynamoDB table
        /// </summary>
        /// <typeparam name="T">object</typeparam>
        /// <returns></returns>
        public virtual async Task <ICollection <T> > GetAllAsync <T>()
        {
            Logger.Log($"Scanning DynamoDB {_tableName} for all TimeSeries");

            ICollection <T> results = new List <T>();

            try
            {
                var docs = await _dynamoDbClient.ScanAsync(new ScanRequest(_tableName));

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

                foreach (var t in docs.Items)
                {
                    // Convert DynamoDB document to C# object
                    var doc = Document.FromAttributeMap(t);
                    var obj = _dynamoDbContext.FromDocument <T>(doc);

                    results.Add(obj);
                }
            }
            catch (Exception e)
            {
                Logger.Log(e.Message);
            }

            return(results);
        }
Exemplo n.º 22
0
        public async Task <ScanResponse> ListItems()
        {
            ScanRequest scanRequest = new ScanRequest {
                TableName = tableName
            };

            return(await dbClient.ScanAsync(scanRequest));
        }
Exemplo n.º 23
0
        private async Task <string> ScanReadingListAsync()
        {
            using var client = new AmazonDynamoDBClient(Amazon.RegionEndpoint.USWest2);

            var response = await client.ScanAsync(new ScanRequest("readingList"));

            return(JsonConvert.SerializeObject(response.Items));
        }
Exemplo n.º 24
0
        public async Task <List <Team> > GetAllAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            ScanRequest  scanRequest  = DynamoDbParser.GetScanRequest();
            ScanResponse scanResponse = await client.ScanAsync(scanRequest, cancellationToken);

            return(DynamoDbParser.GetListTeam(scanResponse));
        }
Exemplo n.º 25
0
        public async Task <IActionResult> GetItems(string TableName)
        {
            var attributesToGet = new List <string>();

            attributesToGet.Add("Id");
            attributesToGet.Add("Data");
            var scanResponse = await DynamoDbClient.ScanAsync(TableName, attributesToGet);

            return(View(scanResponse));
        }
Exemplo n.º 26
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <IEnumerable <PostRecord> > FunctionHandler(PostRequestEvent input, ILambdaContext context)
        {
            var recordId = input.RecordId;

            var tableName = Environment.GetEnvironmentVariable("DB_TABLE_NAME");

            using (var dynamoDb = new AmazonDynamoDBClient())
            {
                var fieldsToRetrieve = new List <string> {
                    "id", "text", "voice", "status", "url"
                };

                if (recordId == "*")
                {
                    var results = await dynamoDb.ScanAsync(tableName, fieldsToRetrieve);

                    return(results.Items.Select(d =>
                    {
                        var record = new PostRecord
                        {
                            Id = d["id"].S,
                            Text = d["text"].S,
                            Voice = d["voice"].S,
                            Status = d["status"].S,
                            Url = d["url"].S
                        };

                        return record;
                    }).ToList());
                }
                else
                {
                    var result = await dynamoDb.GetItemAsync(tableName,
                                                             new Dictionary <string, AttributeValue>
                    {
                        { "id", new AttributeValue {
                              S = recordId
                          } }
                    }
                                                             );

                    var record = new PostRecord
                    {
                        Id     = result.Item["id"].S,
                        Text   = result.Item["text"].S,
                        Voice  = result.Item["voice"].S,
                        Status = result.Item["status"].S,
                        Url    = result.Item["url"].S
                    };

                    return(new[] { record });
                }
            }
        }
Exemplo n.º 27
0
        private async Task <string> somethingAsync()
        {
            using (var client = new AmazonDynamoDBClient())
            {
                var response = await client.ScanAsync(new ScanRequest("hey-bevan-table-new-dev"));

                var heyBevanJson = JsonConvert.SerializeObject(response.Items);

                return(heyBevanJson);
            }
        }
        public async Task <IEnumerable <Event> > GetAllEventsAsync()
        {
            var scanRequest = new ScanRequest
            {
                TableName = _tableName
            };

            var response = await _dynamoDbClient.ScanAsync(scanRequest);

            return(GetEventsFromDynamoDbResponse(response.Items));
        }
Exemplo n.º 29
0
        public async void GetAllFromTable(string tabela)
        {
            using (var client = new AmazonDynamoDBClient(awsCredentials, awsRegion))
            {
                var queryResponse = await client.ScanAsync(new ScanRequest()
                {
                    TableName = tabela
                });

                queryResponse.Items.ForEach((i) => { Console.WriteLine(i["Title"].S); });
            }
        }
Exemplo n.º 30
0
        public async Task TestDDBScanUnsuccessful()
#endif
        {
            var processor = new Mock <BaseProcessor <Activity> >();

            var parent = new Activity("parent").Start();

            using (Sdk.CreateTracerProviderBuilder()
                   .SetSampler(new AlwaysOnSampler())
                   .AddXRayTraceId()
                   .AddAWSInstrumentation()
                   .AddProcessor(processor.Object)
                   .Build())
            {
                var    ddb       = new AmazonDynamoDBClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1);
                string requestId = @"fakerequ-esti-dfak-ereq-uestidfakere";
                AmazonServiceException amazonServiceException = new AmazonServiceException();
                amazonServiceException.StatusCode = System.Net.HttpStatusCode.NotFound;
                amazonServiceException.RequestId  = requestId;
                CustomResponses.SetResponse(ddb, (request) => { throw amazonServiceException; });
                var scan_request = new ScanRequest();

                scan_request.TableName       = "SampleProduct";
                scan_request.AttributesToGet = new List <string>()
                {
                    "Id", "Name"
                };

                try
                {
#if NET452
                    ddb.Scan(scan_request);
#else
                    await ddb.ScanAsync(scan_request);
#endif
                }
                catch (AmazonServiceException)
                {
                    var count = processor.Invocations.Count;
                    Assert.Equal(3, count);

                    Activity awssdk_activity = (Activity)processor.Invocations[2].Arguments[0];

                    this.ValidateAWSActivity(awssdk_activity, parent);
                    this.ValidateDynamoActivityTags(awssdk_activity);

                    Assert.Equal(requestId, Utils.GetTagValue(awssdk_activity, "aws.requestId"));
                    Assert.Equal(Status.Error.WithDescription("Exception of type 'Amazon.Runtime.AmazonServiceException' was thrown."), awssdk_activity.GetStatus());
                    Assert.Equal("exception", awssdk_activity.Events.First().Name);
                }
            }
        }