public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            PutItemResponse response = new PutItemResponse();

            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);
        }
Beispiel #2
0
        public async Task <bool> PutSecret(string secret, string challenge, string address, string fileHash)
        {
            var request = new PutItemRequest
            {
                TableName = tableName,
                Item      = new Dictionary <string, AttributeValue>()
                {
                    { columnSecret, new AttributeValue {
                          S = secret
                      } },
                    { columnChallenge, new AttributeValue {
                          S = challenge
                      } },
                    { columnAddress, new AttributeValue {
                          S = address
                      } },
                    { columnFileHash, new AttributeValue {
                          S = fileHash
                      } }
                }
            };
            PutItemResponse dynamoDbResponse = await _client.PutItemAsync(request);

            return(dynamoDbResponse.HttpStatusCode == System.Net.HttpStatusCode.OK);
        }
        /**
         * Add a ticket price audit record.
         */
        private static async void AddCountryAudit(AmazonDynamoDBClient dbClient,
                                                  string loggedInUserId,
                                                  CountryAuditRecord.AuditChangeType changeType,
                                                  Country country)
        {
            Debug.Tested();
            Debug.AssertValid(dbClient);
            Debug.AssertID(loggedInUserId);
            Debug.AssertValid(country);

            Dictionary <string, AttributeValue> item = new Dictionary <string, AttributeValue>();
            string id = RandomHelper.Next();

            item.Add(FIELD_COUNTRY_AUDIT_ID, new AttributeValue(id));
            item.Add(FIELD_COUNTRY_AUDIT_TIMESTAMP, new AttributeValue(APIHelper.APITimestampStringFromDateTime(DateTime.Now)));
            item.Add(FIELD_COUNTRY_AUDIT_ADMINISTRATOR_ID, new AttributeValue(loggedInUserId));
            item.Add(FIELD_COUNTRY_AUDIT_CHANGE_TYPE, new AttributeValue {
                N = changeType.ToString()
            });
            item.Add(FIELD_COUNTRY_AUDIT_CODE, new AttributeValue(country.Code));
            item.Add(FIELD_COUNTRY_AUDIT_NAME, new AttributeValue(country.Name));
            item.Add(FIELD_COUNTRY_AUDIT_CURRENCIES, new AttributeValue(country.Currencies));
            item.Add(FIELD_COUNTRY_AUDIT_AVAILABLE, new AttributeValue {
                BOOL = country.Available
            });
            PutItemResponse response = await dbClient.PutItemAsync(DATASET_COUNTRY_AUDIT, item);

            Debug.AssertValid(response);
            //??++CHECK RESPONSE?
        }
Beispiel #4
0
        public void Add(Employee employee)
        {
            var request = new PutItemRequest
            {
                TableName = "employee",
                Item      = new Dictionary <string, AttributeValue>
                {
                    { "id", new AttributeValue {
                          S = DateTime.Now.Ticks.ToString()
                      } },
                    { "name", new AttributeValue {
                          S = employee.name
                      } },
                    { "email", new AttributeValue {
                          S = employee.email
                      } },
                    { "department", new AttributeValue {
                          S = employee.department
                      } }
                }
            };
            PutItemResponse x = dynamodbClient.PutItemAsync(request).Result;

            if (x.HttpStatusCode != System.Net.HttpStatusCode.OK && x.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception("Unable to add Employee");
            }

            return;
        }
Beispiel #5
0
        public async Task <APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            LambdaLogger.Log(JObject.FromObject(request).ToString());
            try {
                var connectionId = request.RequestContext.ConnectionId;
                LambdaLogger.Log("ConnectionId:" + connectionId);

                Dictionary <string, AttributeValue> attributes = new Dictionary <string, AttributeValue>();
                attributes["ConnectionId"] = new AttributeValue {
                    S = connectionId
                };


                PutItemRequest ddbRequest = new PutItemRequest()
                {
                    TableName = Environment.GetEnvironmentVariable("DynamoChatTable"),
                    Item      = attributes
                };
                PutItemResponse ddbResponse = ddbClient.PutItemAsync(ddbRequest).Result;

                return(new APIGatewayProxyResponse
                {
                    StatusCode = 200,
                    Body = "Connected."
                });
            } catch (Exception e) {
                LambdaLogger.Log("Error connecting: " + e.Message);
                LambdaLogger.Log(e.StackTrace);
                return(new APIGatewayProxyResponse
                {
                    StatusCode = 500,
                    Body = $"Failed to connecting: {e.Message}"
                });
            }
        }
