Пример #1
0
        /// Accessor for a specific entry in the database
        /// @param primaryKey the key used to lookup the entry in the database
        protected async Task <DatabaseItem> GetEntryByKey(string primaryKey)
        {
            var getRequest = new GetItemRequest
            {
                TableName = tableName,
                Key       = new Dictionary <string, AttributeValue>
                {
                    { primaryPartitionKey, new AttributeValue {
                          S = primaryKey
                      } }
                }
            };

            DatabaseItem item = new DatabaseItem();

            try
            {
                var response = await client.GetItemAsync(getRequest);

                if (response.IsItemSet)
                {
                    item = response.Item;
                }
            }
            catch (Exception e)
            {
                log.WARN("DatabaseClient", "GetEntryByKey(string)", "EXCEPTION: " + e.Message);
            }

            return(item);
        }
Пример #2
0
        private async Task <SkillResponse> BuildMorningReportResponseAsync()
        {
            var response = await _dynamoClient.GetItemAsync(_dynamoTable, new Dictionary <string, AttributeValue> {
                ["Key"] = new AttributeValue {
                    S = MorningReportInfo.ROW_KEY
                }
            });

            AttributeValue value = null;

            if ((response.HttpStatusCode != HttpStatusCode.OK) || !response.Item.TryGetValue("Value", out value))
            {
                return(BuildSpeechResponse(PROMPT_ERROR_MORNING_REPORT));
            }
            var morningReport = MorningReportInfo.FromJson(value.S);

            return(new SkillResponse {
                Version = "1.0",
                Response = new ResponseBody {
                    OutputSpeech = new SsmlOutputSpeech {
                        Ssml = morningReport.ConvertContentsToSsml(_preHeadingBreak, _postHeadingBreak, _bulletBreak)
                    },
                    ShouldEndSession = true
                }
            });
        }
Пример #3
0
        public async Task <WorkflowInstance> GetWorkflowInstance(string Id)
        {
            var req = new GetItemRequest()
            {
                TableName = $"{_tablePrefix}-{WORKFLOW_TABLE}",
                Key       = new Dictionary <string, AttributeValue>
                {
                    { "id", new AttributeValue(Id) }
                }
            };
            var response = await _client.GetItemAsync(req);

            return(response.Item.ToWorkflowInstance());
        }
        public async Task <APIGatewayProxyResponse> GetNotepad(APIGatewayProxyRequest req, ILambdaContext context)
        {
            var request = new GetItemRequest
            {
                TableName = tableName,
                Key       = new Dictionary <string, AttributeValue>()
                {
                    { "Id", new AttributeValue {
                          N = $"{req.QueryStringParameters["Id"]}"
                      } }
                }
            };

            var response = await client.GetItemAsync(request);

            return(new APIGatewayProxyResponse {
                StatusCode = (int)HttpStatusCode.OK,
                Body = JsonSerializer.Serialize(ParseToNotepadObject(response.Item)),
                Headers = new Dictionary <string, string>
                {
                    { "Content-Type", "application/json" },
                    { "Control-Access-Allow-Origin", "*" }
                }
            });
        }
Пример #5
0
        public bool TryGetSong(int songId, out Song song)
        {
            try
            {
                var key = new Dictionary <string, AttributeValue> {
                    { "SongId", new AttributeValue {
                          N = songId.ToString()
                      } }
                };
                var response = _db.GetItemAsync("Songs", key).Result;
                if (response.IsItemSet)
                {
                    var songRef  = Guid.Parse(response.Item["SongRef"].S);
                    var artist   = response.Item["Artist"].S;
                    var album    = response.Item["Album"].S;
                    var title    = response.Item["Title"].S;
                    var track    = int.Parse(response.Item["Track"].N);
                    var filePath = response.Item["FilePath"].S;
                    song = new Song(songId, songRef, artist, album, title, track, filePath);
                    return(true);
                }
            }
            catch (Exception e)
            {
                throw new Exception($"Failed to fetch song (SongId={songId}) from DynamoDb.", e);
            }

            song = null;
            return(false);
        }
