Exemple #1
0
        public async Task <UpdateItemResponse> UpdateItem(UpdateItemRequest item)
        {
            string url         = $"/item/update";
            var    requestBody = await Task.Run(() => JsonConvert.SerializeObject(item));

            using (HttpClient httpClient = new HttpClient())
            {
                UpdateItemResponse data = new UpdateItemResponse();
                try
                {
                    var authHeader = new AuthenticationHeaderValue("Bearer", await SecureStorage.GetAsync("auth_token"));
                    httpClient.DefaultRequestHeaders.Authorization = authHeader;
                    httpClient.BaseAddress = new Uri(Constants.BaseUrl);
                    StringContent       content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                    HttpResponseMessage result  = await httpClient.PostAsync(url, content);

                    string response = await result.Content.ReadAsStringAsync();

                    data = JsonConvert.DeserializeObject <UpdateItemResponse>(response);

                    if (result.IsSuccessStatusCode && result.StatusCode == HttpStatusCode.OK)
                    {
                        return(data);
                    }

                    return(null);
                }
                catch (Exception exp)
                {
                    return(null);
                }
            }
        }
        public static UpdateItemResponse UpdateItem(AmazonDynamoDBClient dynamoDBClient, UpdateItemRequest requestUpdate)
        {
            Debug.WriteLine(String.Format("RUNNING SOLUTION CODE: {0}! Follow the steps in the lab guide to replace this method with your own implementation.\n", "UpdateItem"));
            UpdateItemResponse response = dynamoDBClient.UpdateItem(requestUpdate);

            return(response);
        }
Exemple #3
0
        public async Task <UpdatePointResult> UpdatePointAsync(UpdatePointRequest updatePointRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (updatePointRequest == null)
            {
                throw new ArgumentNullException("updatePointRequest");
            }

            var geohash = S2Manager.GenerateGeohash(updatePointRequest.GeoPoint);
            var hashKey = S2Manager.GenerateHashKey(geohash, _config.HashKeyLength);

            var updateItemRequest = updatePointRequest.UpdateItemRequest;

            updateItemRequest.TableName = _config.TableName;

            var hashKeyValue = new AttributeValue
            {
                N = hashKey.ToString(CultureInfo.InvariantCulture)
            };

            updateItemRequest.Key[_config.HashKeyAttributeName]  = hashKeyValue;
            updateItemRequest.Key[_config.RangeKeyAttributeName] = updatePointRequest.RangeKeyValue;

            // Geohash and geoJson cannot be updated.
            updateItemRequest.AttributeUpdates.Remove(_config.GeohashAttributeName);
            updateItemRequest.AttributeUpdates.Remove(_config.GeoJsonAttributeName);

            UpdateItemResponse updateItemResult = await _config.DynamoDBClient.UpdateItemAsync(updateItemRequest, cancellationToken).ConfigureAwait(false);

            var updatePointResult = new UpdatePointResult(updateItemResult);

            return(updatePointResult);
        }