Beispiel #6
0
 public PutPointResult(PutItemResponse putItemResult)
 {
     if (putItemResult == null)
     {
         throw new ArgumentNullException("putItemResult");
     }
     PutItemResult = putItemResult;
 }
        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);
        }
Beispiel #8
0
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            PutItemResponse response = new PutItemResponse();

            context.Read();

            UnmarshallResult(context, response);
            return(response);
        }
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            PutItemResponse response = new PutItemResponse();

            context.Read();
            response.PutItemResult = PutItemResultUnmarshaller.GetInstance().Unmarshall(context);

            return(response);
        }
Beispiel #10
0
        private static void UnmarshallResult(JsonUnmarshallerContext context, PutItemResponse 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);
        }
Beispiel #12
0
        public async Task <PutPointResult> PutPointAsync(PutPointRequest putPointRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (putPointRequest == null)
            {
                throw new ArgumentNullException("putPointRequest");
            }

            var geohash   = S2Manager.GenerateGeohash(putPointRequest.FromGeoPoint);
            var rangeHash = S2Manager.GenerateGeohash(putPointRequest.ToGeoPoint);
            var hashKey   = S2Manager.GenerateHashKey(geohash, _config.HashKeyLength);
            var geoJson   = GeoJsonMapper.StringFromGeoObject(putPointRequest.FromGeoPoint);

            var putItemRequest = putPointRequest.PutItemRequest;

            putItemRequest.TableName = _config.TableName;

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

            putItemRequest.Item[_config.HashKeyAttributeName]  = hashKeyValue;
            putItemRequest.Item[_config.RangeKeyAttributeName] = new AttributeValue
            {
                S = rangeHash.ToString(CultureInfo.InvariantCulture)
            };


            var geohashValue = new AttributeValue
            {
                N = geohash.ToString(CultureInfo.InvariantCulture)
            };

            putItemRequest.Item[_config.GeohashAttributeName] = geohashValue;

            var geoJsonValue = new AttributeValue
            {
                S = geoJson
            };

            putItemRequest.Item[_config.GeoJsonAttributeName] = geoJsonValue;

            PutItemResponse putItemResult = await _config.DynamoDBClient.PutItemAsync(putItemRequest, cancellationToken).ConfigureAwait(false);

            var putPointResult = new PutPointResult(putItemResult);

            return(putPointResult);
        }
Beispiel #13
0
        /**
         * Add an identity global setting record to the data store.
         */
        internal static async Task AddIdentityGlobalSetting(AmazonDynamoDBClient dbClient, string name, string value)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertString(name);
            Debug.AssertStringOrNull(value);

            Dictionary <string, AttributeValue> item = new Dictionary <string, AttributeValue>();

            item.Add(FIELD_IDENTITY_GLOBAL_SETTINGS_NAME, new AttributeValue(name));
            item.Add(FIELD_IDENTITY_GLOBAL_SETTINGS_VALUE, new AttributeValue(value));
            PutItemResponse putResponse = await dbClient.PutItemAsync(DATASET_IDENTITY_GLOBAL_SETTINGS, item);

            Debug.AssertValid(putResponse);
            //??++Check response?
        }