Пример #6
0
        public static async Task GetItemAsync()
        {
            #region service_client_get
            using (var ddbClient = new AmazonDynamoDBClient())
            {
                var request = new GetItemRequest
                {
                    TableName = "TODOList",
                    Key       = new Dictionary <string, AttributeValue>
                    {
                        { "User", new AttributeValue {
                              S = "serviceclient-testuser"
                          } },
                        { "ListId", new AttributeValue {
                              S = "generated-list-id"
                          } }
                    }
                };

                var response = await ddbClient.GetItemAsync(request);

                if (response.Item.Count > 0)
                {
                    Dictionary <string, AttributeValue> item = response.Item;
                    Console.WriteLine($"List Name {response.Item["Name"].S}");
                    PrintItem(item);
                }
                else
                {
                    Console.WriteLine("TODO List item not found");
                }
            }
            #endregion
        }
Пример #7
0
        public async Task <Workflow> GetCurrentStateAsync(string orchestrationId)
        {
            var getItemRequest = new GetItemRequest();

            getItemRequest.TableName = Constants.LAMBDA_BIZ_DYNAMODB_TABLE;
            getItemRequest.Key       = new Dictionary <string, AttributeValue>();
            getItemRequest.Key.Add(Constants.LAMBDA_BIZ_ORCHESTRATION_ID, new AttributeValue
            {
                S = orchestrationId
            });

            var getItemResponse = await _amazonDynamoDbClient.GetItemAsync(getItemRequest);

            var attributes = getItemResponse.Item[Constants.LAMBDA_BIZ_WF_ATTRIBUTES];
            var workflow   = JsonConvert.DeserializeObject <Workflow>(attributes.S);

            workflow.Activities = new List <Activity>();

            foreach (var attribute in getItemResponse.Item)
            {
                if (attribute.Key != Constants.LAMBDA_BIZ_WF_ATTRIBUTES &&
                    attribute.Key != Constants.LAMBDA_BIZ_ORCHESTRATION_ID)
                {
                    (workflow.Activities as IList <Activity>).Add(JsonConvert.DeserializeObject <Activity>(attribute.Value.S));
                }
            }

            return(workflow);
        }