Exemple #4
0
        public UpdateItemResponse Handle(UpdateItemRequest request)
        {
            var response = new UpdateItemResponse();

            response.Errors = Validate(request);

            if (response.HasErrors)
            {
                return(response);
            }
            try
            {
                var item = _itemRepository.Get(request.Item.Id);

                if (item == null)
                {
                    response.Errors.Add(new ErrorStatus("ITEM_NOT_FOUND"));
                    return(response);
                }

                UpdateItemObject(item, request.Item);

                _itemRepository.Update(item);

                return(response);
            }
            catch (Exception ex)
            {
                response.Errors.Add(new ErrorStatus("BAD_REQUEST"));

                return(response);
            }
        }
        /*--------------------------------------------------------------------------
         *                             UpdatingMovie_async
         *--------------------------------------------------------------------------*/
        public static async Task <bool> UpdatingMovie_async(UpdateItemRequest updateRequest, bool report)
        {
            UpdateItemResponse updateResponse = null;

            operationSucceeded = false;
            operationFailed    = false;
            if (report)
            {
                Console.WriteLine("  -- Trying to update a movie item...");
                updateRequest.ReturnValues = "ALL_NEW";
            }

            try
            {
                updateResponse = await client.UpdateItemAsync(updateRequest);

                Console.WriteLine("     -- SUCCEEDED in updating the movie item!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("     -- FAILED to update the movie item, because:\n       {0}.", ex.Message);
                if (updateResponse != null)
                {
                    Console.WriteLine("     -- The status code was " + updateResponse.HttpStatusCode.ToString( ));
                }
                operationFailed = true; return(false);
            }
            if (report)
            {
                Console.WriteLine("     Here is the updated movie informtion:");
                Console.WriteLine(movieAttributesToJson(updateResponse.Attributes));
            }
            operationSucceeded = true;
            return(true);
        }
Exemple #6
0
        public async static Task <UpdateItemResponse> MainUpdateAsync(SongDescription UpdateSong)
        {
            Dictionary <string, AttributeValue> key = new Dictionary <string, AttributeValue>
            {
                { "Artist", new AttributeValue {
                      S = UpdateSong.Artist
                  } },
                { "SongTitle", new AttributeValue {
                      S = UpdateSong.SongTitle
                  } },
            };
            Dictionary <string, AttributeValueUpdate> updates = new Dictionary <string, AttributeValueUpdate>();

            updates["Duration"] = new AttributeValueUpdate()
            {
                Action = AttributeAction.PUT,
                Value  = new AttributeValue {
                    S = UpdateSong.Duration
                }
            };
            var request = new UpdateItemRequest
            {
                TableName        = tableName,
                Key              = key,
                AttributeUpdates = updates,
                ReturnValues     = "UPDATED_NEW"
            };

            UpdateItemResponse r = await client.UpdateItemAsync(request);

            return(r);
        }
        // Not used for now
        public async Task <int> IncrementNumberOfSubscribers(string tag, int incrBy)
        {
            var request = new UpdateItemRequest
            {
                TableName = TABLENAME,
                Key       = new Dictionary <string, AttributeValue>()
                {
                    { "Tag", new AttributeValue {
                          S = tag
                      } }
                },
                ExpressionAttributeNames = new Dictionary <string, string>()
                {
                    { "#Q", "NumberOfSubscribers" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>()
                {
                    { ":incr", new AttributeValue {
                          N = incrBy.ToString()
                      } }
                },
                UpdateExpression = "SET #Q = #Q + :incr",
                ReturnValues     = ReturnValue.UPDATED_NEW,
            };

            UpdateItemResponse response = await dynamoclient.UpdateItemAsync(request);

            return(int.Parse(response.Attributes["NumberOfSubscribers"].N));
        }
Exemple #8
0
        public static string ConvertToJSON(UpdateItemResponse response)
        {
            Debug.WriteLine(String.Format("RUNNING SOLUTION CODE: {0}! Follow the steps in the lab guide to replace this method with your own implementation.\n", "ConvertToJSON"));
            string json = JsonConvert.SerializeObject(response);

            return(json);
        }
Exemple #9
0
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            UpdateItemResponse response = new UpdateItemResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.TestExpression("Attributes", targetDepth))
                {
                    var unmarshaller = new DictionaryUnmarshaller <string, AttributeValue, StringUnmarshaller, AttributeValueUnmarshaller>(StringUnmarshaller.Instance, AttributeValueUnmarshaller.Instance);
                    response.Attributes = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("ConsumedCapacity", targetDepth))
                {
                    var unmarshaller = ConsumedCapacityUnmarshaller.Instance;
                    response.ConsumedCapacity = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("ItemCollectionMetrics", targetDepth))
                {
                    var unmarshaller = ItemCollectionMetricsUnmarshaller.Instance;
                    response.ItemCollectionMetrics = unmarshaller.Unmarshall(context);
                    continue;
                }
            }

            return(response);
        }
 public UpdatePointResult(UpdateItemResponse updateItemResult)
 {
     if (updateItemResult == null)
     {
         throw new ArgumentNullException("updateItemResult");
     }
     UpdateItemResult = updateItemResult;
 }
        public async Task TestColsAddAsync()
        {
            string id = Guid.NewGuid().ToString();

            Console.WriteLine(id);

            Dictionary <string, AttributeValue> keyItem = new Dictionary <string, AttributeValue>
            {
                { "Id", new AttributeValue {
                      S = id
                  } }
            };

            PutItemResponse putResponse = await DDBClient.PutItemAsync(TableName, keyItem);

            Assert.AreEqual(putResponse.HttpStatusCode, HttpStatusCode.OK);


            Dictionary <string, AttributeValueUpdate> updateItem = new Dictionary <string, AttributeValueUpdate>
            {
                { "Col1", new AttributeValueUpdate {
                      Action = AttributeAction.PUT, Value = new AttributeValue {
                          N = "0"
                      }
                  } }
            };

            UpdateItemResponse updateResponse = await DDBClient.UpdateItemAsync(TableName, keyItem, updateItem);

            Assert.AreEqual(updateResponse.HttpStatusCode, HttpStatusCode.OK);

            Dictionary <string, AttributeValueUpdate> updateItem2 = new Dictionary <string, AttributeValueUpdate>
            {
                { "Col1", new AttributeValueUpdate {
                      Action = AttributeAction.PUT, Value = new AttributeValue {
                          N = "1"
                      }
                  } }
            };

            UpdateItemResponse updateResponse2 = await DDBClient.UpdateItemAsync(TableName, keyItem, updateItem2);

            Assert.AreEqual(updateResponse2.HttpStatusCode, HttpStatusCode.OK);


            GetItemResponse getItemResponse = await DDBClient.GetItemAsync(TableName, keyItem);

            Assert.AreEqual(getItemResponse.HttpStatusCode, HttpStatusCode.OK);
            bool isId = getItemResponse.Item.TryGetValue("Id", out AttributeValue id2);

            Assert.IsTrue(isId);
            Assert.AreEqual(id, id2.S);

            bool isCol1 = getItemResponse.Item.TryGetValue("Col1", out AttributeValue co1);

            Assert.IsTrue(isCol1);
            Assert.AreEqual("1", co1.N);
        }
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            UpdateItemResponse response = new UpdateItemResponse();

            context.Read();

            UnmarshallResult(context, response);
            return(response);
        }