Beispiel #14
0
        private LockItem UpsertExpiredLock(string key, string recordVersionNumber)
        {
            var item = BuildLockItem(key, recordVersionNumber);

            string conditionalExpression = null;
            Dictionary <string, AttributeValue> expressionAttributeValues =
                new Dictionary <string, AttributeValue>
            {
                { RvnValueExpressionVariable, new AttributeValue {
                      S = recordVersionNumber
                  } }
            };

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

            conditionalExpression = PkExistsAndRvnIsTheSameCondition;

            PutItemRequest putItemRequest =
                new PutItemRequest(_tableName, item)
            {
                ExpressionAttributeNames  = expressionAttributeNames,
                ExpressionAttributeValues = expressionAttributeValues,
                ConditionExpression       = conditionalExpression
            };

            DateTime lookUpTime = DateTime.Now;

            PutItemResponse response = _client.PutItemAsync(putItemRequest).Result;

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                var lockItem = CreateLockFromDbAttribute(item, lookUpTime);

                _locks.TryAdd(lockItem.UniqueIdentifier, lockItem);

                return(lockItem);
            }


            return(null);
        }
Beispiel #15
0
        /**
         * Add a access token record to the data store.
         */
        internal static async Task AddAccessToken(AmazonDynamoDBClient dbClient, AccessToken accessToken)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertValid(accessToken);
            Debug.AssertID(accessToken.ID);

            Dictionary <string, AttributeValue> item = new Dictionary <string, AttributeValue>();

            item.Add(FIELD_ACCESS_TOKENS_ID, new AttributeValue(accessToken.ID));
            item.Add(FIELD_ACCESS_TOKENS_USER_ID, new AttributeValue(accessToken.UserID));
            item.Add(FIELD_ACCESS_TOKENS_EXPIRES, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(accessToken.Expires)));
            item.Add(FIELD_ACCESS_TOKENS_MAX_EXPIRY, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(accessToken.MaxExpiry)));
            PutItemResponse putResponse = await dbClient.PutItemAsync(DATASET_ACCESS_TOKENS, item);

            Debug.AssertValid(putResponse);
            //??++Check response?
        }
Beispiel #16
0
        /// <summary>
        /// Creates a user with given information.
        /// </summary>
        /// <param name="user">Entity holding user information, without password.</param>
        /// <param name="password">Password of a user.</param>
        /// <returns>Created user entity on success, null otherwise.</returns>
        public async Task <User> Create(User user, string password)
        {
            // Password validation.
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ApplicationException("Password is required.");
            }

            // Check if username is already taken.
            QueryResponse dbResult = await _dynamoDBClient.QueryAsync(new QueryRequest()
            {
                TableName = "dotnetcore-react-redux-users",
                IndexName = "username-index",
                KeyConditionExpression    = "username = :username",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>()
                {
                    [":username"] = new AttributeValue()
                    {
                        S = user.Username
                    }
                },
            });

            if (dbResult.Items.Count > 0)
            {
                throw new ApplicationException("Username '" + user.Username + "' is already taken.");
            }

            byte[] passwordHash;
            CreatePasswordHash(password, out passwordHash);

            user.PasswordHash = passwordHash;

            // Create ID based on timestamp.
            user.Id = new Random().Next() + 1;

            PutItemResponse putItemResult = await _dynamoDBClient.PutItemAsync(new PutItemRequest()
            {
                TableName = "dotnetcore-react-redux-users",
                Item      = this.ConvertUserToDynamoDBItem(user)
            });

            return(user);
        }