Пример #8
0
        private string GetContentFromDynamoDb(string key)
        {
            string content = string.Empty;

            try
            {
                AmazonDynamoDBConfig clientConfig = new AmazonDynamoDBConfig();
                clientConfig.RegionEndpoint = RegionEndpoint.USEast1;

                AmazonDynamoDBClient client = new AmazonDynamoDBClient(clientConfig);

                GetItemRequest request = new GetItemRequest();
                request.TableName = TABLE_NAME;
                request.Key       = new Dictionary <string, AttributeValue>();
                request.Key.Add("ContentKey", new AttributeValue()
                {
                    S = key
                });

                var response = client.GetItemAsync(request);

                if (response.Result.HttpStatusCode == HttpStatusCode.OK)
                {
                    var item = response.Result.Item;
                    content = item["Content"].S;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(content);
        }
Пример #9
0
        public Contract Get(string contractId)
        {
            SetupDatabase();

            var request = new GetItemRequest()
            {
                TableName = ContractTableName,
                Key       = new Dictionary <string, AttributeValue>()
                {
                    { "ContractId", new AttributeValue()
                      {
                          S = contractId
                      } }
                }
            };

            var result = DbClient.GetItemAsync(request);

            result.Wait();

            if (result.IsCompletedSuccessfully)
            {
                var contract      = GetContract(result.Result.Item);
                var assetProvider = new AssetProvider(DbClient);
                contract.Assets = assetProvider.GetAssets(contract.ContractId);
                return(contract);
            }

            throw new ApplicationException("Error reading Contract information", result.Exception);
        }
Пример #10
0
        public async Task <APIGatewayProxyResponse> RunAsync(APIGatewayProxyRequest request)
        {
            using (var client = new AmazonDynamoDBClient(Amazon.RegionEndpoint.USEast1))
            {
                var requestId           = request.PathParameters["requestId"];
                var attributeDictionary = new Dictionary <string, AttributeValue> {
                    { "RequestId", new AttributeValue(requestId) }
                };
                var getItem  = new GetItemRequest("ChangeRequest", attributeDictionary);
                var response = await client.GetItemAsync(getItem);

                var headers = new Dictionary <string, string>
                {
                    { "Access-Control-Allow-Origin", "*" }
                };
                if (response == null || response.Item.Count == 0)
                {
                    return(new APIGatewayProxyResponse {
                        StatusCode = (int)HttpStatusCode.NotFound, Headers = headers
                    });
                }
                var item   = DeserializeChangeRequest(response);
                var result = JsonConvert.SerializeObject(item, new JsonSerializerSettings {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                });
                return(new APIGatewayProxyResponse {
                    StatusCode = (int)HttpStatusCode.OK, Headers = headers, Body = result
                });
            }
        }
Пример #11
0
        /// <summary>
        /// Read an entry from a DynamoDB table
        /// </summary>
        /// <typeparam name="TResult">The result type</typeparam>
        /// <param name="tableName">The name of the table to search for the entry</param>
        /// <param name="keys">The table entry keys to search for</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</param>
        /// <returns>The object translated by the resolver function</returns>
        public async Task <TResult> ReadSingleEntryAsync <TResult>(string tableName, Dictionary <string, AttributeValue> keys, Func <Dictionary <string, AttributeValue>, TResult> resolver) where TResult : class
        {
            try
            {
                var request = new GetItemRequest
                {
                    TableName      = tableName,
                    Key            = keys,
                    ConsistentRead = true
                };

                var response = await ddbClient.GetItemAsync(request);

                if (response.IsItemSet)
                {
                    return(resolver(response.Item));
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception)
            {
                if (Logger.IsVerbose)
                {
                    Logger.Verbose("Unable to find table entry for Keys = {0}", Utils.DictionaryToString(keys));
                }
                throw;
            }
        }
Пример #12
0
        private string GetFact(int factId)
        {
            var request = new GetItemRequest {
                TableName = _tableName,
                Key       = new Dictionary <string, AttributeValue>()
                {
                    {
                        "Id", new AttributeValue()
                        {
                            N = factId.ToString()
                        }
                    }
                }
            };
            var task = _dynamoClient.GetItemAsync(request);

            task.Wait();
            AttributeValue fact;

            if (task.Result.Item.TryGetValue("Fact", out fact))
            {
                LambdaLogger.Log($"INFO: Fact returned from database was #{factId}: {fact.S}");
                return(fact.S);
            }
            else
            {
                // GetFact();
                return("Sorry, could not retrieve a fact");
            }
        }
Пример #13
0
        public async Task <GetItemResponse> GetKey(string order)
        {
            var orderModel = JsonConvert.DeserializeObject <OrderModel>(order);
            var store      = new DynamoDataStore(_client);

            //// Construct the key //
            var key = orderModel.OrderId + "_" + orderModel.Email;

            try
            {
                var request = new GetItemRequest
                {
                    TableName = OrderTableName,
                    Key       = new Dictionary <string, AttributeValue>()
                    {
                        { OrderIdKey, new AttributeValue {
                              S = key
                          } }
                    },
                };

                return(await _client.GetItemAsync(request));
            }
            catch (Exception ex)
            {
                throw;
            }

            return(null);
        }
Пример #14
0
        public static async Task ServiceClientExampleAsync()
        {
            try
            {
                var client = new AmazonDynamoDBClient(RegionEndpoint.USWest2);

                var request = new GetItemRequest
                {
                    TableName = "RetailDatabase",
                    Key       = new Dictionary <string, AttributeValue>
                    {
                        { "pk", new AttributeValue {
                              S = "*****@*****.**"
                          } },
                        { "sk", new AttributeValue {
                              S = "metadata"
                          } }
                    }
                };

                var response = await client.GetItemAsync(request);

                Console.WriteLine($"Item retrieved with {response.Item.Count} attributes.");
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
            }
        }
Пример #15
0
 /// <summary>
 /// Return the table contents
 /// </summary>
 /// <param name="tableName">Table Name</param>
 /// <param name="isDocumentModelType"> true for Document Model and false for Local Mode</param>
 /// <returns>Array of Values</returns>
 public Document[] FuncReadTable(string tableName, bool isDocumentModelType)
 {
     if (isDocumentModelType)
     {
         try
         {
             Table      table       = Table.LoadTable(client, tableName);
             ScanFilter scanFilter  = new ScanFilter();
             Search     getAllItems = table.Scan(scanFilter);
             Document[] allItems    = getAllItems.GetRemainingAsync().Result.ToArray();
             return(allItems);
         }
         catch (Exception)
         {
             return(null);
         }
     }
     else
     {
         Dictionary <string, AttributeValue> dictObj = new Dictionary <string, AttributeValue>
         {
             { "1", null }
         };
         try
         {
             System.Threading.Tasks.Task <GetItemResponse> request = client.GetItemAsync(tableName, dictObj);
         }
         catch (Exception)
         {
         }
         return(null);
     }
 }
Пример #16
0
        public static async void RetrieveItem(AmazonDynamoDBClient client, string partitionKey, string sortKey)
        {
            var request = new GetItemRequest
            {
                TableName = _tableName,
                Key       = new Dictionary <string, AttributeValue>()
                {
                    { "Id", new AttributeValue {
                          S = partitionKey
                      } },
                    { "ReplyDateTime", new AttributeValue {
                          S = sortKey
                      } }
                },
                ConsistentRead = true
            };

            var response = await client.GetItemAsync(request);

            // Check the response.
            var attributeList = response.Item; // attribute list in the response.

            Console.WriteLine("\nPrinting item after retrieving it ............");

            PrintItem(attributeList);
        }
Пример #17
0
        public async Task <string> FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context)
        {
            string coinSymbol   = "";
            string testVariable = null;

            Table table = Table.LoadTable(client, tableName);

            Dictionary <string, string> queryStrings = (Dictionary <string, string>)input.QueryStringParameters;

            if (queryStrings != null)
            {
                queryStrings.TryGetValue("coinName", out coinSymbol);
            }
            else
            {
                if (testVariable != null)
                {
                    coinSymbol = testVariable;
                }
                coinSymbol = "bitcoin";
            }

            GetItemResponse response = await client.GetItemAsync(tableName, new Dictionary <string, AttributeValue>
            {
                { "id", new AttributeValue {
                      S = coinSymbol
                  } }
            });

            Document doc = Document.FromAttributeMap(response.Item);

            Coin coin = JsonConvert.DeserializeObject <Coin>(doc.ToJson());

            return(JsonConvert.SerializeObject(coin));
        }
Пример #18
0
        private async void GetItem()
        {
            AmazonDynamoDBClient client = new AmazonDynamoDBClient(awsCredentials, awsRegion);

            Dictionary <string, AttributeValue> key = new Dictionary <string, AttributeValue>
            {
                { "Id", new AttributeValue {
                      N = "10"
                  } }
            };

            GetItemRequest request = new GetItemRequest
            {
                TableName = "Books",
                Key       = key,
            };

            var result = await client.GetItemAsync(request);

            Console.WriteLine("Item:");
            Dictionary <string, AttributeValue> item = result.Item;

            foreach (var keyValuePair in item)
            {
                Console.WriteLine("Author := {0}", item["Author"]);
                Console.WriteLine("Title := {0}", item["Title"]);
                Console.WriteLine("Price:= {0}", item["Price"]);
                Console.WriteLine("PageCount := {0}", item["PageCount"]);
            }
        }
Пример #19
0
 public static T ReadData <T>(string id)
 {
     using (var client = new AmazonDynamoDBClient(accessKey, privateKey, RegionEndpoint.USEast1))
     {
         var name       = typeof(T).Name;
         var primaryKey = name + "ID";
         var request    = new GetItemRequest
         {
             TableName = name,
             Key       = new Dictionary <string, AttributeValue>()
             {
                 { primaryKey, new AttributeValue {
                       S = id
                   } }
             },
         };
         var asyncResult = client.GetItemAsync(request);
         while (!asyncResult.IsCompleted)
         {
             Thread.Sleep(200);
         }
         if (asyncResult.IsFaulted)
         {
             throw asyncResult.Exception;
         }
         var response = asyncResult.Result;
         var output   = (T)Activator.CreateInstance(typeof(T));
         foreach (var property in typeof(T).GetProperties())
         {
             if (response.Item.ContainsKey(property.Name))
             {
                 var value = response.Item[property.Name];
                 if (property.PropertyType == typeof(string) && value.S != null)
                 {
                     property.SetValue(output, value.S);
                 }
                 else if (property.PropertyType == typeof(DateTime) && value.S != null)
                 {
                     property.SetValue(output, value.S);
                 }
                 else if (property.PropertyType == typeof(Guid) && value.S != null)
                 {
                     property.SetValue(output, value.S);
                 }
                 else if (value.IsMSet && value.N != default(string))
                 {
                     property.SetValue(output, value.N);
                 }
                 else if (value.IsBOOLSet)
                 {
                     property.SetValue(output, value.B);
                 }
             }
         }
         return(output);
     }
 }
Пример #20
0
        public async Task <string> GetItemAsync(string pk, string sk)
        {
            using var client = new AmazonDynamoDBClient();
            var key             = GetKey(pk, sk);
            var getItemRequest  = new GetItemRequest(TABLE_NAME, key);
            var getItemResponse = await client.GetItemAsync(getItemRequest);

            return(getItemResponse.Item["data"].S);
        }
Пример #21
0
        public async Task <Team> GetAsync(string id, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            GetItemRequest  getItem      = DynamoDbParser.GetGetItemRequest(id);
            GetItemResponse responseItem = await client.GetItemAsync(getItem, cancellationToken);

            return(DynamoDbParser.GetTeam(responseItem));
        }
Пример #22
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 string FunctionHandler(Models.Topic input, ILambdaContext context)
        {
            if (input == null || string.IsNullOrWhiteSpace(input.TopicId))
            {
                throw new ArgumentNullException("Input required");
            }

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

            key.Add("id", new AttributeValue()
            {
                S = input.TopicId
            });

            var dynamoDbClient = new AmazonDynamoDBClient(RegionEndpoint.APSoutheast1);
            var item           = dynamoDbClient.GetItemAsync("Topics", key).Result.Item;

            var topicName = item.GetValueOrDefault("name").S;
            var topicArn  = item.GetValueOrDefault("arn").S;
            var messages  = item.GetValueOrDefault("messages")?.SS;

            var message = string.Empty;

            if (messages != null && messages.Count > 0)
            {
                if (messages.Count > 1)
                {
                    var random      = new Random();
                    var randomIndex = random.Next(0, messages.Count - 1);
                    message = messages[randomIndex];
                }
                else
                {
                    message = messages[0];
                }
            }
            else
            {
                return("failed");
            }

            var snsClient      = new AmazonSimpleNotificationServiceClient(RegionEndpoint.APSoutheast1);
            var publishRequest = new PublishRequest();

            publishRequest.Message  = message;
            publishRequest.Subject  = $"AWSUGID Test Email Notification [Topic: {topicName}]";
            publishRequest.TopicArn = topicArn;
            var publishResponse = snsClient.PublishAsync(publishRequest).Result;

            if (publishResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException(publishResponse.HttpStatusCode.ToString());
            }

            return("success");
        }
Пример #23
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 });
                }
            }
        }
