public async Task CreateProjectAsync(string username, Project newProject) { Table projectsTable = Table.LoadTable(this.dynamoDB, this.projectsTableName); var condition = new Expression { ExpressionStatement = $"attribute_not_exists({nameof(Project.Id)})", }; var putOperation = new PutItemOperationConfig { ConditionalExpression = condition, }; var project = new Document(); project[nameof(Project.Id)] = newProject.Id; project[nameof(Project.OwningUser)] = newProject.OwningUser; project[nameof(Project.CompletionDate)] = newProject.CompletionDate; project[nameof(Project.IsArchived)] = newProject.IsArchived; project[nameof(Project.IsFlagged)] = newProject.IsFlagged; project[nameof(Project.PercentageCompleted)] = newProject.PercentageCompleted; project[nameof(Project.Priority)] = newProject.Priority.ToString(); project[nameof(Project.StartDate)] = newProject.StartDate; project[nameof(Project.Status)] = newProject.Status.ToString(); project[nameof(Project.TargetDate)] = newProject.TargetDate; project[nameof(Project.Title)] = newProject.Title; project[nameof(Project.Type)] = newProject.Type.ToString(); DateTime auditDate = DateTime.UtcNow; project[nameof(Project.CreateDate)] = auditDate; project[nameof(Project.UpdateDate)] = auditDate; await projectsTable.PutItemAsync(project, putOperation); }
public async Task <bool> UpsertItemAsync <T>(T item, CancellationToken token) where T : class { await EnsureProvisionedAsync(token); if (!Table.TryLoadTable(_client, TableName, out var table)) { return(false); } var json = JsonSerializer.Serialize(item, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); var document = Document.FromJson(json); var config = new PutItemOperationConfig { ReturnValues = ReturnValues.AllOldAttributes }; var response = await table.PutItemAsync(document, config, token); return(response != null); }
public T Update <T>(T record, bool failIfMissing = false) { string tableName = GetTableName(typeof(T)); Table table = Table.LoadTable(client, tableName); PutItemOperationConfig config = new PutItemOperationConfig(); if (failIfMissing) { config.ConditionalExpression = new Expression(); foreach (string hash in table.HashKeys) { config.ConditionalExpression.ExpressionAttributeNames.Add("#" + hash, hash); string statement = "(attribute_exists(#" + hash + "))"; if (String.IsNullOrWhiteSpace(config.ConditionalExpression.ExpressionStatement)) { config.ConditionalExpression.ExpressionStatement = statement; } else { config.ConditionalExpression.ExpressionStatement = " and " + statement; } } } Document doc = ConvertToDocument(record); Task <Document> task = table.PutItemAsync(doc, config); task.Wait(defaultTimeout); return(record); }
public async Task <Document> PutItemAsync(DynamoDbTablesEnum dynamoDbtable, Document document, PutItemOperationConfig config) { Table table = this.LoadTable(dynamoDbtable); return(await table.PutItemAsync(document, null)); }
public async Task <string> FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context) { Five newFive = JsonConvert.DeserializeObject <Five>(input.Body); if (newFive.company == "b" || newFive.company == "B") { newFive.rating = newFive.rating / 2.0; } List <string> listDescrip = new List <string>(newFive.description.Split(' ')); newFive.lastInstanceOfWord = listDescrip.FindLast(x => x.ToLower().Contains("o")); int position = 0; int position1 = 0; position = newFive.description.LastIndexOf("e"); position1 = newFive.description.LastIndexOf("o"); if (position > position1) { string lastInstanceOf = listDescrip.FindLast(x => x.ToLower().Contains("e")); newFive.lastInstanceOfWord = lastInstanceOf.ToLower(); } else if (position1 > position) { string lastInstanceOf1 = listDescrip.FindLast(x => x.ToLower().Contains("o")); newFive.lastInstanceOfWord = lastInstanceOf1.ToLower(); } else if (position == -1) { string lastInstanceOf1 = listDescrip.FindLast(x => x.ToLower().Contains("o")); newFive.lastInstanceOfWord = lastInstanceOf1.ToLower(); } else if (position1 == -1) { string lastInstanceOf = listDescrip.FindLast(x => x.ToLower().Contains("e")); newFive.lastInstanceOfWord = lastInstanceOf.ToLower(); } Table five = Table.LoadTable(client, tableName); PutItemOperationConfig config = new PutItemOperationConfig(); config.ReturnValues = ReturnValues.AllOldAttributes; Document result = await five.PutItemAsync(Document.FromJson(JsonConvert.SerializeObject(newFive)), config); return(input.Body); }
/// <summary> /// Stores the <see cref="JObject"/> value using the specified keyId and created time. The DynamoDB partition /// key is formed using the <see cref="DynamoDbMetastoreImpl.GetHashKey"/> method, which may or may not add a /// region suffix to it. /// </summary> /// /// <param name="keyId">The keyId to store.</param> /// <param name="created">The created time to store.</param> /// <param name="value">The <see cref="JObject"/> value to store.</param> /// <returns><value>True</value> if the store succeeded, <value>False</value> if the store failed for a known /// condition like duplicate key.</returns> /// <exception cref="AppEncryptionException">Raise an exception in case of any other metastore errors. /// </exception> public bool Store(string keyId, DateTimeOffset created, JObject value) { using (MetricsUtil.MetricsInstance.Measure.Timer.Time(StoreTimerOptions)) { try { Document document = new Document { [PartitionKey] = GetHashKey(keyId), [SortKey] = created.ToUnixTimeSeconds(), // TODO Optimize JObject to Document conversion. Just need lambda that calls Document. // Add and recurses for Dictionary and List types [AttributeKeyRecord] = Document.FromJson(value.ToString()), }; // Note conditional expression using attribute_not_exists has special semantics. Can be used on // partition OR sort key alone to guarantee primary key uniqueness. It automatically checks for // existence of this item's composite primary key and if it contains the specified attribute name, // either of which is inherently required. Expression expr = new Expression { ExpressionStatement = "attribute_not_exists(" + PartitionKey + ")" }; PutItemOperationConfig config = new PutItemOperationConfig { ConditionalExpression = expr, }; table.PutItemAsync(document, config).Wait(); return(true); } catch (AggregateException ae) { foreach (Exception exception in ae.InnerExceptions) { if (exception is ConditionalCheckFailedException) { Logger.LogInformation( "Attempted to create duplicate key: {keyId} {created}", keyId, created); return(false); } } Logger.LogError(ae, "Metastore error during store"); throw new AppEncryptionException("Metastore error:", ae); } } }
public async Task <string> FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context) { Table items = Table.LoadTable(client, tableName); Item myItem = JsonConvert.DeserializeObject <Item>(input.Body); PutItemOperationConfig config = new PutItemOperationConfig(); config.ReturnValues = ReturnValues.AllOldAttributes; Document result = await items.PutItemAsync(Document.FromJson(JsonConvert.SerializeObject(myItem)), config); return(input.Body); }
private async Task <APIGatewayProxyResponse> PostHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { var payload = JsonConvert.DeserializeObject <Payload>(apigProxyEvent.Body); string docHash = hash(payload.Document); payload.Hash = docHash; var document = Payload.ToDynamodbDocument(payload); Expression expr = new Expression(); expr.ExpressionStatement = "ID <> :id"; expr.ExpressionAttributeValues[":id"] = payload.ID; PutItemOperationConfig putConfig = new PutItemOperationConfig { ConditionalExpression = expr, ReturnValues = ReturnValues.AllOldAttributes }; try{ table.PutItemAsync(document, putConfig).Wait(); }catch (Exception e) { return(new APIGatewayProxyResponse { Body = JsonConvert.SerializeObject(new Dictionary <string, string> { { "id", payload.ID.ToString() }, { "message", "object already exists" } }), StatusCode = 409, Headers = new Dictionary <string, string> { { "Content-Type", "application/json" } } }); } var body = new Dictionary <string, string> { { "id", payload.ID.ToString() }, { "hash", docHash } }; return(new APIGatewayProxyResponse { Body = JsonConvert.SerializeObject(body), StatusCode = 201, Headers = new Dictionary <string, string> { { "Content-Type", "application/json" } } }); }
public async Task PutItemAsync(string tableName, object item, bool checkUniqueKey = false) { var jsonData = JsonConvert.SerializeObject(item, serializerSettings); var document = Document.FromJson(jsonData); Table table; try { table = Table.LoadTable(dynamoDBClient, tableName); } catch (ResourceNotFoundException e) { throw new TableNameFailException($"Not found the source '{tableName}'.", e); } foreach (var k in table.Keys) { if (!document.ContainsKey(k.Key)) { throw new PrimaryKeyNameFailException($"Not found the primary key '{k.Key}' in saving data.", null); } } var keys = table.Keys.Select(k => k.Key).ToArray(); var config = new PutItemOperationConfig(); if (checkUniqueKey) { config.ConditionalExpression = new Expression { ExpressionStatement = string.Join(" && ", keys.Select(k => $"attribute_not_exists({k})")) }; } try { await table.PutItemAsync(document, config); } catch (ConditionalCheckFailedException e) { throw new DuplicateKeyException( $"The source '{tableName}' has already contained data with keys '{string.Join(", ", keys)}'.", e); } }
private async Task TestExpressionPut(Table hashTable) { Document doc = new Document(); doc["Id"] = DateTime.Now.Ticks; doc["name"] = "condition-form"; await hashTable.PutItemAsync(doc); Expression expression = new Expression { ExpressionStatement = "attribute_not_exists(referencecounter) or referencecounter = :cond1", ExpressionAttributeValues = new Dictionary <string, DynamoDBEntry> { { ":cond1", 0 } } }; PutItemOperationConfig config = new PutItemOperationConfig { ConditionalExpression = expression }; doc["update-test"] = 1; //Assert.IsTrue(hashTable.TryPutItem(doc, config)); await hashTable.PutItemAsync(doc, config); doc["referencecounter"] = 0; await hashTable.UpdateItemAsync(doc); doc["update-test"] = null; //Assert.IsTrue(hashTable.TryPutItem(doc, config)); await hashTable.PutItemAsync(doc, config); // Make sure removing attributes works doc = await hashTable.GetItemAsync(doc); Assert.IsFalse(doc.Contains("update-test")); doc["referencecounter"] = 1; await hashTable.UpdateItemAsync(doc); doc["update-test"] = 3; //Assert.IsFalse(hashTable.TryPutItem(doc, config)); await AssertExtensions.ExpectExceptionAsync(hashTable.PutItemAsync(doc, config)); await hashTable.DeleteItemAsync(doc); }
public async Task <ExpandoObject> FunctionHandler(APIGatewayProxyRequest input, ILambdaContext db) { HttpClient client = new HttpClient(); string url = $"https://api.nasa.gov/planetary/apod?api_key=DcyC0NbDLkfedANtzI58asjhgNQWWHYozbs0yHeP"; Table pod = Table.LoadTable(dbclient, tableName); NasaPOD podItem = JsonConvert.DeserializeObject <NasaPOD>(await client.GetStringAsync(url)); PutItemOperationConfig config = new PutItemOperationConfig(); config.ReturnValues = ReturnValues.AllOldAttributes; await pod.PutItemAsync(Document.FromJson(JsonConvert.SerializeObject(podItem)), config); return(JsonConvert.DeserializeObject <ExpandoObject>(await client.GetStringAsync(url))); }
async Task <bool> IDataRepository.AddFamily(Family family) { var document = _ddbContext.ToDocument(family); var config = new PutItemOperationConfig { ConditionalExpression = GetAttributeNotExists(nameof(family.FamilyId)) }; try { _logger.LogInformation($"Creating family with churchId :{family.ChurchId} and familyId:{family.FamilyId}"); await _familiesTable.PutItemAsync(document, config); return(true); } catch (ConditionalCheckFailedException) { _logger.LogInformation($"Family with churchId :{family.ChurchId} and familyId:{family.FamilyId} already exits"); return(false); } }
protected Task CreateOrUpdateItemAsync <T>(T item, string pk, string sk, Expression condition, CancellationToken cancellationToken) { var document = Serialize(item); document["_Type"] = item.GetType().Name; document["_Modified"] = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); document["PK"] = pk ?? throw new ArgumentNullException(nameof(pk)); document["SK"] = sk ?? throw new ArgumentNullException(nameof(sk)); // add operation condition when provided PutItemOperationConfig operationConfig = null; if (condition != null) { operationConfig = new PutItemOperationConfig { ConditionalExpression = condition }; } return(Table.PutItemAsync(document, operationConfig, cancellationToken)); }
public async void CreateAUser() { Document user = new Document { ["EmailAddress"] = "*****@*****.**", ["Password"] = "******" }; // Create a condition expression for the optional conditional put operation. Expression expr = new Expression { ExpressionStatement = "EmailAddress != :pk", ExpressionAttributeValues = { [":pk"] = "*****@*****.**" } }; PutItemOperationConfig config = new PutItemOperationConfig() { ConditionalExpression = expr }; await this._dynamoDbService.PutItemAsync(DynamoDbTablesEnum.Users, user, config); }
async Task <bool> IDataRepository.AddChurch(Church church) { var document = _ddbContext.ToDocument(church); var config = new PutItemOperationConfig { ConditionalExpression = GetAttributeNotExists(nameof(church.ChurchId)) }; try { _logger.LogInformation($"Adding a new church with churchId {church.ChurchId}"); await _churchesTable.PutItemAsync(document, config); return(true); } catch (ConditionalCheckFailedException) { _logger.LogInformation($"Church with id {church.ChurchId} already exists"); return(false); } }
public async Task <List <dynamic> > FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context) { HttpClient client = new HttpClient(); dynamic obj = new ExpandoObject(); //top cryptos api endpoint HttpResponseMessage response = client.GetAsync("https://api.coincap.io/v2/assets").Result; response.EnsureSuccessStatusCode(); string result = response.Content.ReadAsStringAsync().Result; var expConverter = new Newtonsoft.Json.Converters.ExpandoObjectConverter(); obj = JsonConvert.DeserializeObject <ExpandoObject>(result, expConverter); Table coins = Table.LoadTable(cli, tableName); var json = JsonConvert.SerializeObject(obj.data); List <Coin> lCoins = JsonConvert.DeserializeObject <List <Coin> >(json); PutItemOperationConfig config = new PutItemOperationConfig(); foreach (Coin c in lCoins) { Console.WriteLine(c.id); Document res = await coins.PutItemAsync(Document.FromJson(JsonConvert.SerializeObject(c)), config); } return(obj.data); }
private static string tableName = "FinalAssignment"; //Name of the table in DynamoDB public async Task <List <dynamic> > FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context) { //Create an http client and expandoobject HttpClient client = new HttpClient(); dynamic obj = new ExpandoObject(); //Get the quotes from the api and put them into a result string HttpResponseMessage response = client.GetAsync("https://quote-garden.herokuapp.com/api/v3/quotes").Result; response.EnsureSuccessStatusCode(); string result = response.Content.ReadAsStringAsync().Result; //Convert the result string to an ExpanoObject var converter = new Newtonsoft.Json.Converters.ExpandoObjectConverter(); obj = JsonConvert.DeserializeObject <ExpandoObject>(result, converter); //Load the quotes tables Table quotes = Table.LoadTable(dbClient, tableName); //Get the data from the quotes object (we don't want the status codes or anything else, just the data). var json = JsonConvert.SerializeObject(obj.data); //Create a list of all of the data that's in the json object List <Quote> quoteList = JsonConvert.DeserializeObject <List <Quote> >(json); PutItemOperationConfig config = new PutItemOperationConfig(); //Put the data into the table foreach (Quote q in quoteList) { Document res = await quotes.PutItemAsync(Document.FromJson(JsonConvert.SerializeObject(q)), config); } return(obj.data); }
public async Task <string> FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context) { Table items = Table.LoadTable(client, tableName); Item newItem = JsonConvert.DeserializeObject <Item>(input.Body); if (newItem.company.ToUpper() == "B") { if (0 < newItem.rating && newItem.rating < 11) { int rate = newItem.rating; if (newItem.rating == 1) { } else { newItem.rating = (rate / 2); } } else { return("Error: Rating for Company B is not between 1 and 10"); } } else if (newItem.company.ToUpper() == "A") { if (0 < newItem.rating && newItem.rating < 6) { } else { return("Error: Rating for Company A is not between 1 and 5"); } } else { return("Error: Company does not match A or B"); } List <string> result = newItem.description.Split(' ').ToList(); string lastInstanceOfO = result.FindLast(x => x.ToUpper().Contains("O")); int lastO = result.FindLastIndex(x => x.ToUpper().Contains("O")); string lastInstanceOfE = result.FindLast(x => x.ToUpper().Contains("E")); int lastE = result.FindLastIndex(x => x.ToUpper().Contains("E")); if (newItem.description == "") { newItem.description = "Not Available"; newItem.lastInstanceOfWord = "Not Available"; } else if (lastInstanceOfE == null && lastInstanceOfO == null) { newItem.lastInstanceOfWord = "Not Available"; } else if (lastE > lastO) { newItem.lastInstanceOfWord = lastInstanceOfE; } else if (lastO > lastE) { newItem.lastInstanceOfWord = lastInstanceOfO; } else { newItem.lastInstanceOfWord = lastInstanceOfO; } PutItemOperationConfig config = new PutItemOperationConfig(); config.ReturnValues = ReturnValues.AllOldAttributes; //Document myDoc = await items.PutItemAsync(Document.FromJson(JsonConvert.SerializeObject(newItem)), config); //return myDoc.ToJson(); await items.PutItemAsync(Document.FromJson(JsonConvert.SerializeObject(newItem)), config); return(input.Body); }