Beispiel #17
0
        public void PutItem()
        {
            try
            {
                StringBuilder sb = new StringBuilder("", 50);
                sb.Append("MS Dhoni");
                var request = new PutItemRequest
                {
                    TableName = "Student",
                    Item      = new Dictionary <string, AttributeValue>()
                    {
                        { "Id", new AttributeValue {
                              N = "5"
                          } },
                        { "Branch", new AttributeValue {
                              S = "CSE"
                          } },
                        { "Marks", new AttributeValue {
                              N = marks.ToString()
                          } },
                        { "Name", new AttributeValue {
                              S = sb.ToString()
                          } },
                    }
                    //  ,
                    //ExpressionAttributeNames = new Dictionary<string, string>() {

                    //    {"#Student","Name"}
                    //},
                    //ExpressionAttributeValues = new Dictionary<string,AttributeValue>(){

                    //    {":studentname",new AttributeValue{S="Dhoni"}}
                    //},
                    //ConditionExpression = "Name = Dhoni"
                };
                PutItemResponse putResponse = client.PutItem(request);
                successMessage = putResponse.HttpStatusCode == HttpStatusCode.OK ? "Success" : "Error";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #18
0
        //public async Task AddNewEntry(int id, string replyDateTime, double price)
        //{
        //	var queryRequest = RequestBuilder(id, replyDateTime, price);

        //	await PutItemAsync(queryRequest);
        //}

        //private PutItemRequest RequestBuilder(int id, string replyDateTime, double price)
        //{
        //	var item = new Dictionary<string, AttributeValue>
        //	{
        //		{"Id", new AttributeValue {N = id.ToString()} },
        //		{"ReplyDateTime", new AttributeValue {S = replyDateTime.ToString()} },
        //		{"Price", new AttributeValue {N = price.ToString(CultureInfo.InvariantCulture)}}

        //	};

        //	return new PutItemRequest
        //	{
        //		TableName = "TempDynamoDB",
        //		Item = item
        //	};
        //}

        public async Task <PutItemResponse> PutItems <T> (T tabelaInterna, string nomeTabela)
        {
            //Identificar tabela
            table = Table.LoadTable(_dynamoClient, nomeTabela);
            //Criar contexto
            DynamoDBContext db = new DynamoDBContext(_dynamoClient);
            //Identificando campos do objeto genérico preenchidos
            Document documentRequest = db.ToDocument(tabelaInterna);

            //Mapeando os campos
            chave = table.ToAttributeMap(documentRequest);
            //Realizar o PUT
            PutItemResponse response = await _dynamoClient.PutItemAsync(nomeTabela, chave, cancellationToken);

            //
            db.Dispose();
            //Retornar resposta
            return(response);
        }
Beispiel #19
0
        public bool SaveGame(Game gameData)
        {
            var putItemRequest = new PutItemRequest
            {
                TableName = "Game",
                Item      = gameData.AsDictionary()
            };

            using (var dynamoClient = new AmazonDynamoDBClient(RegionEndpoint.APSoutheast2))
            {
                PutItemResponse response = null;

                Task.Run(async() =>
                {
                    response = await dynamoClient.PutItemAsync(putItemRequest);
                }).Wait();

                return((response?.HttpStatusCode ?? HttpStatusCode.InternalServerError) == HttpStatusCode.OK);
            }
        }
Beispiel #20
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <string> FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context)
        {
            //declaring dictionary for items to send to db
            Dictionary <string, AttributeValue> myDictionary = new Dictionary <string, AttributeValue>();

            //for deserializing input obj if neeeded
            //obj = JsonConvert.DeserializeObject<myJSONBody>(input.Body);

            //adding item to dict
            //specifiying what type of data is being inserted to db AKA SHORTHAND
            myDictionary.Add("id", new AttributeValue()
            {
                S = input.Body.ToUpper()
            });
            PutItemRequest myRequest = new PutItemRequest(tableName, myDictionary);
            //async struct
            PutItemResponse res = await client.PutItemAsync(myRequest);

            return(input.Body.ToUpper());
        }
Beispiel #21
0
        private LockItem AddLockItemToDynamo(string partitionKey, string recordVersionNumber,
                                             PutItemRequest putItemRequest)
        {
            long lastUpdatedTime = LockClientUtils.TimeStamp();


            PutItemResponse response = _client.PutItemAsync(putItemRequest).Result;

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                //todo: do something with this
            }

            LockItem lockItem =
                new LockItem(partitionKey, _ownerName, recordVersionNumber, DateTime.Now, null);

            _locks.TryAdd(lockItem.UniqueIdentifier, lockItem);

            return(lockItem);
        }
