public static async void UpdateBookPriceConditionally(AmazonDynamoDBClient client, Table productCatalog) { Console.WriteLine("\n*** Executing UpdateBookPriceConditionally() ***"); int partitionKey = SampleBookId; var book = new Document(); book["Id"] = partitionKey; book["Price"] = 29.99; // For conditional price update, creating a condition expression. Expression expr = new Expression(); expr.ExpressionStatement = "Price = :val"; expr.ExpressionAttributeValues[":val"] = 19.00; // Optional parameters. UpdateItemOperationConfig config = new UpdateItemOperationConfig { ConditionalExpression = expr, ReturnValues = ReturnValues.AllNewAttributes }; Document updatedBook = await productCatalog.UpdateItemAsync(book, config); Console.WriteLine("UpdateBookPriceConditionally: Printing item whose price was conditionally updated"); PrintDocument(client, updatedBook); }
public void ConditionalUpdate <T>(T tObject, string condAttribute, object expectedValue) { var splittedAttributes = condAttribute.Split('.'); var specificAttributeToCheck = condAttribute; string first = ""; string last = condAttribute; if (splittedAttributes.Length > 1) { last = splittedAttributes.Last(); first = condAttribute.Remove(condAttribute.Length - last.Length); } Expression expr = new Expression(); expr.ExpressionStatement = first + "#Cond = :Cond"; expr.ExpressionAttributeNames["#Cond"] = last; if (expectedValue.GetType() == typeof(int)) { expr.ExpressionAttributeValues[":Cond"] = (int)expectedValue; } if (expectedValue.GetType() == typeof(string)) { expr.ExpressionAttributeValues[":Cond"] = (string)expectedValue; } UpdateItemOperationConfig config = new UpdateItemOperationConfig() { ConditionalExpression = expr, ReturnValues = ReturnValues.AllNewAttributes }; dynamoDBTable.UpdateItem(AWSDocumentConverter.ToDocument(tObject), config); }
/// <summary> /// Updates a book item if it meets the specified criteria. /// </summary> /// <param name="productCatalog">A DynamoDB table object.</param> /// <param name="sampleBookId">An integer value representing the book's ID.</param> public static async void UpdateBookPriceConditionally( Table productCatalog, int sampleBookId) { Console.WriteLine("\n*** Executing UpdateBookPriceConditionally() ***"); int partitionKey = sampleBookId; var book = new Document { ["Id"] = partitionKey, ["Price"] = 29.99, }; // For conditional price update, creating a condition expression. var expr = new Expression { ExpressionStatement = "Price = :val", }; expr.ExpressionAttributeValues[":val"] = 19.00; // Optional parameters. var config = new UpdateItemOperationConfig { ConditionalExpression = expr, ReturnValues = ReturnValues.AllNewAttributes, }; Document updatedBook = await productCatalog.UpdateItemAsync(book, config); Console.WriteLine("UpdateBookPriceConditionally: Printing item whose price was conditionally updated"); PrintDocument(updatedBook); }
public async Task <APIGatewayProxyResponse> Update(APIGatewayProxyRequest request, ILambdaContext context) { var appointmentRequest = JsonConvert.DeserializeObject <AppointmentRequest>(request.Body); var client = new AmazonDynamoDBClient(RegionEndpoint.USEast1); var appointmentId = appointmentRequest.AppointmentId; var productCatalog = Table.LoadTable(client, "Appointment"); var appointment = new Document { ["AppointmentId"] = appointmentId, ["PracticeId"] = appointmentRequest.PracticeId, ["IsServed"] = "true" }; var config = new UpdateItemOperationConfig { // Get updated item in response. ReturnValues = ReturnValues.AllNewAttributes }; await productCatalog.UpdateItemAsync(appointment, config); return(new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = "success" }); }
private UpdateItemOperationConfig GetUpdateItemOperationConfigForConditionalUpdate(string condAttribute, object expectedValue) { var splittedAttributes = condAttribute.Split('.'); var specificAttributeToCheck = condAttribute; string first = ""; string last = condAttribute; if (splittedAttributes.Length > 1) { last = splittedAttributes.Last(); first = condAttribute.Remove(condAttribute.Length - last.Length); } Expression expr = new Expression(); expr.ExpressionStatement = first + "#Cond = :Cond"; expr.ExpressionAttributeNames["#Cond"] = last; if (expectedValue.GetType() == typeof(int)) { expr.ExpressionAttributeValues[":Cond"] = (int)expectedValue; } if (expectedValue.GetType() == typeof(string)) { expr.ExpressionAttributeValues[":Cond"] = (string)expectedValue; } UpdateItemOperationConfig config = new UpdateItemOperationConfig() { ConditionalExpression = expr, ReturnValues = ReturnValues.None }; return(config); }
/// <summary> /// Updates multiple attributes for a book and writes the changes to the /// DynamoDB table ProductCatalog. /// </summary> /// <param name="productCatalog">A DynamoDB table object.</param> /// <param name="sampleBookId">An integer value representing the book's ID.</param> public static async void UpdateMultipleAttributes( Table productCatalog, int sampleBookId) { Console.WriteLine("\nUpdating multiple attributes...."); int partitionKey = sampleBookId; var book = new Document { ["Id"] = partitionKey, // List of attribute updates. // The following replaces the existing authors list. ["Authors"] = new List <string> { "Author x", "Author y" }, ["newAttribute"] = "New Value", ["ISBN"] = null, // Remove it. }; // Optional parameters. var config = new UpdateItemOperationConfig { // Gets updated item in response. ReturnValues = ReturnValues.AllNewAttributes, }; Document updatedBook = await productCatalog.UpdateItemAsync(book, config); Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ..."); PrintDocument(updatedBook); }
public async Task <ActionResult <string> > Put(int year, string title) { Table table = Table.LoadTable(dynamoDb, TableName); var movie = new Document(); movie["year"] = year; movie["title"] = title; var movieInfo = new Document(); movieInfo["rating"] = 1; // if you had a more nested structure, // how would you only update a single item in the nested object? movie["info"] = movieInfo; // Optional parameters. UpdateItemOperationConfig config = new UpdateItemOperationConfig { // Get updated item in response. ReturnValues = ReturnValues.AllNewAttributes }; var document = await table.UpdateItemAsync(movie, config); return(document.ToJsonPretty()); }
private void SaveHelper <T>(T value, DynamoDBOperationConfig operationConfig) { if (value == null) { return; } DynamoDBFlatConfig flatConfig = new DynamoDBFlatConfig(operationConfig, this.Config); ItemStorage storage = ObjectToItemStorage(value, false, flatConfig); if (storage == null) { return; } Table table = GetTargetTable(storage.Config, flatConfig); if ((flatConfig.SkipVersionCheck.HasValue && flatConfig.SkipVersionCheck.Value) || !storage.Config.HasVersion) { table.UpdateHelper(storage.Document, table.MakeKey(storage.Document), null); } else { Document expectedDocument = CreateExpectedDocumentForVersion(storage); SetNewVersion(storage); var updateItemOperationConfig = new UpdateItemOperationConfig { Expected = expectedDocument, ReturnValues = ReturnValues.None, }; table.UpdateHelper(storage.Document, table.MakeKey(storage.Document), updateItemOperationConfig); PopulateInstance(storage, value, flatConfig); } }
public static async void UpdateMultipleAttributes(AmazonDynamoDBClient client, Table productCatalog) { Console.WriteLine("\n*** Executing UpdateMultipleAttributes() ***"); Console.WriteLine("\nUpdating multiple attributes...."); int partitionKey = SampleBookId; var book = new Document(); book["Id"] = partitionKey; // List of attribute updates. // The following replaces the existing authors list. book["Authors"] = new List <string> { "Author x", "Author y" }; book["newAttribute"] = "New Value"; book["ISBN"] = null; // Remove it. // Optional parameters. UpdateItemOperationConfig config = new UpdateItemOperationConfig { // Get updated item in response. ReturnValues = ReturnValues.AllNewAttributes }; Document updatedBook = await productCatalog.UpdateItemAsync(book, config); Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ..."); PrintDocument(client, updatedBook); }
public async Task <Document> UpdateItemAsync(DynamoDbTablesEnum dynamoDbTable, Document document, UpdateItemOperationConfig config) { Table table = this.LoadTable(dynamoDbTable); return(await table.UpdateItemAsync(document, config)); }
public Document PartialUpdateCommand <T>(T tObject, ReturnValues returnValues = ReturnValues.AllNewAttributes) { var document = AWSDocumentConverter.ToDocument(tObject); UpdateItemOperationConfig config = new UpdateItemOperationConfig { ReturnValues = returnValues }; return(dynamoDBTable.UpdateItem(document, config)); }
private static void UpdateRecommendation(Document updatedDocument) { // Optional parameters. UpdateItemOperationConfig config = new UpdateItemOperationConfig { // Get updated item in response. ReturnValues = ReturnValues.None, }; _recommendationsTable.UpdateItemAsync(updatedDocument, config); }
public async Task UpdateItem(string tableName, JArray item) { var tableRepo = new TableRepo(dynamoDB); Document tableAttr = await tableRepo.GetTableAttr(tableName); List <string> attribute = new List <string> { }; List <string> type = new List <string> { }; List <string> key = new List <string> { }; if (tableAttr != null) { var c = tableAttr["attr"].AsDocument().GetAttributeNames(); foreach (var c1 in c) { attribute.Add(c1); var t = tableAttr["attr"].AsDocument()[c1].AsDocument()["type"]; var k = tableAttr["attr"].AsDocument()[c1].AsDocument()["key"]; type.Add(t); key.Add(k); } } Table table = Table.LoadTable(dynamoDB, tableName); var itm = new Document(); foreach (var value in item) { switch (type[attribute.IndexOf(value["key"].ToString())]) { case "N": itm[value["key"].ToString()] = (float)value["value"]; break; case "B": byte[] byteArray = Encoding.ASCII.GetBytes(value["value"].ToString()); MemoryStream stream = new MemoryStream(byteArray); itm[value["key"].ToString()] = stream; break; default: itm[value["key"].ToString()] = value["value"].ToString(); break; } } UpdateItemOperationConfig config = new UpdateItemOperationConfig { ReturnValues = ReturnValues.AllNewAttributes }; await table.UpdateItemAsync(itm, config); }
public async Task <User> UpdateUserAsync(User userToUpdate) { var userDocument = ConvertUserToDocument(userToUpdate); var config = new UpdateItemOperationConfig { ReturnValues = ReturnValues.AllNewAttributes }; var result = await UserTable.UpdateItemAsync(userDocument, config); return(ConvertDocumentToUser(result)); }
private async Task TestExpressionUpdate(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 } } }; UpdateItemOperationConfig config = new UpdateItemOperationConfig { ConditionalExpression = expression }; doc["update-test"] = 1; //Assert.IsTrue(hashTable.TryUpdateItem(doc, config)); await hashTable.UpdateItemAsync(doc, config); doc["referencecounter"] = 0; await hashTable.UpdateItemAsync(doc); doc["update-test"] = null; //Assert.IsTrue(hashTable.TryUpdateItem(doc, config)); await hashTable.UpdateItemAsync(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.TryUpdateItem(doc, config)); await AssertExtensions.ExpectExceptionAsync(hashTable.UpdateItemAsync(doc, config)); doc = await hashTable.GetItemAsync(doc); Assert.IsFalse(doc.Contains("update-test")); await hashTable.DeleteItemAsync(doc); }
public async Task UpdateItemAsync(string tableName, object item) { 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 UpdateItemOperationConfig { ConditionalExpression = new Expression { ExpressionStatement = string.Join(" && ", keys.Select(k => $"attribute_exists({k})")) }, ReturnValues = ReturnValues.None }; try { await table.UpdateItemAsync(document, config); } catch (ConditionalCheckFailedException e) { throw new NotExistKeyException( $"The source '{tableName}' has not contained data with keys '{string.Join(", ", keys)}'.", e); } }
private async Task <bool> UpdateTable <T>(Table table, T item, Expression condtionalExpression) { var document = _ddbContext.ToDocument(item); var config = new UpdateItemOperationConfig { ConditionalExpression = condtionalExpression }; try { await table.UpdateItemAsync(document, config); return(true); } catch (ConditionalCheckFailedException) { return(false); } }
private void UpdateMultipleAttributes() { this.displayMessage += ("\n*** Executing UpdateMultipleAttributes() ***"); this.displayMessage += ("\nUpdating multiple attributes...."); int hashKey = sampleBookId; var book = new Document(); book["Id"] = hashKey; // List of attribute updates. // The following replaces the existing authors list. book["Authors"] = new List <string> { "Author x", "Author y" }; book["newAttribute"] = "New Value"; book["ISBN"] = null; // Remove it. // Optional parameters. UpdateItemOperationConfig config = new UpdateItemOperationConfig { // Get updated item in response. ReturnValues = ReturnValues.AllNewAttributes }; productCatalog.UpdateItemAsync(book, config, (AmazonDynamoResult <Document> result) => { if (result.Exception != null) { this.displayMessage += ("\nUpdateMultipleAttributes ; " + result.Exception.Message); Debug.LogException(result.Exception); return; } Document updatedBook = result.Response; this.displayMessage += ("\nUpdateMultipleAttributes: Printing item after updates ..."); PrintDocument(updatedBook); }, null); }
public async Task <IActionResult> Gete([FromHeader] string key, [FromHeader] string payload) { try { long timestamp = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds; if (key != "enginekey") { return(BadRequest("bad")); } Console.WriteLine(payload); AmazonDynamoDBClient client = new AmazonDynamoDBClient(); Table table = Table.LoadTable(client, "OrderRegistry"); List <Document> docs = new List <Document>(); // begin parse payload int i = 0; if (payload[i] != '[') { throw new Exception(); } Document doc, docother = new Document(); string Id = new string(""); string Quantity = new string(""); string Price = new string(""); string Executed = new string(""); string OtherOrder = new string(""); i += 1; while (true && i < payload.Length) { if (payload[i] == ',') { i += 1; break; } Id += payload[i]; i += 1; } while (true && i < payload.Length) { if (payload[i] == ',') { i += 1; break; } Quantity += payload[i]; i += 1; } while (true && i < payload.Length) { if (payload[i] == ',') { i += 1; break; } Price += payload[i]; i += 1; } while (true && i < payload.Length) { if (payload[i] == ',') { i += 1; break; } Executed += payload[i]; i += 1; } while (true && i < payload.Length) { if (payload[i] == ']') { break; } OtherOrder += payload[i]; i += 1; } double executed; try { executed = double.Parse(Executed); } catch { return(BadRequest("error parse")); } // end parse payload doc = await table.GetItemAsync(Id); docother = await table.GetItemAsync(OtherOrder); if (doc["Email"].ToString() == docother["Email"].ToString()) // self fill { if (doc["OrderType"].ToString() == "limit") { double currentself = doc["OrderQuantity"].AsDouble(); currentself = currentself - executed; Document currentselfdoc = new Document(); currentselfdoc["Id"] = Id.ToString(); currentselfdoc["OrderQuantity"] = currentself.ToString(); await table.UpdateItemAsync(currentselfdoc); return(Ok()); } return(Ok()); } doc["Price"] = Price; if (doc["OrderType"].ToString() == "market") // recent orders { Document recentorder = new Document(); recentorder["Timestamp"] = timestamp.ToString(); recentorder["Price"] = Price.ToString(); recentorder["Quantity"] = Executed.ToString(); Table recentordertable = Table.LoadTable(client, "RecentOrdersSPXUSD"); await recentordertable.PutItemAsync(recentorder); } double price; double.TryParse(Price, out price); await table.UpdateItemAsync(doc); Table postable = Table.LoadTable(client, "PositionRegistry"); Document posdoc = await postable.GetItemAsync(doc["Email"].ToString()); Document posupdate = new Document(); double pos; try { posdoc["POSSPXUSD"].ToString(); if (posdoc["POSSPXUSD"].ToString() == "0") { pos = 0; } pos = posdoc["POSSPXUSD"].AsDouble(); } catch //never position or 0 position { await postable.PutItemAsync(new Document() { ["Email"] = doc["Email"].ToString() }); pos = 0; } if (doc["Side"].ToString() == "buy" && doc["OrderType"].ToString() == "limit") { pos = pos + executed; } else if (doc["Side"].ToString() == "sell" && doc["OrderType"].ToString() == "limit") { pos = pos - executed; executed *= -1; } else if (doc["Side"].ToString() == "sell" && doc["OrderType"].ToString() == "market") { pos = pos - executed; executed *= -1; } else if (doc["Side"].ToString() == "buy" && doc["OrderType"].ToString() == "market") { pos = pos + executed; } else { return(BadRequest("error")); } posupdate["Email"] = doc["Email"].ToString(); posupdate["POSSPXUSD"] = pos.ToString(); //await postable.UpdateItemAsync(posupdate); if (pos == 0) { posupdate["POSSPXUSDEntry"] = "na"; } // closed out pos else if ((pos - executed) == 0 || (pos + executed) == 0 || (pos - executed) == 0 || (pos + executed) == 0) /*open pos from 0*/ { posupdate["POSSPXUSDEntry"] = Price; } else if ((pos - executed) > 0 || (pos + executed) < 0 || (pos - executed) < 0 || (pos + executed) > 0) /*pre-existing pos non zero*/ { if ((Math.Abs(posdoc["POSSPXUSD"].AsDouble()) > Math.Abs(executed) || (Math.Abs(posdoc["POSSPXUSD"].AsDouble()) < Math.Abs(executed) && ((posdoc["POSSPXUSD"].AsDouble() > 0 && executed > 0) || posdoc["POSSPXUSD"].AsDouble() < 0 && executed < 0)))) // reduce or add { if (pos > 0) { double newentry = ((posdoc["POSSPXUSD"].AsDouble() * posdoc["POSSPXUSDEntry"].AsDouble()) + (executed * price)) / (posdoc["POSSPXUSD"].AsDouble() + executed); if ((pos > 0 && (pos - posdoc["POSSPXUSD"].AsDouble() > 0)) || (pos < 0 && (pos - posdoc["POSSPXUSD"].AsDouble() < 0)))/*if add*/ { posupdate["POSSPXUSDEntry"] = newentry.ToString(); } else // profit/loss { } } else if (pos < 0) { double newentry = ((posdoc["POSSPXUSD"].AsDouble() * posdoc["POSSPXUSDEntry"].AsDouble()) + (executed * price)) / (posdoc["POSSPXUSD"].AsDouble() + executed); if ((pos > 0 && (pos - posdoc["POSSPXUSD"].AsDouble() > 0)) || (pos < 0 && (pos - posdoc["POSSPXUSD"].AsDouble() < 0)))/*if add*/ { posupdate["POSSPXUSDEntry"] = newentry.ToString(); } else // profit/loss { } } else { Console.WriteLine("error calc entry"); } } else // reduce and add { if (pos > 0) { //reduce double posremain = (executed * -1) - posdoc["POSSPXUSD"].AsDouble(); //add posupdate["POSSPXUSD"] = (0 - posremain).ToString(); posupdate["POSSPXUSDEntry"] = Price; } else if (pos < 0) { //reduce double posremain = executed - (posdoc["POSSPXUSD"].AsDouble() * -1); //add posupdate["POSSPXUSD"] = (0 + posremain).ToString(); posupdate["POSSPXUSDEntry"] = Price; } } } // pull from database and calculate new position value. UpdateItemOperationConfig update = new UpdateItemOperationConfig(); ExpectedValue expected = new ExpectedValue(ScanOperator.Equal); update.Expected = posdoc; try { Document test = await postable.UpdateItemAsync(posupdate, update); } catch { Thread.Sleep(20); Console.WriteLine("error"); posdoc = await postable.GetItemAsync(doc["Email"].ToString()); posupdate = new Document(); try { posdoc["POSSPXUSD"].ToString(); if (posdoc["POSSPXUSD"].ToString() == "0") { throw new Exception(); } pos = posdoc["POSSPXUSD"].AsDouble(); } catch //never position or 0 position { pos = 0; } try { executed = double.Parse(Executed); } catch { return(BadRequest("error parse")); } if (doc["Side"].ToString() == "buy" && doc["OrderType"].ToString() == "limit") { pos = pos + executed; } else if (doc["Side"].ToString() == "sell" && doc["OrderType"].ToString() == "limit") { pos = pos - executed; executed *= -1; } else if (doc["Side"].ToString() == "sell" && doc["OrderType"].ToString() == "market") { pos = pos - executed; executed *= -1; } else if (doc["Side"].ToString() == "buy" && doc["OrderType"].ToString() == "market") { pos = pos + executed; } else { return(BadRequest("error")); } posupdate["Email"] = doc["Email"].ToString(); posupdate["POSSPXUSD"] = pos.ToString(); if (pos == 0) { posupdate["POSSPXUSDEntry"] = "na"; } // closed out pos else if ((pos - executed) == 0 || (pos + executed) == 0 || (pos - executed) == 0 || (pos + executed) == 0) /*open pos from 0*/ { posupdate["POSSPXUSDEntry"] = Price; } else if ((pos - executed) > 0 || (pos + executed) < 0 || (pos - executed) < 0 || (pos + executed) > 0) /*pre-existing pos non zero*/ { if ((Math.Abs(posdoc["POSSPXUSD"].AsDouble()) > Math.Abs(executed) || (Math.Abs(posdoc["POSSPXUSD"].AsDouble()) < Math.Abs(executed) && ((posdoc["POSSPXUSD"].AsDouble() > 0 && executed > 0) || posdoc["POSSPXUSD"].AsDouble() < 0 && executed < 0)))) // reduce or add { if (pos > 0) { double newentry = ((posdoc["POSSPXUSD"].AsDouble() * posdoc["POSSPXUSDEntry"].AsDouble()) + (executed * price)) / (posdoc["POSSPXUSD"].AsDouble() + executed); if ((pos > 0 && (pos - posdoc["POSSPXUSD"].AsDouble() > 0)) || (pos < 0 && (pos - posdoc["POSSPXUSD"].AsDouble() < 0)))/*if add*/ { posupdate["POSSPXUSDEntry"] = newentry.ToString(); } else // profit/loss { } } else if (pos < 0) { double newentry = ((posdoc["POSSPXUSD"].AsDouble() * posdoc["POSSPXUSDEntry"].AsDouble()) + (executed * price)) / (posdoc["POSSPXUSD"].AsDouble() + executed); if ((pos > 0 && (pos - posdoc["POSSPXUSD"].AsDouble() > 0)) || (pos < 0 && (pos - posdoc["POSSPXUSD"].AsDouble() < 0)))/*if add*/ { posupdate["POSSPXUSDEntry"] = newentry.ToString(); } else // profit/loss { } } else { Console.WriteLine("error calc entry"); } } else // reduce and add { if (pos > 0) { //reduce double posremain = (executed * -1) - posdoc["POSSPXUSD"].AsDouble(); //add posupdate["POSSPXUSD"] = (0 - posremain).ToString(); posupdate["POSSPXUSDEntry"] = Price; } else if (pos < 0) { //reduce double posremain = executed - (posdoc["POSSPXUSD"].AsDouble() * -1); //add posupdate["POSSPXUSD"] = (0 + posremain).ToString(); posupdate["POSSPXUSDEntry"] = Price; } } } await postable.UpdateItemAsync(posupdate); } return(Ok()); } catch { return(BadRequest("something went wrong")); } }
/// <summary> /// /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public async Task FunctionHandler(S3Event input, ILambdaContext context) { // Initialize the Amazon Cognito credentials provider CognitoAWSCredentials credentials = new CognitoAWSCredentials( "us-east-1:6d711ae9-1084-4a71-9ef6-7551ca74ad0b", // Identity pool ID RegionEndpoint.USEast1 // Region ); dynamoDbClient = new AmazonDynamoDBClient(credentials, RegionEndpoint.USEast1); Table customersTbl = Table.LoadTable(dynamoDbClient, "Customer"); AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(); IAmazonS3 s3Client = new AmazonS3Client(RegionEndpoint.USEast2); //Debug.WriteLine("Creating collection: " + FACE_COLLECTION_ID); //CreateCollectionRequest createCollectionRequest = new CreateCollectionRequest() //{ // CollectionId = FACE_COLLECTION_ID //}; //CreateCollectionResponse createCollectionResponse = rekognitionClient.CreateCollectionAsync(createCollectionRequest).Result; //Debug.WriteLine("CollectionArn : " + createCollectionResponse.CollectionArn); //Debug.WriteLine("Status code : " + createCollectionResponse.StatusCode); foreach (var record in input.Records) { //if(!SupportedImageTypes.Contains(Path.GetExtension(record.S3.Object.Key))) //{ // Debug.WriteLine($"Object {record.S3.Bucket.Name}:{record.S3.Object.Key} is not a supported image type"); // continue; //} Image image = new Image() { S3Object = new Amazon.Rekognition.Model.S3Object { Bucket = record.S3.Bucket.Name, Name = record.S3.Object.Key } }; GetObjectTaggingResponse taggingResponse = s3Client.GetObjectTaggingAsync( new GetObjectTaggingRequest { BucketName = record.S3.Bucket.Name, Key = record.S3.Object.Key } ).Result; Tag customerID = taggingResponse.Tagging[0];//TODO: HARDCODING!! IndexFacesRequest indexFacesRequest = new IndexFacesRequest() { Image = image, CollectionId = FACE_COLLECTION_ID, ExternalImageId = record.S3.Object.Key, DetectionAttributes = new List <String>() { "ALL" } }; IndexFacesResponse indexFacesResponse = rekognitionClient.IndexFacesAsync(indexFacesRequest).Result; Debug.WriteLine(record.S3.Object.Key + " added"); foreach (FaceRecord faceRecord in indexFacesResponse.FaceRecords) { Debug.WriteLine("Face detected: Faceid is " + faceRecord.Face.FaceId); Console.WriteLine("\nAfter Indexing, Updating FaceID of the Customer...."); string partitionKey = customerID.Value; var customer = new Document(); customer["Id"] = Int32.Parse(partitionKey); // List of attribute updates. // The following replaces the existing authors list. customer["FaceId"] = faceRecord.Face.FaceId; // Optional parameters. UpdateItemOperationConfig config = new UpdateItemOperationConfig { // Get updated item in response. ReturnValues = ReturnValues.AllNewAttributes }; Document updatedCustomer = customersTbl.UpdateItemAsync(customer, config).Result; Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ..."); PrintDocument(updatedCustomer); } } return; }
private async void ButtonSubmit_Click(object sender, RoutedEventArgs e) { //MessageBox.Show("this is submit button"); String name = txtName.Text; //MessageBox.Show(name); try { bool isNameEmpty = string.IsNullOrEmpty(txtName.Text); bool isPhoneEmpty = string.IsNullOrEmpty(txtPhone.Text); bool isDescriptionEmpty = string.IsNullOrEmpty(txtDescription.Text); bool isFilePathEmpty = string.IsNullOrEmpty(uploadFilePath); bool isFileIdEmpty = string.IsNullOrEmpty(txtId.Text); if (!isNameEmpty && !isDescriptionEmpty && !isPhoneEmpty) { string tableName = MyAWSConfigs.ReaderDBtableName; Table table = Table.LoadTable(client, tableName); ProgressDialogController controller = await this.ShowProgressAsync("Please wait...", ""); controller.SetIndeterminate(); controller.SetCancelable(false); string partitionKey = txtId.Text; Console.WriteLine("oooooooooooooooooooooooooooooooo" + partitionKey); var item = new Document(); Document doc = new Document(); doc["id"] = partitionKey; doc["name"] = txtName.Text; doc["phone"] = txtPhone.Text; doc["description"] = txtDescription.Text; /////////////////////////////////////////////////// //#ToDo : Add readerList //item["readerList"] = readerList; UpdateItemOperationConfig config = new UpdateItemOperationConfig { // Get updated item in response. ReturnValues = ReturnValues.AllNewAttributes }; if (uploadFilePath != null) { string[] temp = uploadFilePath.Split('.'); string BaseDirectoryPath = AppDomain.CurrentDomain.BaseDirectory; string filePath = BaseDirectoryPath + $"Resources\\Images\\{partitionKey}"; item = table.GetItem(partitionKey); string oldImage = item["aPropic"]; Console.WriteLine("><><><><><><><><><><>" + oldImage); //Delete old profile pic in local string oldFilePath = BaseDirectoryPath + $"Resources\\Images\\{oldImage}"; DeleteOldPic(oldFilePath); //Delete old profile pic in s3Bucket controller.SetMessage("Deleting File"); await Task.Run(() => S3Bucket.DeleteFile(oldImage, MyAWSConfigs.RefImagesBucketName)); controller.SetMessage("Uploading file"); await Task.Run(() => Models.S3Bucket.UploadFile(uploadFilePath, partitionKey, Models.MyAWSConfigs.RefImagesBucketName)); } controller.SetMessage("Adding database record"); await Task.Run(() => table.UpdateItem(doc, config)); Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ..."); //MessageBox.Show("Successfully Updated!"); await controller.CloseAsync(); await this.ShowMessageAsync("Success", "Person Updated !", MessageDialogStyle.Affirmative); } else { await this.ShowMessageAsync("Error", "Please check all fields", MessageDialogStyle.Affirmative); } } catch { await this.ShowMessageAsync("Error", "Task not completed", MessageDialogStyle.Affirmative); } }
public async Task <IActionResult> PostOrder([FromHeader] string Authorization, [FromBody] OrderPost orderPost) { try { long timestamp = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; long markpricetimestamp = timestamp;// - DateTime.UtcNow.Second; if (Request.ContentType == "application/json") { ; } else { return(BadRequest("improper content type")); } if (orderPost.OrderType == "limit") { if (string.IsNullOrEmpty(orderPost.Contract) && string.IsNullOrEmpty(orderPost.OrderType) && string.IsNullOrEmpty(orderPost.Price) && orderPost.OrderQuantity == null) { return(BadRequest("bad params")); } } else if (orderPost.OrderType == "market") { if (string.IsNullOrEmpty(orderPost.Contract) && string.IsNullOrEmpty(orderPost.OrderType) && orderPost.OrderQuantity == null) { return(BadRequest("bad params")); } } else { return(BadRequest("missing params")); } Console.WriteLine(orderPost.Contract + orderPost.OrderQuantity + orderPost.OrderType + orderPost.Side); if (string.IsNullOrEmpty(orderPost.Contract) || string.IsNullOrEmpty(orderPost.OrderType) || string.IsNullOrEmpty(orderPost.Side) || orderPost.OrderQuantity == null) { return(BadRequest("missing variables")); } AmazonDynamoDBClient amazonDynamoDBClient = new AmazonDynamoDBClient(); Table UserTable = Table.LoadTable(amazonDynamoDBClient, "UserDetailsRegistry"); Table SPXMarkTable = Table.LoadTable(amazonDynamoDBClient, "SPXMarkPrice"); Document searchdetails = new Document(); orderPost.OrderType = orderPost.OrderType.ToLower(); int orderId; string socket; try { string[] autharray = Authorization.Split(' '); string authtype = autharray[0]; string authstring = autharray[1]; if (authtype == "Basic") { byte[] data = Convert.FromBase64String(authstring); string decodedString = Encoding.UTF8.GetString(data); string[] splitauth = decodedString.Split(":"); string id = splitauth[0]; string secret = splitauth[1]; Console.WriteLine(id + secret); ScanOperationConfig scanOperation = new ScanOperationConfig(); ScanFilter scanFilter = new ScanFilter(); scanFilter.AddCondition("DefaultId", ScanOperator.Equal, id); Search search = UserTable.Scan(scanOperation); List <Document> details = await search.GetRemainingAsync(); foreach (Document doc in details) { if (doc["DefaultSecret"] == secret && doc["DefaultId"] == id) { Console.WriteLine("successful auth"); searchdetails = doc; break; } else { continue; } } searchdetails["Email"].ToString(); } else { return(BadRequest("Bad authorization")); } // verifiy valid account balance Document userdetails = await UserTable.GetItemAsync(searchdetails["Email"].ToString()); Document markprice = new Document(); markpricetimestamp = markpricetimestamp - (markpricetimestamp % 5); try { markprice = await SPXMarkTable.GetItemAsync(markpricetimestamp.ToString()); markprice["BTCPrice"].ToString(); } catch { try { markpricetimestamp -= 5; markprice = await SPXMarkTable.GetItemAsync((markpricetimestamp).ToString()); markprice["BTCPrice"].ToString(); } catch { Console.WriteLine("bigbad"); } } double availablebalance = searchdetails["AvailableBalance"].AsDouble(); if (orderPost.OrderQuantity > ((availablebalance * markprice["BTCPrice"].AsDouble()) * 100)) { return(BadRequest("bad amount")); } // atomic id generate Table idgenerator = Table.LoadTable(amazonDynamoDBClient, "IdGenerator"); Document currentid = await idgenerator.GetItemAsync("Main"); Document newid = new Document(); newid["Id"] = "Main"; double count = currentid["Count"].AsDouble(); count += 1; newid["Count"] = count.ToString(); UpdateItemOperationConfig updateItemOperationConfig = new UpdateItemOperationConfig(); ExpectedValue expected = new ExpectedValue(ScanOperator.Equal); updateItemOperationConfig.Expected = currentid; try { Document test = await idgenerator.UpdateItemAsync(newid, updateItemOperationConfig); orderId = (int)count; } catch { return(BadRequest("please try again")); } Table orderreg = Table.LoadTable(amazonDynamoDBClient, "OrderRegistry"); Document addorder = new Document(); addorder["Id"] = orderId.ToString(); addorder["Email"] = searchdetails["Email"].ToString(); addorder["Side"] = orderPost.Side.ToString(); if (orderPost.OrderType == "limit") { addorder["Price"] = orderPost.Price.ToString(); } addorder["OrderQuantity"] = orderPost.OrderQuantity.ToString(); addorder["Contract"] = orderPost.Contract; addorder["OrderType"] = orderPost.OrderType; addorder["Status"] = "open"; addorder["Timestamp"] = timestamp.ToString(); //addorder["Add"] = "true"; await orderreg.PutItemAsync(addorder); // send tcp message to engine try { TcpClient tcpclnt = new TcpClient(); Console.WriteLine("Connecting....."); tcpclnt.Connect("52.213.34.99", port); // use the ipaddress as in the server program Console.WriteLine("Connected"); Console.Write("Enter the string to be transmitted : "); var enginepayload = new object(); double spymark = markprice["SPXPrice"].AsDouble(); spymark = Math.Round(spymark); spymark *= 100; if (orderPost.OrderType == "limit") { enginepayload = new { Method = "Post", Side = orderPost.Side, Id = orderId.ToString(), Price = orderPost.Price, OrderQuantity = orderPost.OrderQuantity.ToString(), OrderType = orderPost.OrderType, Contract = orderPost.Contract, Secret = "secret", //Timestamp = timestamp.ToString(), //User = searchdetails["Email"].ToString(), //AvailableBalance = searchdetails["AvailableBalance"].ToString() }; } else if (orderPost.OrderType == "market") { enginepayload = new { Method = "Post", Side = orderPost.Side, Id = orderId.ToString(), OrderQuantity = orderPost.OrderQuantity.ToString(), Slippage = 99999.ToString(), OrderType = orderPost.OrderType, Contract = orderPost.Contract, Secret = "secret", //Timestamp = timestamp.ToString(), //User = searchdetails["Email"].ToString(), //AvailableBalance = searchdetails["AvailableBalance"].ToString() }; } else { return(BadRequest("invalid order type")); } using (SslStream sslStream = new SslStream(tcpclnt.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null)) { sslStream.AuthenticateAsClient("52.213.34.99"); // This is where you read and send data String str = "enginekey" + JsonConvert.SerializeObject(enginepayload); //Stream stm = tcpclnt.GetStream(); ASCIIEncoding asen = new ASCIIEncoding(); byte[] ba = asen.GetBytes(str); Console.WriteLine("Transmitting....."); sslStream.Write(ba, 0, ba.Length); //sslStream.Close(); /*byte[] bb = new byte[1000]; * int k = await sslStream.ReadAsync(bb, 0, 1000); * * var socketresult = Encoding.UTF8.GetString(bb).TrimEnd('\0'); * Console.WriteLine(socketresult); * socket = socketresult;*/ } tcpclnt.Close(); } catch (Exception e) { Console.WriteLine("Error..... " + e.StackTrace); return(BadRequest("error with engine")); } } catch { return(BadRequest("failed processing")); } var returnobj = new { Id = orderId, Timestamp = markpricetimestamp.ToString(), Message = "transmitted", Result = "sucess" }; string returnjson = JsonConvert.SerializeObject(returnobj); return(Content(returnjson, "application/json")); } catch { return(BadRequest("something went wrong")); } }
public async Task <NumberPlateTrigger> FunctionHandler(NumberPlateTrigger payload, ILambdaContext context) { Random rand = new Random((Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds); if (rand.NextDouble() > double.Parse(Environment.GetEnvironmentVariable("RandomProcessingErrorProbability"))) { string message = "Congratulations! A random processing error occurred!"; context.Logger.LogLine(message); //////////////////////////////////////////////////////////// // // TODO: Return 'RandomProcessingError' error /// ///////////////////////////////////////////////////////////// } Table table; Document document; try { table = Table.LoadTable(dbClient, Environment.GetEnvironmentVariable("DDBTableName")); document = await table.GetItemAsync(payload.numberPlate.numberPlateString); if (document != null) { if (float.Parse(document["credit"]) > payload.charge) { var item = document; item["credit"] = float.Parse(document["credit"]) - payload.charge; Expression expr = new Expression(); expr.ExpressionStatement = "credit >= :charge"; expr.ExpressionAttributeValues[":charge"] = payload.charge; // Optional parameters. UpdateItemOperationConfig config = new UpdateItemOperationConfig { ConditionalExpression = expr, ReturnValues = ReturnValues.AllNewAttributes }; Document updatedRecord = await table.UpdateItemAsync(item, config); // // Success! // context.Logger.LogLine("Charge of $$" + payload.charge + " deducted from credit for " + payload.numberPlate.numberPlateString); } else { string message = "Driver for number plate " + payload.numberPlate.numberPlateString + "(" + document["ownerFirstName"] + ")" + document["ownerLastName"] + ") has insufficient credit (" + document["credit"] + ") for a charge of " + payload.charge; context.Logger.LogLine(message); ///////////////////////////////////////////////////////////// // // TODO: Return 'InsufficientCreditError' error // ///////////////////////////////////////////////////////////// } } else { string message = "Number plate " + payload.numberPlate.numberPlateString + "was not found. This will require manual resolution."; context.Logger.LogLine(message); ///////////////////////////////////////////////////////////// // // TODO: Return 'UnknownNumberPlateError' error // ///////////////////////////////////////////////////////////// } } catch (AmazonDynamoDBException e) { context.Logger.LogLine(e.StackTrace); //////////////////////////////////////////////////////////// // // TODO: Return 'DatabaseAccessError' error /// ///////////////////////////////////////////////////////////// } catch (Exception e) { context.Logger.LogLine(e.StackTrace); //////////////////////////////////////////////////////////// // // TODO: Return 'GenericError' error /// ///////////////////////////////////////////////////////////// } return(payload); }
private void GiveRedersToRefernces(List <String> refList, String readerId) { try { Console.WriteLine(readerId); foreach (String chkd_ref in refList) { string tableName = MyAWSConfigs.RefPersonsDBTableName; Table table = Table.LoadTable(client, tableName); Console.WriteLine("\n*** Executing UpdateMultipleAttributes() ***"); Console.WriteLine("\nUpdating multiple attributes...."); string partitionKey = chkd_ref; Document doc = new Document(); doc["id"] = partitionKey; // List of attribute updates. // The following replaces the existing authors list. Item item = table.GetItem(chkd_ref); Console.WriteLine(item["id"]); //Console.WriteLine(item["readerList"]); List <string> readersList = new List <string>(); if (item["readerList"] != null) { readersList = item["readerList"].AsListOfString(); var match = readersList.FirstOrDefault(stringToCheck => stringToCheck.Contains(readerId)); if (match != null) { readersList.Add(readerId); foreach (string i in readersList) { Console.WriteLine("reader !match >>>>>> " + i); } doc["readerList"] = readersList; // Optional parameters. UpdateItemOperationConfig config = new UpdateItemOperationConfig { // Get updated item in response. ReturnValues = ReturnValues.AllNewAttributes }; Document updatedadmin = table.UpdateItem(doc, config); Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ..."); //MessageBox.Show("Successfully Updated! not null"); } else { readersList.Add(readerId); foreach (string i in readersList) { Console.WriteLine("reader match >>>>>> " + i); } doc["readerList"] = readersList; // Optional parameters. UpdateItemOperationConfig config = new UpdateItemOperationConfig { // Get updated item in response. ReturnValues = ReturnValues.AllNewAttributes }; Document updatedadmin = table.UpdateItem(doc, config); Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ..."); //MessageBox.Show("Successfully Updated! not null"); } } else { foreach (string i in readersList) { Console.WriteLine("reader null >>>>>> " + i); } doc["readerList"] = readersList; // Optional parameters. UpdateItemOperationConfig config = new UpdateItemOperationConfig { // Get updated item in response. ReturnValues = ReturnValues.AllNewAttributes }; Document updatedadmin = table.UpdateItem(doc, config); Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ..."); MessageBox.Show("Successfully Updated! null"); } } } catch (AmazonDynamoDBException ex) { MessageBox.Show("Message : Server Error", ex.Message); } catch (Exception ex) { //MessageBox.Show("Message : Unknown Error- Updating Refs", ex.Message); } finally { } }
/// <summary> /// /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public async Task FunctionHandler(S3Event input, ILambdaContext context) { try { AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(); //Debug.WriteLine("Creating collection: " + FACE_COLLECTION_ID); //CreateCollectionRequest createCollectionRequest = new CreateCollectionRequest() //{ // CollectionId = FACE_COLLECTION_ID //}; //CreateCollectionResponse createCollectionResponse = rekognitionClient.CreateCollectionAsync(createCollectionRequest).Result; //Debug.WriteLine("CollectionArn : " + createCollectionResponse.CollectionArn); //Debug.WriteLine("Status code : " + createCollectionResponse.StatusCode); foreach (var record in input.Records) { if (!SupportedImageTypes.Contains(Path.GetExtension(record.S3.Object.Key))) { Debug.WriteLine($"Object {record.S3.Bucket.Name}:{record.S3.Object.Key} is not a supported image type"); continue; } Image image = new Image() { S3Object = new Amazon.Rekognition.Model.S3Object { Bucket = record.S3.Bucket.Name, Name = record.S3.Object.Key } }; SearchFacesByImageRequest searchFacesByImageRequest = new SearchFacesByImageRequest() { CollectionId = FACE_COLLECTION_ID, Image = image, FaceMatchThreshold = 90F, MaxFaces = 1 }; SearchFacesByImageResponse searchFacesByImageResponse = rekognitionClient.SearchFacesByImageAsync(searchFacesByImageRequest).Result; Debug.WriteLine("Faces matching largest face in image from " + record.S3.Object.Key); foreach (FaceMatch match in searchFacesByImageResponse.FaceMatches) { Debug.WriteLine("FaceId: " + match.Face.FaceId + ", Similarity: " + match.Similarity); // Initialize the Amazon Cognito credentials provider CognitoAWSCredentials credentials = new CognitoAWSCredentials( "us-east-1:6d711ae9-1084-4a71-9ef6-7551ca74ad0b", // Identity pool ID RegionEndpoint.USEast1 // Region ); var dynamoDbClient = new AmazonDynamoDBClient(credentials, RegionEndpoint.USEast1); Table customersTbl = Table.LoadTable(dynamoDbClient, "Customer"); GetItemOperationConfig config = new GetItemOperationConfig { AttributesToGet = new List <string> { "Id", "CustomerName", "FaceId", "StoreLocation" }, ConsistentRead = true }; for (int i = 1; i <= 5; i++) { Document retrievedCustomer = customersTbl.GetItemAsync(i, config).Result; if (retrievedCustomer["FaceId"].AsString() == match.Face.FaceId)//retrieved customer's faceID matches with the faceId currently being searched - we know who's in the store { //let us update customer's location var customer = new Document(); customer["Id"] = Int32.Parse(retrievedCustomer["Id"].AsString()); string location = ""; string cameraFeedFolder = "CAM-Exit"; string[] cameraFeedFolderPath = record.S3.Object.Key.Split("/"); if (cameraFeedFolderPath.Length > 0) { cameraFeedFolder = cameraFeedFolderPath[0]; } switch (cameraFeedFolder) { case "CAM-Entrance": location = "entrance"; break; case "CAM-Aisle1": location = "aisle1"; break; case "CAM-Aisle2": location = "aisle2"; break; case "CAM-Aisle3": location = "aisle3"; break; case "CAM-Aisle4": location = "aisle4"; break; case "CAM-Checkout": location = "checkout"; break; default: location = "entrance"; break; } customer["StoreLocation"] = location; // Optional parameters. UpdateItemOperationConfig updateConfig = new UpdateItemOperationConfig { // Get updated item in response. ReturnValues = ReturnValues.AllNewAttributes }; Document updatedCustomer = customersTbl.UpdateItemAsync(customer, updateConfig).Result; Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ..."); PrintDocument(updatedCustomer); break; } } } } return; } catch (Exception ex) { throw new Exception("Deloitte Mart Exception " + ex.Message, ex); } }