Пример #24
0
        /// <summary>
        /// Get an item from the 'users' table.
        /// </summary>
        /// <param name="id">The id of the table (User.Id)</param>
        /// <param name="projection">The projection to be used, e.g., "AccessorId,UserInfo.LastName"</param>
        /// <returns></returns>
        public Task <GetItemResponse> GetItem(Guid id, string projection = null)
        {
            var request = new GetItemRequest
            {
                TableName            = Meta.TableName.User,
                Key                  = GetKey(id),
                ProjectionExpression = projection,
            };

            return(client.GetItemAsync(request));
        }
Пример #25
0
        public async Task <T> GetItemAsync <T>(string pk, string sk)
        {
            using var client = new AmazonDynamoDBClient();
            var key             = GetKey(pk, sk);
            var getItemRequest  = new GetItemRequest(TABLE_NAME, key);
            var getItemResponse = await client.GetItemAsync(getItemRequest);

            var item = JsonSerializer.Deserialize <T>(getItemResponse.Item["data"].S);

            return(item);
        }
        /**
         * Add a new country or update an existing one.
         */
        public static async Task <bool> UpdateCountry(AmazonDynamoDBClient dbClient, string loggedInUserId, Country country)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(loggedInUserId);
            Debug.Assert(Helper.IsValidCountryCode(country.Code));
            Debug.Assert(country.Currencies.Count > 0);

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

            // Get the existing country
            bool created = false;
            Dictionary <string, AttributeValue> key = new Dictionary <string, AttributeValue>();

            key.Add(FIELD_COUNTRIES_CODE, new AttributeValue(country.Code));
            GetItemResponse getResponse = await dbClient.GetItemAsync(DATASET_COUNTRIES, key);

            Debug.AssertValid(getResponse);
            Debug.AssertValidOrNull(getResponse.Item);
            if (getResponse.Item != null)
            {
                // The country exists so update it.
                Dictionary <string, AttributeValueUpdate> attributeUpdates = new Dictionary <string, AttributeValueUpdate>();
                attributeUpdates.Add(FIELD_COUNTRIES_NAME, new AttributeValueUpdate(new AttributeValue(country.Name), AttributeAction.PUT));
                attributeUpdates.Add(FIELD_COUNTRIES_CURRENCIES, new AttributeValueUpdate(new AttributeValue(country.Currencies), AttributeAction.PUT));
                attributeUpdates.Add(FIELD_COUNTRIES_AVAILABLE, new AttributeValueUpdate(new AttributeValue {
                    BOOL = country.Available
                }, AttributeAction.PUT));
                UpdateItemResponse updateResponse = await dbClient.UpdateItemAsync(DATASET_COUNTRIES, key, attributeUpdates);

                Debug.AssertValid(updateResponse);
                //??++CHECK RESPONSE?
            }
            else
            {
                // The country does not exist so create it.
                Dictionary <string, AttributeValue> item = new Dictionary <string, AttributeValue>();
                item.Add(FIELD_COUNTRIES_CODE, new AttributeValue(country.Code));
                item.Add(FIELD_COUNTRIES_NAME, new AttributeValue(country.Name));
                item.Add(FIELD_COUNTRIES_CURRENCIES, new AttributeValue(country.Currencies));
                item.Add(FIELD_COUNTRIES_AVAILABLE, new AttributeValue {
                    BOOL = country.Available
                });
                PutItemResponse putResponse = await dbClient.PutItemAsync(DATASET_COUNTRIES, item);

                Debug.AssertValid(putResponse);
                //??++CHECK RESPONSE?
                created = true;
            }
            AddCountryAudit(dbClient, loggedInUserId, CountryAuditRecord.AuditChangeType.create, country);
            return(created);
        }