Beispiel #22
0
        public async Task InsertNewItem(Profile profile)
        {
            Dictionary <string, AttributeValue> item =
                ConvertFromProfile(profile);
            PutItemRequest putItemRequest = new PutItemRequest
            {
                TableName = _tableName,
                Item      = item
            };
            PutItemResponse putItemResponse = await _dynamoDBClient.PutItemAsync(putItemRequest);

            if (putItemResponse.HttpStatusCode == HttpStatusCode.OK ||
                putItemResponse.HttpStatusCode == HttpStatusCode.Created)
            {
                Console.WriteLine("New item successfully added");
            }
            else
            {
                Console.WriteLine(putItemResponse.HttpStatusCode);
            }
        }
        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);
        }
Beispiel #24
0
        public LockItem AddAndWatchNewOrReleasedLock(string partitionKey, string recordVersionNumber,
                                                     Dictionary <string, AttributeValue> item)
        {
            Dictionary <string, string> expressionAttributeNames = new Dictionary <string, string>
            {
                { PkPathExpressionVariable, _partitionKeyName },
                { IsReleasedPathExpressionVariable, IsReleased }
            };

            Dictionary <string, AttributeValue> expressionAttributeValues =
                new Dictionary <string, AttributeValue> {
                { IsReleasedValueExpressionVariable, IsReleasedAttributeValue }
            };


            PutItemRequest putItemRequest = new PutItemRequest(_tableName, item)
            {
                ConditionExpression       = AcquireLockThatDoesntExistOrIsReleasedCondition,
                ExpressionAttributeNames  = expressionAttributeNames,
                ExpressionAttributeValues = expressionAttributeValues
            };


            long lastUpdatedTime = LockClientUtils.TimeStamp();


            PutItemResponse response = _client.PutItemAsync(putItemRequest).Result;

            if (response.HttpStatusCode != HttpStatusCode.OK)
            {
                //todo: do something with this
            }

            LockItem lockItem =
                new LockItem(partitionKey, _ownerName, recordVersionNumber, DateTime.Now, null);

            _locks.TryAdd(lockItem.UniqueIdentifier, lockItem);

            return(lockItem);
        }
Beispiel #25
0
        /**
         * Add a link record to the data store.
         */
        internal static async Task AddLink(AmazonDynamoDBClient dbClient, Link link)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertValid(link);
            Debug.AssertID(link.ID);

            Dictionary <string, AttributeValue> item = new Dictionary <string, AttributeValue>();

            item.Add(FIELD_LINKS_ID, new AttributeValue(link.ID));
            item.Add(FIELD_LINKS_TYPE, new AttributeValue(link.Type));
            item.Add(FIELD_LINKS_EXPIRES, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(link.Expires)));
            item.Add(FIELD_LINKS_USER_ID, new AttributeValue(link.UserID));
            item.Add(FIELD_LINKS_REVOKED, new AttributeValue {
                BOOL = link.Revoked
            });
            item.Add(FIELD_LINKS_ONE_TIME_PASSWORD, new AttributeValue(link.OneTimePassword));
            PutItemResponse putResponse = await dbClient.PutItemAsync(DATASET_LINKS, item);

            Debug.AssertValid(putResponse);
            //??++Check response?
        }
Beispiel #26
0
        public static async Task <bool> InsertSecretChallange(this AmazonDynamoDBClient client, string secret, string challenge, string address)
        {
            var request = new PutItemRequest
            {
                TableName = tableName,
                Item      = new Dictionary <string, AttributeValue>()
                {
                    { columnSecret, new AttributeValue {
                          S = secret
                      } },
                    { columnChallenge, new AttributeValue {
                          S = challenge
                      } },
                    { columnAddress, new AttributeValue {
                          S = address
                      } }
                }
            };
            PutItemResponse dynamoDbResponse = await client.PutItemAsync(request);

            return(dynamoDbResponse.HttpStatusCode == System.Net.HttpStatusCode.OK);
        }