Exemple #13
0
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            UpdateItemResponse response = new UpdateItemResponse();

            context.Read();
            response.UpdateItemResult = UpdateItemResultUnmarshaller.GetInstance().Unmarshall(context);

            return(response);
        }
Exemple #14
0
        public UpdateItemResponse GetFakeUpdateItemResponse_UPC_12DigitNumber()
        {
            var fake = new UpdateItemResponse()
            {
                Message = $"Record with Id: 1 sucessfully updated."
            };

            return(fake);
        }
        static void Main(string[] args)
        {
            // Get an AmazonDynamoDBClient for the local database
            AmazonDynamoDBClient client = GetLocalClient();

            if (client == null)
            {
                PauseForDebugWindow();
                return;
            }

            // Create an UpdateItemRequest to modify two existing nested attributes
            // and add a new one
            UpdateItemRequest updateRequest = new UpdateItemRequest()
            {
                TableName = "Movies",
                Key       = new Dictionary <string, AttributeValue>
                {
                    { "year", new AttributeValue {
                          N = "2015"
                      } },
                    { "title", new AttributeValue {
                          S = "The Big New Movie"
                      } }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":inc", new AttributeValue {
                          N = "1"
                      } }
                },
                UpdateExpression = "SET info.rating = info.rating + :inc",
                ReturnValues     = "UPDATED_NEW"
            };

            // Use AmazonDynamoDBClient.UpdateItem to update the specified attributes
            UpdateItemResponse uir = null;

            try
            {
                uir = client.UpdateItem(updateRequest);
            }
            catch (Exception ex)
            {
                Console.WriteLine("\nError: UpdateItem failed, because " + ex.Message);
                if (uir != null)
                {
                    Console.WriteLine("    Status code was: " + uir.HttpStatusCode.ToString());
                }
                PauseForDebugWindow();
                return;
            }

            // Get the item from the table and display it to validate that the update succeeded
            DisplayMovieItem(client, "2015", "The Big New Movie");
        }
        private static void UnmarshallResult(JsonUnmarshallerContext context, UpdateItemResponse response)
        {
            int originalDepth = context.CurrentDepth;
            int targetDepth   = originalDepth + 1;

            while (context.Read())
            {
                if (context.TestExpression("Attributes", targetDepth))
                {
                    context.Read();
                    response.Attributes = new Dictionary <String, AttributeValue>();
                    if (context.CurrentTokenType == JsonToken.Null)
                    {
                        continue;
                    }
                    KeyValueUnmarshaller <string, AttributeValue, StringUnmarshaller, AttributeValueUnmarshaller> unmarshaller = new KeyValueUnmarshaller <string, AttributeValue, StringUnmarshaller, AttributeValueUnmarshaller>(StringUnmarshaller.GetInstance(), AttributeValueUnmarshaller.GetInstance());
                    while (context.Read())
                    {
                        JsonToken token = context.CurrentTokenType;
                        if (token == JsonToken.ArrayStart || token == JsonToken.ObjectStart)
                        {
                            continue;
                        }
                        if (token == JsonToken.ArrayEnd || token == JsonToken.ObjectEnd)
                        {
                            break;
                        }
                        KeyValuePair <string, AttributeValue> kvp = unmarshaller.Unmarshall(context);
                        response.Attributes.Add(kvp.Key, kvp.Value);
                    }
                    continue;
                }

                if (context.TestExpression("ConsumedCapacity", targetDepth))
                {
                    context.Read();
                    response.ConsumedCapacity = ConsumedCapacityUnmarshaller.GetInstance().Unmarshall(context);
                    continue;
                }

                if (context.TestExpression("ItemCollectionMetrics", targetDepth))
                {
                    context.Read();
                    response.ItemCollectionMetrics = ItemCollectionMetricsUnmarshaller.GetInstance().Unmarshall(context);
                    continue;
                }

                if (context.CurrentDepth <= originalDepth)
                {
                    return;
                }
            }

            return;
        }
        /**
         * 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);
        }
        public async Task <IActionResult> Update([FromBody] Person p)
        {
            //Define key
            Dictionary <string, AttributeValue> key = new Dictionary <string, AttributeValue>
            {
                { "Name", new AttributeValue {
                      S = p.Name
                  } }
            };

            // Define attribute updates
            Dictionary <string, AttributeValueUpdate> updates = new Dictionary <string, AttributeValueUpdate> ();

            updates["IsHome"] = new AttributeValueUpdate
            {
                Action = AttributeAction.PUT,
                Value  = new AttributeValue {
                    BOOL = p.IsHome
                }
            };
            updates["Timestamp"] = new AttributeValueUpdate
            {
                Action = AttributeAction.PUT,
                Value  = new AttributeValue
                {
                    S = DateTime.Now.ToString()
                }
            };

            UpdateItemRequest req = new UpdateItemRequest()
            {
                TableName        = TABLE_NAME,
                AttributeUpdates = updates,
                Key = key
            };
            //await response from the dynamodb client
            UpdateItemResponse resp = await _dynamoClient.UpdateItemAsync(req);

            if (resp.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                return(Ok());
            }
            else
            {
                return(NotFound());
            }
        }
Exemple #19
0
        public async Task UpdateEmail(string countryId, string name, string id, string newPhoneToInsert, string emailToUpdate)
        {
            UpdateItemResponse updateItemResponse = await _dynamoDBClient.UpdateItemAsync(new UpdateItemRequest
            {
                TableName = _tableName,
                Key       =
                {
                    { "CountryId", new AttributeValue(countryId) },
                    { "Name",      new AttributeValue(name)      }
                },
                UpdateExpression          = "ADD Phones :newPhone SET Email = :email",
                ConditionExpression       = "Id = :id",
                ExpressionAttributeValues =
                {
                    {
                        ":id", new AttributeValue(id)
                    },
                    {
                        ":newPhone", new AttributeValue{
                            SS = new List <string>{
                                newPhoneToInsert
                            }
                        }
                    },
                    {
                        ":email", new AttributeValue(emailToUpdate)
                    }
                }
            });


            if (updateItemResponse.HttpStatusCode == HttpStatusCode.OK ||
                updateItemResponse.HttpStatusCode == HttpStatusCode.Accepted)
            {
                Console.WriteLine("Fields updated successfully");
            }
            else
            {
                Console.WriteLine(updateItemResponse.HttpStatusCode);
            }
        }
Exemple #20
0
        public void UpdateItem(int id)
        {
            //Update Items
            UpdateItemResponse updateClient = null;

            if (resultSet.Count > 0)
            {
                for (int i = 0; i < resultSet.Count; i++)
                {
                    string attributeValue = "";

                    attributeValue = doc[i]["Id"].AsString();
                    //var value = resultSet.Where(resultSet[0].Keys.Count>0).Select(x => x.Values);
                    UpdateItemRequest updateRequest = new UpdateItemRequest()
                    {
                        TableName = "Student",
                        Key       = new Dictionary <string, AttributeValue> {
                            { "Id", new AttributeValue {
                                  N = attributeValue
                              } }
                        },
                        ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                        {
                            { ":r", new AttributeValue {
                                  N = "10"
                              } },
                            { ":n", new AttributeValue {
                                  N = "1"
                              } }
                        },
                        ConditionExpression = "Marks >= :n",
                        UpdateExpression    = "SET Marks = :r",
                        ReturnValues        = "UPDATED_NEW"
                    };

                    updateClient = client.UpdateItem(updateRequest);
                }
            }
            successMessage = updateClient.HttpStatusCode == HttpStatusCode.OK ? "Item Updated " : "Error Occured While Updating";
        }
        public async Task TestColsLargeAmountsAddAsync()
        {
            string id = Guid.NewGuid().ToString();

            Console.WriteLine(id);

            Dictionary <string, AttributeValue> keyItem = new Dictionary <string, AttributeValue>
            {
                { "Id", new AttributeValue {
                      S = id
                  } }
            };

            PutItemResponse putResponse = await DDBClient.PutItemAsync(TableName, keyItem);

            Assert.AreEqual(putResponse.HttpStatusCode, HttpStatusCode.OK);

            int colSize = 500;
            Dictionary <string, AttributeValueUpdate> updateItem = new Dictionary <string, AttributeValueUpdate>
            {
                { "ColSize", new AttributeValueUpdate {
                      Action = AttributeAction.PUT, Value = new AttributeValue {
                          N = $"{colSize}"
                      }
                  } }
            };

            Enumerable.Range(1, colSize).ToList().ForEach(i =>
            {
                updateItem.Add($"Col{i}", new AttributeValueUpdate {
                    Action = AttributeAction.PUT, Value = new AttributeValue {
                        N = "0"
                    }
                });
            });

            UpdateItemResponse updateResponse = await DDBClient.UpdateItemAsync(TableName, keyItem, updateItem);

            Assert.AreEqual(updateResponse.HttpStatusCode, HttpStatusCode.OK);
        }
Exemple #22
0
        private static void UpdateItemWithLink(string patientId, string reportUrl)
        {
            Debug.WriteLine("Updating item patientId: {0}, reportURL: {1}", patientId, reportUrl);

            UpdateItemRequest requestUpdate = new UpdateItemRequest
            {
                TableName = InfectionsTableName,
                Key       = new Dictionary <string, AttributeValue>()
                {
                    { "PatientID", new AttributeValue {
                          S = patientId
                      } }
                },
                ExpressionAttributeNames = new Dictionary <string, string>()
                {
                    { "#purl", "PatientReportUrl" },
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>()
                {
                    { ":val1", new AttributeValue {
                          S = reportUrl
                      } },
                },
                // This expression does the following:
                // Adds a new attribute to the item
                UpdateExpression = "SET #purl = :val1"
            };

            UpdateItemResponse responseUpdate = UpdateItem(requestUpdate);

            Debug.WriteLine("Printing item after adding attribute:");

            string jsonDisplayText = ConvertToJSON(responseUpdate);

            Debug.WriteLine("Display item.");
            Debug.WriteLine(jsonDisplayText);
        }
        private static void UpdateItemWithLink(string customerId, string reportUrl)
        {
            Debug.WriteLine("Updating item customerId: {0}, reportURL: {1}", customerId, reportUrl);

            UpdateItemRequest requestUpdate = new UpdateItemRequest
            {
                TableName = ReservationsTableName,
                Key       = new Dictionary <string, AttributeValue>()
                {
                    { "CustomerID", new AttributeValue {
                          S = customerId
                      } }
                },
                ExpressionAttributeNames = new Dictionary <string, string>()
                {
                    { "#curl", "CustomerReportUrl" },
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>()
                {
                    { ":val1", new AttributeValue {
                          S = reportUrl
                      } },
                },
                // This expression does the following:
                // Adds a new attribute to the item
                UpdateExpression = "SET #curl = :val1"
            };

            UpdateItemResponse responseUpdate = UpdateItem(requestUpdate);

            Debug.WriteLine("Printing item after adding attribute:");

            string jsonDisplayText = JsonConvert.SerializeObject(responseUpdate);

            Debug.WriteLine("Display item.");
            Debug.WriteLine(jsonDisplayText);
        }
Exemple #24
0
        public async Task <UpdateItemResponse> Put([FromBody] UpdateItemRequest request, long id = 0)
        {
            UpdateItemResponse updateItemResponse;
            var pattern = @"^(?:\d{12})$";

            try
            {
                if (!Regex.IsMatch(request.UPC, pattern))
                {
                    throw new Exception("UPC must be 12 digit number.");
                }

                var resp = await _domainService.UpdateItem(id, request);

                if (resp)
                {
                    updateItemResponse = new UpdateItemResponse()
                    {
                        Message = $"Record with Id: {id} sucessfully updated."
                    };
                }
                else
                {
                    updateItemResponse = new UpdateItemResponse()
                    {
                        Message = $"Record with Id: {id} does not exist."
                    };
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return(updateItemResponse);
        }
Exemple #25
0
        public bool ReleaseLock(LockItem item)
        {
            if (!item.Owner.Equals(_ownerName))
            {
                return(false);
            }

            lock (_threadLock)
            {
                try
                {
                    _locks.TryRemove(item.UniqueIdentifier, out var removedLockItem);

                    Dictionary <string, AttributeValue> expressionAttributeValues =
                        new Dictionary <string, AttributeValue>
                    {
                        { RvnValueExpressionVariable, new AttributeValue {
                              S = item.RecordVersionNumber
                          } },
                        { OwnerNameValueExpressionVariable, new AttributeValue {
                              S = item.Owner
                          } }
                    };

                    Dictionary <string, string> expressionAttributeNames = new Dictionary <string, string>
                    {
                        { PkPathExpressionVariable, _partitionKeyName },
                        { OwnerNamePathExpressionVariable, OwnerName },
                        { RvnPathExpressionVariable, RecordVersionNumber }
                    };

                    var conditionalExpression = PkExistsAndOwnerNameSameAndRvnSameCondition;

                    Dictionary <string, AttributeValue> key = new Dictionary <string, AttributeValue>
                    {
                        {
                            _partitionKeyName, new AttributeValue
                            {
                                S = item.UniqueIdentifier
                            }
                        }
                    };

                    string updateExpression = null;
                    expressionAttributeNames.Add(IsReleasedPathExpressionVariable, IsReleased);
                    expressionAttributeValues.Add(IsReleasedValueExpressionVariable, IsReleasedAttributeValue);

                    updateExpression = UpdateIsReleased;


                    UpdateItemRequest updateItemRequest =
                        new UpdateItemRequest(_tableName, key, null)
                    {
                        ConditionExpression       = conditionalExpression,
                        UpdateExpression          = updateExpression,
                        ExpressionAttributeNames  = expressionAttributeNames,
                        ExpressionAttributeValues = expressionAttributeValues
                    };


                    UpdateItemResponse response =
                        _client.UpdateItemAsync(updateItemRequest, CancellationToken.None).Result;
                }
                catch (ConditionalCheckFailedException conditionalCheckFailedException)
                {
                    // logger.debug("Someone else acquired the lock before you asked to release it", conditionalCheckFailedException);
                    return(false);
                }
                catch (AmazonClientException amazonClientException)
                {
                    throw;
                }
            }

            return(true);
        }
Exemple #26
0
 /**
  * Retrieve the item from the UpdateItemOutcome object and print
  * its contents in JSON format
  *
  * @param response     Order
  * @return             Order in JSON format
  */
 private static string ConvertToJSON(UpdateItemResponse response)
 {
     // STUDENT TODO 6: Replace the solution with your own code
     return(Solution.ConvertToJSON(response));
 }
        public async Task <Response <PlanoTreino> > SalvarAsync(PlanoTreino planoTreino)
        {
            var resp = new Response <PlanoTreino>();

            if (planoTreino == null)
            {
                resp.ErrorMessages.Add("Grupo Muscular inválido.");
                return(resp);
            }

            if (planoTreino.UsuarioId == 0)
            {
                resp.ErrorMessages.Add("Usuario não informado");
                return(resp);
            }

            string gruposMuscularesJson = "";

            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List <GrupoMuscular>));
                    ser.WriteObject(ms, planoTreino.GruposMusculares);
                    byte[] json = ms.ToArray();
                    ms.Close();
                    gruposMuscularesJson = Encoding.UTF8.GetString(json, 0, json.Length);
                }
            }
            catch (Exception e)
            {
                _log.LogError(e.Message);
                resp.ErrorMessages.Add(e.Message);
            }

            resp.Return = planoTreino;
            var    attributeValues = new Dictionary <string, AttributeValue>();
            var    attributeNames  = new Dictionary <string, string>();
            string updExpr         = String.Empty;

            planoTreino.DtAtualizacao = DateTime.Now;
            attributeNames.Add("#dtAt", "dt-atualizacao");
            attributeValues.Add(":dtAt", new AttributeValue {
                S = planoTreino.DtAtualizacao.ToString()
            });
            updExpr = "#dtAt = :dtAt";

            if (planoTreino.Id < 1)
            {
                planoTreino.Id = (Int32)DateTimeOffset.UtcNow.ToUnixTimeSeconds();

                attributeNames.Add("#usrId", "usuario-id");
                attributeValues.Add(":usrId", new AttributeValue {
                    N = planoTreino.UsuarioId.ToString()
                });
                updExpr += ", #usrId = :usrId";
            }

            if (!String.IsNullOrEmpty(planoTreino.Descricao))
            {
                attributeNames.Add("#descr", "descricao");
                attributeValues.Add(":descr", new AttributeValue {
                    S = planoTreino.Descricao
                });
                updExpr += ", #descr = :descr";
            }

            if (!String.IsNullOrEmpty(planoTreino.Observacao))
            {
                attributeNames.Add("#obs", "observacao");
                attributeValues.Add(":obs", new AttributeValue {
                    S = planoTreino.Observacao
                });
                updExpr += ", #obs = :obs";
            }

            if (!String.IsNullOrEmpty(gruposMuscularesJson))
            {
                attributeNames.Add("#grp", "grupos-musculares");
                attributeValues.Add(":grp", new AttributeValue {
                    S = gruposMuscularesJson
                });
                updExpr += ", #grp = :grp";
            }

            var request = new UpdateItemRequest
            {
                TableName = _context.TableName,
                Key       = new Dictionary <string, AttributeValue>
                {
                    { "tipo", new AttributeValue {
                          S = TipoPlanoTreino(planoTreino)
                      } },
                    { "id", new AttributeValue {
                          N = planoTreino.Id.ToString()
                      } }
                },
                ExpressionAttributeNames  = attributeNames,
                ExpressionAttributeValues = attributeValues,
                UpdateExpression          = "SET " + updExpr
            };

            UpdateItemResponse updResponse = null;

            using (var client = _context.GetClientInstance())
            {
                try
                {
                    updResponse = await client.UpdateItemAsync(request);

                    resp.Messages.Add(updResponse.HttpStatusCode.ToString());
                }
                catch (Exception e)
                {
                    _log.LogError(e.Message);
                    resp.ErrorMessages.Add(e.Message);
                }
                return(resp);
            }
        }