Пример #27
0
        public async static Task <bool> ItemExists(string key)
        {
            var response = await dbClient.GetItemAsync(
                tableName : clientTableName,
                key : new Dictionary <string, AttributeValue>
            {
                { "ClientID", new AttributeValue {
                      S = key
                  } }
            });

            Client client = new Client();

            try
            {
                client.ClientID = response.Item["ClientID"].S.ToString();
            }
            catch { return(false); }

            return(true);
        }
Пример #28
0
        private string GetContentFromFile(string key)
        {
            string filename = string.Empty;
            string content  = string.Empty;

            try
            {
                AmazonDynamoDBConfig clientConfig = new AmazonDynamoDBConfig();
                clientConfig.RegionEndpoint = RegionEndpoint.USEast1;

                AmazonDynamoDBClient client = new AmazonDynamoDBClient(clientConfig);

                GetItemRequest getItemRqst = new GetItemRequest();
                getItemRqst.TableName = TABLE_NAME;
                getItemRqst.Key       = new Dictionary <string, AttributeValue>();
                getItemRqst.Key.Add("ContentKey", new AttributeValue()
                {
                    S = key
                });

                var response = client.GetItemAsync(getItemRqst).Result;

                if (response.HttpStatusCode == HttpStatusCode.OK)
                {
                    filename = response.Item["Filename"].S;
                }

                if (!filename.Equals(string.Empty))
                {
                    AmazonS3Client s3Client = new AmazonS3Client(RegionEndpoint.USEast1);

                    GetObjectRequest getRequest = new GetObjectRequest()
                    {
                        BucketName = S3_BUCKET_NAME,
                        Key        = filename
                    };

                    using (GetObjectResponse getResponse = s3Client.GetObjectAsync(getRequest).Result)
                        using (Stream responseStream = getResponse.ResponseStream)
                            using (StreamReader reader = new StreamReader(responseStream))
                            {
                                content = reader.ReadToEnd();
                            }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(content);
        }
Пример #29
0
        private GetItemResponse GetItem(string key)
        {
            var dynamoDbKey =
                new Dictionary <string, AttributeValue> {
                { _partitionKeyName, new AttributeValue {
                      S = key
                  } }
            };

            GetItemRequest getItemRequest = new GetItemRequest(_tableName, dynamoDbKey);

            return(_client.GetItemAsync(getItemRequest, CancellationToken.None).Result);
        }
Пример #30
0
        public async Task <string> GetNextShardIterator(string app, string stream, string shard)
        {
            if (!_tableConfirmed)
            {
                await EnsureTable();
            }

            var response = await _client.GetItemAsync(new GetItemRequest()
            {
                TableName = _tableName,
                Key       = new Dictionary <string, AttributeValue>
                {
                    { "id", new AttributeValue(FormatId(app, stream, shard)) }
                }
            });

            if (!response.Item.ContainsKey("next_iterator"))
            {
                return(null);
            }

            return(response.Item["next_iterator"].S);
        }