Beispiel #27
0
        public async Task <string> SubmitQuote(QuoteWriteDTO quote)
        {
            string referenceId = Guid.NewGuid().ToString();
            // The best way to get accurate timing
            long ttlExpiryTimestamp = (long)DateTime.UtcNow.Subtract(DateTime.UnixEpoch)
                                      .Add(TimeSpan.FromHours(DataDefinitions.QUOTES_PROPOSAL_TABLE_TTL_VALUE_HOURS)).TotalSeconds;

            Dictionary <string, AttributeValue> attributes = new Dictionary <string, AttributeValue>
            {
                { DataDefinitions.QUOTES_PROPOSAL_TABLE_HASH_KEY, new AttributeValue {
                      S = DateTime.UtcNow.ToString()
                  } },
                { DataDefinitions.QUOTES_PROPOSAL_TABLE_SORT_KEY, new AttributeValue {
                      S = referenceId
                  } },
                { "Text", new AttributeValue {
                      S = quote.Text
                  } },
                { "Quoter", new AttributeValue {
                      S = quote.Quoter
                  } },
                { "SubmitterEmail", new AttributeValue {
                      S = quote.SubmitterEmail
                  } },
                { DataDefinitions.QUOTES_PROPOSAL_TABLE_TTL, new AttributeValue {
                      N = ttlExpiryTimestamp.ToString()
                  } }
            };

            PutItemRequest request = new PutItemRequest
            {
                TableName = DataDefinitions.QUOTES_PROPOSAL_TABLE,
                Item      = attributes
            };

            PutItemResponse response = await _client.PutItemAsync(request);

            return(response.HttpStatusCode == HttpStatusCode.OK? referenceId: null);
        }
Beispiel #28
0
        public async Task <string> FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context)
        {
            Table items = Table.LoadTable(storageClient, tableName);

            /**dynamic data = new ExpandoObject();
             * Dictionary<string, string> dict = (Dictionary<string, string>)input.QueryStringParameters;
             * string something = await client.GetStringAsync("https://api.nytimes.com/svc/books/v3/lists/current/" + dict.First().Value + ".json?api-key=iXIGuGPUAFHQ5FFAnHAdkrJJ0at4fkLV");
             * dynamic objects = JsonConvert.DeserializeObject<ExpandoObject>(something);
             * return objects;
             * This is Assignment 9's code that gets data from the api*/
            //Task<ExpandoObject>


            Dictionary <string, string> dict = (Dictionary <string, string>)input.QueryStringParameters;
            string something = await client.GetStringAsync("https://api.lyrics.ovh/v1/" + dict.First().Key + "/" + dict.First().Value);

            dynamic objects = JsonConvert.DeserializeObject <ExpandoObject>(something);



            Dictionary <string, AttributeValue> myDictionary = new Dictionary <string, AttributeValue>();

            myDictionary.Add("song", new AttributeValue()
            {
                S = dict.First().Value
            });
            myDictionary.Add("lyrics", new AttributeValue()
            {
                S = objects.lyrics
            });
            PutItemRequest  myRequest = new PutItemRequest(tableName, myDictionary);
            PutItemResponse res       = await storageClient.PutItemAsync(myRequest);


            return("Song: " + dict.First().Value + "\nLyrics: " + objects.lyrics);
        }