Exemple #28
0
        public async Task <Response <PostagemHome> > SalvarAsync(PostagemHome postagemHome)
        {
            var resp = new Response <PostagemHome>();

            if (postagemHome == null)
            {
                resp.ErrorMessages.Add("postagem nula.");
                return(resp);
            }

            if (postagemHome.UsuarioId == 0)
            {
                resp.ErrorMessages.Add("Usuario não informado");
                return(resp);
            }

            resp.Return = postagemHome;
            var    attributeValues = new Dictionary <string, AttributeValue>();
            var    attributeNames  = new Dictionary <string, string>();
            string updExpr         = String.Empty;

            postagemHome.DataAtualizacao = DateTime.Now;
            attributeNames.Add("#dtAt", "dt-atualizacao");
            attributeValues.Add(":dtAt", new AttributeValue {
                S = postagemHome.DataAtualizacao.ToString("dd/MM/yyyy hh:mm:ss")
            });
            updExpr = "#dtAt = :dtAt";

            attributeNames.Add("#ordem", "ordem");
            attributeValues.Add(":ordem", new AttributeValue {
                N = postagemHome.Ordem.ToString()
            });
            updExpr += ", #ordem = :ordem";

            if (postagemHome.Id < 1)
            {
                postagemHome.Id = (Int32)DateTimeOffset.UtcNow.ToUnixTimeSeconds();

                attributeNames.Add("#usrId", "usuario-id");
                attributeValues.Add(":usrId", new AttributeValue {
                    N = postagemHome.UsuarioId.ToString()
                });
                updExpr += ", #usrId = :usrId";
            }

            if (!String.IsNullOrEmpty(postagemHome.Titulo))
            {
                attributeNames.Add("#titulo", "titulo");
                attributeValues.Add(":titulo", new AttributeValue {
                    S = postagemHome.Titulo
                });
                updExpr += ", #titulo = :titulo";
            }

            if (!String.IsNullOrEmpty(postagemHome.Texto))
            {
                attributeNames.Add("#texto", "texto");
                attributeValues.Add(":texto", new AttributeValue {
                    S = postagemHome.Texto
                });
                updExpr += ", #texto = :texto";
            }

            attributeNames.Add("#urlImagem", "url-imagem");

            if (!String.IsNullOrEmpty(postagemHome.UrlImagem))
            {
                attributeValues.Add(":urlImagem", new AttributeValue {
                    S = postagemHome.UrlImagem
                });
                updExpr += ", #urlImagem = :urlImagem";
            }
            else
            {
                updExpr += " REMOVE #urlImagem";
            }

            var request = new UpdateItemRequest
            {
                TableName = _context.TableName,
                Key       = new Dictionary <string, AttributeValue>
                {
                    { "tipo", new AttributeValue {
                          S = _type
                      } },
                    { "id", new AttributeValue {
                          N = postagemHome.Id.ToString()
                      } }
                },
                ExpressionAttributeNames  = attributeNames,
                ExpressionAttributeValues = attributeValues,
                UpdateExpression          = "SET " + updExpr
            };

            UpdateItemResponse updResponse = null;

            using (var client = _context.GetClientInstance())
            {
                try
                {
                    updResponse = await client.UpdateItemAsync(request);

                    resp.Messages.Add(updResponse.HttpStatusCode.ToString());
                }
                catch (Exception e)
                {
                    _log.LogError(e.Message);
                    resp.ErrorMessages.Add(e.Message);
                }
                return(resp);
            }
        }