Beispiel #29
0
        /// <summary>
        /// Updates a user's information with given data.
        /// </summary>
        /// <param name="userParam">Information to be updated. Must have all information including non-changed ones.</param>
        /// <param name="password">To change password, set this parameter as non-null, non-whitespace only value.</param>
        public async Task <User> Update(User userParam, string password = null)
        {
            // Fetch target user.
            GetItemResponse dbResult = await _dynamoDBClient.GetItemAsync(new GetItemRequest()
            {
                TableName = "dotnetcore-react-redux-users",
                Key       = new Dictionary <string, AttributeValue>()
                {
                    ["id"] = new AttributeValue()
                    {
                        N = userParam.Id.ToString()
                    }
                }
            });

            if (dbResult.Item == null)
            {
                throw new ApplicationException("User not found.");
            }
            User user = this.ConvertDynamoDBItemToUser(dbResult.Item);

            if (userParam.Username != user.Username)
            {
                // Check if username is already taken.
                QueryResponse usernameCheckResult = await _dynamoDBClient.QueryAsync(new QueryRequest()
                {
                    TableName = "dotnetcore-react-redux-users",
                    IndexName = "username-index",
                    KeyConditionExpression    = "username = :username",
                    ExpressionAttributeValues = new Dictionary <string, AttributeValue>()
                    {
                        [":username"] = new AttributeValue()
                        {
                            S = userParam.Username
                        }
                    }
                });

                if (usernameCheckResult.Items.Count > 0)
                {
                    throw new ApplicationException("Username '" + userParam.Username + "' is already taken.");
                }
            }

            // Update user properties.
            user.Email     = userParam.Email;
            user.FirstName = userParam.FirstName;
            user.LastName  = userParam.LastName;
            user.Username  = userParam.Username;

            // Update password if given.
            if (!string.IsNullOrWhiteSpace(password))
            {
                byte[] passwordHash;
                CreatePasswordHash(password, out passwordHash);

                user.PasswordHash = passwordHash;
            }

            PutItemResponse putItemResult = await _dynamoDBClient.PutItemAsync(new PutItemRequest()
            {
                TableName = "dotnetcore-react-redux-users",
                Item      = this.ConvertUserToDynamoDBItem(user)
            });

            return(user);
        }