Exemple #29
0
        public void SendHeartbeat(LockItem item)
        {
            long leaseDurationToEnsureInMilliseconds = _leaseDuration;


            if (item.IsExpired || !item.Owner.Equals(this._ownerName) || item.IsReleased)
            {
                _locks.TryRemove(item.UniqueIdentifier, out var removedLockItem);

                throw new LockNotGrantedException("Cannot send heartbeat because lock is not granted", null);
            }

            lock (_threadLock)
            {
                string recordVersionNumber   = GenerateRecordVersionNumber();
                string conditionalExpression = null;
                string updateExpression      = null;

                Dictionary <string, AttributeValue> expressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { RvnValueExpressionVariable, new AttributeValue {
                          S = item.RecordVersionNumber
                      } },
                    { OwnerNameValueExpressionVariable, new AttributeValue {
                          S = item.Owner
                      } }
                };

                Dictionary <string, string> expressionAttributeNames = new Dictionary <string, string>
                {
                    { PkPathExpressionVariable, _partitionKeyName },
                    { LeaseDurationPathValueExpressionVariable, LeaseDuration },
                    { RvnPathExpressionVariable, RecordVersionNumber },
                    { OwnerNamePathExpressionVariable, OwnerName }
                };


                expressionAttributeValues.Add(NewRvnValueExpressionVariable, new AttributeValue {
                    S = recordVersionNumber
                });
                expressionAttributeValues.Add(LeaseDurationValueExpressionVariable, new AttributeValue
                {
                    S = _leaseDuration.ToString()
                });


                conditionalExpression = PkExistsAndOwnerNameSameAndRvnSameCondition;
                updateExpression      = UpdateLeaseDurationAndRvn;

                var key = new Dictionary <string, AttributeValue>
                {
                    { _partitionKeyName, new AttributeValue {
                          S = item.UniqueIdentifier
                      } }
                };

                UpdateItemRequest updateItemRequest =
                    new UpdateItemRequest(_tableName, key, null)
                {
                    ConditionExpression       = conditionalExpression,
                    UpdateExpression          = updateExpression,
                    ExpressionAttributeValues = expressionAttributeValues,
                    ExpressionAttributeNames  = expressionAttributeNames
                };



                try
                {
                    UpdateItemResponse response = _client.UpdateItemAsync(updateItemRequest).Result;

                    if (response.HttpStatusCode != HttpStatusCode.OK)
                    {
                        throw new LockNotGrantedException("failed to updated database", null);
                    }

                    item.UpdatedRecordVersionNumber(recordVersionNumber, DateTime.Now,
                                                    leaseDurationToEnsureInMilliseconds);

                    Console.WriteLine($"updated lock item : {item.UniqueIdentifier} with new RVN: {recordVersionNumber} and lease {_leaseDuration / 1000} seconds");
                }
                catch (ConditionalCheckFailedException conditionalCheckFailedException)
                {
                    //    logger.debug("Someone else acquired the lock, so we will stop heartbeating it", conditionalCheckFailedException);
                    _locks.TryRemove(item.UniqueIdentifier, out var lockToRemove);
                    throw new LockNotGrantedException("Someone else acquired the lock, so we will stop heartbeating it",
                                                      conditionalCheckFailedException);
                }
            }
        }
Exemple #30
0
        public async Task <string> FunctionHandler(S3Event evnt, ILambdaContext context)
        {
            var s3Event = evnt.Records?[0].S3;

            if (s3Event == null)
            {
                return(null);
            }
            else
            {
                try
                {
                    S3Client = new AmazonS3Client(bucketRegion);
                    GetObjectRequest request = new GetObjectRequest
                    {
                        BucketName = s3Event.Bucket.Name,
                        Key        = s3Event.Object.Key
                    };

                    int count          = 0;
                    int recordsUpdated = 0;
                    int recordsErrored = 0;

                    using (GetObjectResponse response = await S3Client.GetObjectAsync(request))
                    {
                        StreamReader reader;
                        using (reader = new StreamReader(response.ResponseStream, Encoding.UTF8))
                        {
                            using (var csv = new CsvReader(reader))
                            {
                                csv.Read();
                                csv.ReadHeader();

                                while (csv.Read())
                                {
                                    if (count < 2000)
                                    {
                                        //Console.WriteLine("INFO : Week : '{0}' Day : '{1}' UPRN : '{2}'", csv.GetField<String>("Week"), csv.GetField<String>("Day"), csv.GetField<String>("UPRN"));
                                        String round = "";
                                        switch (csv.GetField <String>("Week"))
                                        {
                                        case "A":
                                            switch (csv.GetField <String>("Day"))
                                            {
                                            case "Monday":
                                                round = "1";
                                                break;

                                            case "Tuesday":
                                                round = "2";
                                                break;

                                            case "Wednesday":
                                                round = "3";
                                                break;

                                            case "Thursday":
                                                round = "4";
                                                break;

                                            case "Friday":
                                                round = "5";
                                                break;

                                            default:
                                                Console.WriteLine("Unexpected Day found for UPRN : '{0}'", csv.GetField <String>("UPRN"));
                                                break;
                                            }
                                            break;

                                        case "B":
                                            switch (csv.GetField <String>("Day"))
                                            {
                                            case "Monday":
                                                round = "7";
                                                break;

                                            case "Tuesday":
                                                round = "8";
                                                break;

                                            case "Wednesday":
                                                round = "9";
                                                break;

                                            case "Thursday":
                                                round = "10";
                                                break;

                                            case "Friday":
                                                round = "11";
                                                break;

                                            default:
                                                Console.WriteLine("Unexpected Day found for UPRN : '{0}'", csv.GetField <String>("UPRN"));
                                                break;
                                            }
                                            break;

                                        default:
                                            Console.WriteLine("Unexpected Week found for UPRN : '{0}'", csv.GetField <String>("UPRN"));
                                            break;
                                        }
                                        AmazonDynamoDBClient client = new AmazonDynamoDBClient();
                                        string tableName            = "bin-details";
                                        var    dynamoRequest        = new UpdateItemRequest
                                        {
                                            TableName = tableName,
                                            Key       = new Dictionary <string, AttributeValue>()
                                            {
                                                { "UPRN", new AttributeValue {
                                                      N = csv.GetField <String>("UPRN")
                                                  } }
                                            },
                                            ExpressionAttributeNames = new Dictionary <string, string>()
                                            {
                                                { "#D", "Day" },
                                                { "#R", "Round" },
                                                { "#B", "Bins2Sacks" }
                                            },
                                            ExpressionAttributeValues = new Dictionary <string, AttributeValue>()
                                            {
                                                { ":day", new AttributeValue {
                                                      S = csv.GetField <String>("Day")
                                                  } },
                                                { ":round", new AttributeValue {
                                                      N = round
                                                  } },
                                                { ":bins2sacks", new AttributeValue {
                                                      S = "Y"
                                                  } }
                                            },
                                            UpdateExpression = "SET #D = :day, #R = :round, #B = :bins2sacks"
                                        };
                                        UpdateItemResponse dynamoResponse = await client.UpdateItemAsync(dynamoRequest);

                                        if (dynamoResponse.HttpStatusCode == HttpStatusCode.OK)
                                        {
                                            recordsUpdated++;
                                        }
                                        else
                                        {
                                            Console.WriteLine("DynamoResponse NOT OK : '{0}'", dynamoResponse.HttpStatusCode);
                                            recordsErrored++;
                                        }
                                    }
                                    count++;
                                }
                            }
                        }
                    }
                    Console.WriteLine("Records processed   : '{0}'", count);
                    Console.WriteLine("Records updated     : '{0}'", recordsUpdated);
                    Console.WriteLine("Records not updated : '{0}'", recordsErrored);
                    return("{\"Message\":\"Found file\",\"lambdaResult\":\"Success\"}");
                }
                catch (AmazonS3Exception error)
                {
                    Console.WriteLine("ERROR : Reading Email : '{0}' when reading file", error.Message);
                    return(null);
                }
                catch (Exception error)
                {
                    Console.WriteLine("ERROR : An Unknown encountered : {0}' when reading file", error.Message);
                    return(null);
                }
            }
        }