Beispiel #30
0
        /**
         * Add a user record to the data store.
         */
        internal static async Task AddUser(AmazonDynamoDBClient dbClient, User user)
        {
            Debug.Untested();
            Debug.AssertValid(dbClient);
            Debug.AssertValid(user);
            Debug.AssertID(user.ID);

            Dictionary <string, AttributeValue> item = new Dictionary <string, AttributeValue>();

            item.Add(FIELD_USERS_ID, new AttributeValue(user.ID));
            item.Add(FIELD_USERS_CLIENT_ID, new AttributeValue(user.ClientID));
            item.Add(FIELD_USERS_GIVEN_NAME, new AttributeValue(user.GivenName));
            item.Add(FIELD_USERS_FAMILY_NAME, new AttributeValue(user.FamilyName));
            item.Add(FIELD_USERS_PREFERRED_NAME, new AttributeValue(user.PreferredName));
            item.Add(FIELD_USERS_FULL_NAME, new AttributeValue(user.FullName));
            item.Add(FIELD_USERS_EMAIL_ADDRESS, new AttributeValue(user.EmailAddress));
            item.Add(FIELD_USERS_EMAIL_ADDRESS_VERIFIED, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.EmailAddressVerified)));
            item.Add(FIELD_USERS_NEW_EMAIL_ADDRESS, new AttributeValue(user.NewEmailAddress));
            item.Add(FIELD_USERS_PASSWORD_HASH, new AttributeValue(user.PasswordHash));
            item.Add(FIELD_USERS_BLOCKED, new AttributeValue {
                BOOL = user.Blocked
            });
            item.Add(FIELD_USERS_LOCKED, new AttributeValue {
                BOOL = user.Locked
            });
            item.Add(FIELD_USERS_DATE_OF_BIRTH, new AttributeValue(APIHelper.APIDateStringFromDate(user.DateOfBirth)));
            item.Add(FIELD_USERS_GENDER, new AttributeValue {
                N = user.Gender.ToString()
            });
            item.Add(FIELD_USERS_ADDRESS_1, new AttributeValue(user.Address1));
            item.Add(FIELD_USERS_ADDRESS_2, new AttributeValue(user.Address2));
            item.Add(FIELD_USERS_ADDRESS_3, new AttributeValue(user.Address3));
            item.Add(FIELD_USERS_ADDRESS_4, new AttributeValue(user.Address4));
            item.Add(FIELD_USERS_CITY, new AttributeValue(user.City));
            item.Add(FIELD_USERS_REGION, new AttributeValue(user.Region));
            item.Add(FIELD_USERS_COUNTRY, new AttributeValue(user.Country));
            item.Add(FIELD_USERS_POSTAL_CODE, new AttributeValue(user.PostalCode));
            item.Add(FIELD_USERS_PHONE_NUMBER, new AttributeValue(user.PhoneNumber));
            item.Add(FIELD_USERS_PHONE_NUMBER_VERIFIED, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.PhoneNumberVerified)));
            item.Add(FIELD_USERS_LAST_LOGGED_IN, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.LastLoggedIn)));
            item.Add(FIELD_USERS_LAST_LOGGED_OUT, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.LastLoggedOut)));
            item.Add(FIELD_USERS_CLOSED, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.Closed)));
            item.Add(FIELD_USERS_IS_ANONYMISED, new AttributeValue {
                BOOL = user.IsAnonymised
            });
            item.Add(FIELD_USERS_DELETED, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.Deleted)));
            item.Add(FIELD_USERS_ALLOW_NON_ESSENTIAL_EMAILS, new AttributeValue {
                BOOL = user.AllowNonEssentialEmails
            });
            item.Add(FIELD_USERS_ANEE_ON_TIMESTAMP, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.ANEEOnTimestamp)));
            item.Add(FIELD_USERS_ANEE_OFF_TIMESTAMP, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.ANEEOffTimestamp)));
            item.Add(FIELD_USERS_TOTAL_TICKETS_PURCHASED, new AttributeValue {
                N = user.TotalTicketsPurchased.ToString()
            });
            item.Add(FIELD_USERS_TICKETS_PURCHASED_IN_CURRENT_GAME, new AttributeValue {
                N = user.TicketsPurchasedInCurrentGame.ToString()
            });
            item.Add(FIELD_USERS_PREFERRED_LANGUAGE, new AttributeValue(user.PreferredLanguage));
            item.Add(FIELD_USERS_PREFERRED_CURRENCY, new AttributeValue(user.PreferredCurrency));
            item.Add(FIELD_USERS_PREFERRED_TIME_ZONE, new AttributeValue(user.PreferredTimeZone));
            item.Add(FIELD_USERS_FAILED_LOGIN_ATTEMPTS, new AttributeValue {
                N = user.FailedLoginAttempts.ToString()
            });
            item.Add(FIELD_USERS_KYC_STATUS, new AttributeValue(user.KYCStatus));
            item.Add(FIELD_USERS_KYC_TIMESTAMP, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.KCYTimestamp)));
            item.Add(FIELD_USERS_MAX_DAILY_SPENDING_AMOUNT, new AttributeValue {
                N = user.MaxDailySpendingAmount.ToString()
            });
            item.Add(FIELD_USERS_NEW_MAX_DAILY_SPENDING_AMOUNT, new AttributeValue {
                N = user.NewMaxDailySpendingAmount.ToString()
            });
            item.Add(FIELD_USERS_NEW_MAX_DAILY_SPENDING_AMOUNT_TIME, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.NewMaxDailySpendingAmountTime)));
            item.Add(FIELD_USERS_MAX_TIME_LOGGED_IN, new AttributeValue {
                N = user.MaxTimeLoggedIn.ToString()
            });
            item.Add(FIELD_USERS_NEW_MAX_TIME_LOGGED_IN, new AttributeValue {
                N = user.NewMaxTimeLoggedIn.ToString()
            });
            item.Add(FIELD_USERS_NEW_MAX_TIME_LOGGED_IN_TIME, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.NewMaxTimeLoggedInTime)));
            item.Add(FIELD_USERS_EXCLUDE_UNTIL, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.ExcludeUntil)));
            item.Add(FIELD_USERS_NEW_EXCLUDE_UNTIL, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.NewExcludeUntil)));
            item.Add(FIELD_USERS_NEW_EXCLUDE_UNTIL_TIME, new AttributeValue(APIHelper.APIDateTimeStringFromDateTime(user.NewExcludeUntilTime)));
            item.Add(FIELD_USERS_PERMISSIONS, new AttributeValue {
                SS = user.Permissions
            });
            PutItemResponse putResponse = await dbClient.PutItemAsync(DATASET_USERS, item);

            Debug.AssertValid(putResponse);
            //??++Check response?
        }