コード例 #1
0
        public void Add(Contact contact)
        {
            PutItemRequest request = new PutItemRequest();

            request.TableName = "Contacts";
            request.Item      = new Dictionary <string, AttributeValue>()
            {
                { "MobileNumber", new AttributeValue {
                      S = contact.MobileNumber
                  } },
            };

            foreach (string key in contact.OtherDetails.AllKeys)
            {
                request.Item.Add(key, new AttributeValue {
                    S = (string)contact.OtherDetails[key]
                });
            }

            var response = client.PutItemAsync(request).Result;
        }
コード例 #2
0
        public async Task <ServiceTask> CreateTaskAsync()
        {
            var now     = DateTimeOffset.Now;
            var taskId  = Guid.NewGuid();
            var request = new PutItemRequest
            {
                TableName = _tableName,
                Item      = new Dictionary <string, AttributeValue>
                {
                    { "TaskId", new AttributeValue {
                          S = taskId.ToString()
                      } },
                    { "Status", new AttributeValue {
                          S = ServiceTaskStatus.Pending.ToString()
                      } },
                    { "Created", new AttributeValue {
                          S = now.ToString()
                      } },
                    { "LastUpdated", new AttributeValue {
                          S = now.ToString()
                      } },
                }
            };

            var response = await _client.PutItemAsync(request);

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                return(new ServiceTask()
                {
                    Created = now,
                    LastUpdated = now,
                    ResourceId = null,
                    Status = ServiceTaskStatus.Pending,
                    TaskId = taskId
                });
            }

            return(null);
        }
コード例 #3
0
        public virtual void CreateAccountItem(AmazonDynamoDBClient ddbClient, string tableName, Account account)
        {
            // Create the request
            var putItemRequest = new PutItemRequest
            {
                TableName = tableName,
                Item      = new Dictionary <string, AttributeValue>
                {
                    { "Company", new AttributeValue {
                          S = account.Company
                      } },
                    { "Email", new AttributeValue {
                          S = account.Email
                      } }
                }
            };

            // Only add attributes if the coresponding property in the account object is not empty.
            if (!String.IsNullOrEmpty(account.First))
            {
                putItemRequest.Item.Add("First", new AttributeValue {
                    S = account.First
                });
            }
            if (!String.IsNullOrEmpty(account.Last))
            {
                putItemRequest.Item.Add("Last", new AttributeValue {
                    S = account.Last
                });
            }
            if (!String.IsNullOrEmpty(account.Age))
            {
                putItemRequest.Item.Add("Age", new AttributeValue {
                    N = account.Age
                });
            }

            // Submit the request
            ddbClient.PutItem(putItemRequest);
        }
コード例 #4
0
        public async Task AddAsync(Habit item)
        {
            var request = new PutItemRequest()
            {
                TableName = Constants.HabitTableName,
                Item      = new Dictionary <string, AttributeValue>()
                {
                    { "TeamId", new AttributeValue()
                      {
                          S = item.TeamId
                      } },
                    { "HabitId", new AttributeValue()
                      {
                          S = item.HabitId
                      } },
                    { "Name", new AttributeValue()
                      {
                          S = item.Name
                      } },
                    { "StartDate", new AttributeValue()
                      {
                          S = item.StartDate.ToString()
                      } },
                    { "EndDate", new AttributeValue()
                      {
                          S = item.EndDate.ToString()
                      } },
                    { "Status", new AttributeValue()
                      {
                          S = item.Status.ToString()
                      } },
                    { "Notes", new AttributeValue()
                      {
                          S = item.Notes
                      } }
                }
            };

            await _dbClient.PutItemAsync(request);
        }
コード例 #5
0
        public async Task <Result> AddItems(int iteration)
        {
            var request = new PutItemRequest
            {
                TableName = "Benchmarking",
                Item      = new Dictionary <string, AttributeValue>
                {
                    { "Id", new AttributeValue {
                          N = "0"
                      } },
                    { "Property1", new AttributeValue("TEST") },
                    { "Property2", new AttributeValue("TEST") },
                    { "Property3", new AttributeValue("TEST") },
                    { "Property4", new AttributeValue("TEST") },
                }
            };
            var result    = new Result();
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            for (int i = 0; i < iteration; ++i)
            {
                request.Item["Id"] = new AttributeValue {
                    N = $"{i}"
                };

                await amazonDynamoDB.PutItemAsync(request);
            }

            stopwatch.Stop();

            result.Count       = iteration;
            result.TimeTaken   = stopwatch.Elapsed;
            result.Description = $"Add {iteration} items to table";
            result.Service     = repositoryName;
            result.Method      = "Add";

            return(result);
        }
コード例 #6
0
        public async Task UploadData()
        {
            using (var s3Response = await _s3Service.GetObjectAsync("us-west-2-aws-staging", "awsu-ilt/AWS-100-DEV/v2.2/binaries/input/lab-3-dynamoDB/InfectionsData.csv"))
            {
                using (var reader = new StreamReader(s3Response.ResponseStream))
                {
                    var line = reader.ReadLine();

                    while ((line = reader.ReadLine()) != null)
                    {
                        var data = line.Split(",");
                        try
                        {
                            if (!data[0].ToLower().Equals("patientid"))
                            {
                                var requestDiseaseListing = new PutItemRequest
                                {
                                    TableName = Constants.TableName,
                                    Item      = new Dictionary <string, AttributeValue>()
                                    {
                                        { Constants.PatientId, new AttributeValue(data[0]) },
                                        { Constants.City, new AttributeValue(data[1]) },
                                        { Constants.Date, new AttributeValue(data[2]) },
                                    }
                                };
                                await _dbService.PutItemAsync(requestDiseaseListing);

                                Console.WriteLine("Added item:" + line);
                            }
                        }
                        catch (AmazonDynamoDBException ex)
                        {
                            Console.WriteLine("Failed to create item");
                            Console.WriteLine(ex.Message);
                            Console.WriteLine(ex.InnerException.Message);
                        }
                    }
                }
            }
        }
コード例 #7
0
        private void CreateIDsFile()
        {
            Debug.Log("No file was found, creating a new info file");

            DynamoDBInfo info = new DynamoDBInfo();
            info.listOfIndexes = new List<int>();
            info.backupListOfIndexes = new List<int>();

            info.lastIdUsed = 000000000000000000; // 18 zeros
            info.listOfIndexes.Add(info.lastIdUsed);
            info.backupListOfIndexes = info.listOfIndexes;

            string json = JsonUtility.ToJson(info);

            var request = new PutItemRequest
            {
                TableName = DatabaseInfo.info_tableName,
                Item = new Dictionary<string, AttributeValue>
                {
                    { DatabaseInfo.info_pKey, new AttributeValue { N = DatabaseInfo.info_key} },
                    { DatabaseInfo.info_jsonFile, new AttributeValue{ S = json} }
                }
            };

            var response = client.PutItemAsync(request);
            
            if(response.Exception == null) Debug.Log("Info file has been uploaded successfully!");
            /*
            client.PutItemAsync(request, (result) =>
            {
                if (result.Exception != null)
                {
                    Debug.Log(result.Exception.Message);
                    return;
                }
                // else, the item has successfully been uploaded
                else Debug.Log("Info file has been uploaded successfully!");

            }, null);*/
        }
コード例 #8
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);
        }
コード例 #9
0
        // snippet-end:[DynamoDB.dotnetv3.dynamodb-basics.CreateTable]

        // snippet-start:[DynamoDB.dotnetv3.dynamodb-basics.PutItem]

        /// <summary>
        /// Adds a new item to the table.
        /// </summary>
        /// <param name="client">An initialized Amazon DynamoDB client object.</param>
        /// <param name="newMovie">A Movie object containing informtation for
        /// the movie to add to the table.</param>
        /// <param name="tableName">The name of the table where the item will be added.</param>
        /// <returns>A Boolean value that indicates the results of adding the item.</returns>
        public static async Task <bool> PutItemAsync(AmazonDynamoDBClient client, Movie newMovie, string tableName)
        {
            var item = new Dictionary <string, AttributeValue>
            {
                ["title"] = new AttributeValue {
                    S = newMovie.Title
                },
                ["year"] = new AttributeValue {
                    N = newMovie.Year.ToString()
                },
            };

            var request = new PutItemRequest
            {
                TableName = tableName,
                Item      = item,
            };

            var response = await client.PutItemAsync(request);

            return(response.HttpStatusCode == System.Net.HttpStatusCode.OK);
        }
コード例 #10
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);
        }
コード例 #11
0
        public async Task AddLeaderBoardEntry(String initials)
        {
            var count   = GetLeaderBoard().Result.Count;
            var request = new PutItemRequest
            {
                TableName = DyanmoTable,
                Item      = new Dictionary <string, AttributeValue>()
                {
                    { "id", new AttributeValue {
                          N = (count + 1).ToString()
                      } },
                    { "initials", new AttributeValue {
                          S = initials
                      } },
                    { "dateSubmitted", new AttributeValue {
                          S = DateTime.UtcNow.ToString("MM-dd-yyyy")
                      } }
                }
            };

            var result = await DynamoClient.PutItemAsync(request);
        }
コード例 #12
0
        /*----------------------------------- CRUD -----------------------------------------------*/
        // https://docs.aws.amazon.com/pt_br/mobile/sdkforxamarin/developerguide/dynamodb-integration-lowlevelapi.html

        private async void SalvarItem()
        {
            // Create a client
            AmazonDynamoDBClient client = new AmazonDynamoDBClient(awsCredentials, awsRegion);

            // Define item attributes
            Dictionary <string, AttributeValue> attributes = new Dictionary <string, AttributeValue>
            {
                // Author is hash-key
                ["Author"] = new AttributeValue {
                    S = "Mark Twain"
                },
                ["Title"] = new AttributeValue {
                    S = "The Adventures of Tom Sawyer"
                },
                ["PageCount"] = new AttributeValue {
                    N = "275"
                },
                ["Price"] = new AttributeValue {
                    N = "10.00"
                },
                ["Id"] = new AttributeValue {
                    N = "10"
                },
                ["ISBN"] = new AttributeValue {
                    S = "111-1111111"
                }
            };

            // Create PutItem request
            PutItemRequest request = new PutItemRequest
            {
                TableName = "Books",
                Item      = attributes
            };

            // Issue PutItem request
            var response = await client.PutItemAsync(request);
        }
コード例 #13
0
        private async Task UpdateAmazonDB()
        {
            var dbClient   = new AmazonDynamoDBClient(cognitoCred, Amazon.RegionEndpoint.USEast1);
            var addRequest = new PutItemRequest()
            {
                TableName = "Notes",
                Item      = new Dictionary <string, AttributeValue>
                {
                    { "courseName", new AttributeValue {
                          S = course.courseName
                      } },
                    { "noteName", new AttributeValue {
                          S = course.noteName
                      } },
                    { "notes", new AttributeValue {
                          S = course.notes
                      } }
                }
            };

            await dbClient.PutItemAsync(addRequest);
        }
コード例 #14
0
        public async Task <PutItemResponse> CreateNotepad(CreateRequest request, ILambdaContext context)
        {
            var response = await client.DescribeTableAsync(new DescribeTableRequest
            {
                TableName = tableName
            });

            Console.WriteLine(response);

            var createItemRequest = new PutItemRequest
            {
                TableName = tableName,
                Item      = new Dictionary <string, AttributeValue>
                {
                    {
                        "Id",
                        new AttributeValue {
                            N = $"{request.Id}"
                        }
                    },
                    {
                        "Title",
                        new AttributeValue {
                            S = $"{request.Title}"
                        }
                    },
                    {
                        "Content",
                        new AttributeValue {
                            S = $"{request.Content}"
                        }
                    }
                }
            };

            var createItemResponse = await client.PutItemAsync(createItemRequest);

            return(createItemResponse);
        }
コード例 #15
0
        private async Task <Boolean> StoreContactToDynamoAsync(String caseReference, String contact, Boolean unitary)
        {
            String unitaryString = "false";

            if (unitary)
            {
                unitaryString = "true";
            }

            try
            {
                AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient(primaryRegion);
                PutItemRequest       dynamoRequest  = new PutItemRequest
                {
                    TableName = tableName,
                    Item      = new Dictionary <String, AttributeValue>
                    {
                        { "CaseReference", new AttributeValue {
                              S = caseReference
                          } },
                        { "InitialContact", new AttributeValue {
                              S = contact
                          } },
                        { "Unitary", new AttributeValue {
                              S = unitaryString
                          } }
                    }
                };
                await dynamoDBClient.PutItemAsync(dynamoRequest);

                return(true);
            }
            catch (Exception error)
            {
                Console.WriteLine("ERROR : StoreContactToDynamoDB :" + error.Message);
                Console.WriteLine(error.StackTrace);
                return(false);
            }
        }
コード例 #16
0
        public async void InsertToDynamoDbTable(int Id, int Number, string desc)
        {
            Console.WriteLine("Inserting Data");
            var request = new PutItemRequest
            {
                TableName = tablename,
                Item      = new Dictionary <string, AttributeValue>
                {
                    { "Id", new AttributeValue {
                          N = Id.ToString()
                      } },
                    { "Number", new AttributeValue {
                          N = Number.ToString()
                      } },
                    { "Description", new AttributeValue {
                          S = desc.ToString()
                      } }
                }
            };

            await _dynamoDbClient.PutItemAsync(request);
        }
コード例 #17
0
 public async Task DynamoDbPutCacheChannelAsync(string channelId, string playlistTitle, ChannelSnippet channelSnippet)
 {
     var dateNow    = DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds.ToString(CultureInfo.InvariantCulture);
     var putRequest = new PutItemRequest {
         TableName = _dynamoDbPlaylistTableName,
         Item      = new Dictionary <string, AttributeValue> {
             { "channelId", new AttributeValue {
                   S = channelId
               } },
             { "playlistTitle", new AttributeValue {
                   S = playlistTitle
               } },
             { "channelSnippet", new AttributeValue {
                   S = JsonConvert.SerializeObject(channelSnippet.ToChannelSnippetDb())
               } },
             { "timestamp", new AttributeValue {
                   N = dateNow
               } }
         }
     };
     await _dynamoDbClient.PutItemAsync(putRequest);
 }
コード例 #18
0
        /// <summary>
        /// Add user connection to all rooms he belongs to (when logging in)
        /// </summary>
        /// <param name="userId">User who just logged in</param>
        /// <param name="connectionId">Connection id of this user</param>
        public async Task AddUserToHisRooms(string userId, string connectionId)
        {
            // retrieve rooms ids
            var queryRequest = new QueryRequest
            {
                TableName = _UsersRoomsTable,
                KeyConditionExpression    = $"NodeId = :partitionkeyval AND begins_with (TargetId, :sortkeyval)",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":partitionkeyval", new AttributeValue {
                          S = $"user-{userId}"
                      } },
                    { ":sortkeyval", new AttributeValue {
                          S = $"room"
                      } }
                },
                ProjectionExpression = "TargetId"
            };
            var queryResponse = await _DDBClient.QueryAsync(queryRequest);

            // add user to rooms
            foreach (var item in queryResponse.Items)
            {
                var putRequest = new PutItemRequest
                {
                    TableName = _RoomsConnectionsTable,
                    Item      = new Dictionary <string, AttributeValue>
                    {
                        { "RoomId", new AttributeValue {
                              S = item["TargetId"].S
                          } },
                        { "ConnectionId", new AttributeValue {
                              S = connectionId
                          } }
                    }
                };
                await _DDBClient.PutItemAsync(putRequest);
            }
        }
コード例 #19
0
        public async Task <ForroLevel> Insert(ForroLevel forroLevel)
        {
            var attributes = new Dictionary <string, AttributeValue>
            {
                [nameof(ForroLevel.ForroLevelId)] = new AttributeValue()
                {
                    N = forroLevel.ForroLevelId.ToString()
                },
                [nameof(ForroLevel.Name)] = new AttributeValue()
                {
                    S = forroLevel.Name
                }
            };

            if (!string.IsNullOrWhiteSpace(forroLevel.ImageUrl))
            {
                attributes.Add(nameof(ForroLevel.ImageUrl), new AttributeValue()
                {
                    S = forroLevel.ImageUrl
                });
            }

            if (!string.IsNullOrWhiteSpace(forroLevel.ThumbNailImageUrl))
            {
                attributes.Add(nameof(ForroLevel.ThumbNailImageUrl), new AttributeValue()
                {
                    S = forroLevel.ThumbNailImageUrl
                });
            }

            var request = new PutItemRequest()
            {
                TableName = ForroLevelTableName,
                Item      = attributes
            };
            var result = await _client.PutItemAsync(request);

            return(forroLevel);
        }
コード例 #20
0
        public async Task <bool> AcquireLock(string Id, CancellationToken cancellationToken)
        {
            try
            {
                var req = new PutItemRequest()
                {
                    TableName = _tableName,
                    Item      = new Dictionary <string, AttributeValue>
                    {
                        { "id", new AttributeValue(Id) },
                        { "lockOwner", new AttributeValue(_nodeId) },
                        { "expires", new AttributeValue()
                          {
                              N = Convert.ToString(new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds() + _ttl)
                          } }
                    },
                    ConditionExpression       = "attribute_not_exists(id) OR (expires < :expired)",
                    ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                    {
                        { ":expired", new AttributeValue()
                          {
                              N = Convert.ToString(new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds() + _jitter)
                          } }
                    }
                };

                var response = await _client.PutItemAsync(req, _cancellationTokenSource.Token);

                if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
                {
                    _localLocks.Add(Id);
                    return(true);
                }
            }
            catch (ConditionalCheckFailedException)
            {
            }
            return(false);
        }
コード例 #21
0
        public static async Task Main(string[] args)
        {
            AmazonDynamoDBClient client = new AmazonDynamoDBClient();

            var tableName = "TryDaxTable";

            string someData = new string('X', 1000);
            var    pkmax    = 10;
            var    skmax    = 10;

            for (var ipk = 1; ipk <= pkmax; ipk++)
            {
                Console.WriteLine($"Writing {skmax} items for partition key: {ipk}");
                for (var isk = 1; isk <= skmax; isk++)
                {
                    var request = new PutItemRequest()
                    {
                        TableName = tableName,
                        Item      = new Dictionary <string, AttributeValue>()
                        {
                            { "pk", new AttributeValue {
                                  N = ipk.ToString()
                              } },
                            { "sk", new AttributeValue {
                                  N = isk.ToString()
                              } },
                            { "someData", new AttributeValue {
                                  S = someData
                              } }
                        }
                    };

                    var response = await client.PutItemAsync(request);
                }
            }

            Console.WriteLine("Hit <enter> to continue...");
            Console.ReadLine();
        }
コード例 #22
0
        public static void AddItemToTable(AmazonDynamoDBClient dynamoDBClient, string[] infectionsDataAttrValues, string InfectionsTableName)
        {
            Debug.WriteLine(String.Format("RUNNING SOLUTION CODE: {0}! Follow the steps in the lab guide to replace this method with your own implementation.\n", "AddItemToTable"));
            var requestDiseaseListing = new PutItemRequest
            {
                TableName = InfectionsTableName,
                Item      = new Dictionary <string, AttributeValue>()
                {
                    { "PatientID", new AttributeValue {
                          S = infectionsDataAttrValues[0]
                      } },
                    { "City", new AttributeValue {
                          S = infectionsDataAttrValues[1]
                      } },
                    { "Date", new AttributeValue {
                          S = infectionsDataAttrValues[2]
                      } },
                }
            };

            dynamoDBClient.PutItem(requestDiseaseListing);
        }
コード例 #23
0
        /**
         * Add the item to the reservations data table
         *
         * @param reservationsDataAttrValues    Values to be inserted into the table
         */
        private static void AddItemToTable(string[] reservationsDataAttrValues)
        {
            // TODO 1: Replace the solution with your own code
            var request = new PutItemRequest
            {
                TableName = ReservationsTableName,
                Item      = new Dictionary <string, AttributeValue>()
                {
                    { "CustomerID", new AttributeValue {
                          S = reservationsDataAttrValues[0]
                      } },
                    { "City", new AttributeValue {
                          S = reservationsDataAttrValues[1]
                      } },
                    { "Date", new AttributeValue {
                          S = reservationsDataAttrValues[2]
                      } },
                }
            };

            dynamoDBClient.PutItem(request);
        }
コード例 #24
0
ファイル: QuotesService.cs プロジェクト: Morr0/Quotey
        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);
        }
コード例 #25
0
        private async void SendHeartbeat()
        {
            while (!_cancellationTokenSource.IsCancellationRequested)
            {
                try
                {
                    await Task.Delay(_heartbeat, _cancellationTokenSource.Token);

                    foreach (var item in _localLocks)
                    {
                        var req = new PutItemRequest
                        {
                            TableName = _tableName,
                            Item      = new Dictionary <string, AttributeValue>
                            {
                                { "id", new AttributeValue(item) },
                                { "lockOwner", new AttributeValue(_nodeId) },
                                { "expires", new AttributeValue()
                                  {
                                      N = Convert.ToString(new DateTimeOffset(DateTime.UtcNow).ToUnixTimeMilliseconds() + _ttl)
                                  } }
                            },
                            ConditionExpression       = "lockOwner = :nodeId",
                            ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                            {
                                { ":nodeId", new AttributeValue(_nodeId) }
                            }
                        };

                        await _client.PutItemAsync(req, _cancellationTokenSource.Token);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(default(EventId), ex, ex.Message);
                }
            }
        }
コード例 #26
0
ファイル: Function.cs プロジェクト: ludoguer/BlazorVotingDemo
        public async Task <APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            try
            {
                // Using JObject instead of APIGatewayProxyRequest till APIGatewayProxyRequest gets updated with DomainName and ConnectionId
                var connectionId = request.RequestContext.ConnectionId;
                context.Logger.LogLine($"ConnectionId: {connectionId}");

                var ddbRequest = new PutItemRequest
                {
                    TableName = Constants.TABLE_NAME,
                    Item      = new Dictionary <string, AttributeValue>
                    {
                        { Constants.ConnectionIdField, new AttributeValue {
                              S = connectionId
                          } }
                    }
                };

                await _ddbClient.PutItemAsync(ddbRequest);

                return(new APIGatewayProxyResponse
                {
                    StatusCode = 200,
                    Body = "Connected."
                });
            }
            catch (Exception e)
            {
                context.Logger.LogLine("Error connecting: " + e.Message);
                context.Logger.LogLine(e.StackTrace);
                return(new APIGatewayProxyResponse
                {
                    StatusCode = 500,
                    Body = $"Failed to connect: {e.Message}"
                });
            }
        }
コード例 #27
0
        public static void PutItem(AmazonDynamoDBClient client, int[] s, string endpoint, string body)
        {
            const string tableName = "testTable";
            Random       random    = new Random();
            DateTime     d         = DateTime.Now;
            var          request   = new PutItemRequest
            {
                TableName = tableName,
                Item      = new Dictionary <string, AttributeValue>()
                {
                    { "ID", new AttributeValue {
                          S = body + "--" + endpoint
                      } },
                    { "Title", new AttributeValue {
                          S = "123"
                      } },
                    { "Time", new AttributeValue {
                          S = d.ToString(CultureInfo.InvariantCulture).ToString()
                      } },
                    { "Price", new AttributeValue {
                          N = random.Next(0, 100).ToString()
                      } },
                    {
                        "Authors",
                        new AttributeValue
                        {
                            SS = new List <string> {
                                "aotuo", "zhang"
                            }
                        }
                    }
                }
            };

            client.PutItem(request);
            Console.WriteLine("DynamoDB get message " + endpoint + s[0]);
            // s[0]++;
        }
コード例 #28
0
 /// <summary>
 /// Adds a record to the DynamoDBB MessagesTable containing the message, the room id,
 /// the user id and the date measured in a UNIX Epoch time system.
 /// </summary>
 /// <param name="message">The message</param>
 /// <param name="roomId">The room in which the message was sent</param>
 /// <param name="user">Author of the message</param>
 /// <returns></returns>
 public async Task PutMessage(string message, string roomId, string user, string date)
 {
     var putRequest = new PutItemRequest
     {
         TableName = _MessagesTable,
         Item      = new Dictionary <string, AttributeValue>
         {
             { "RoomId", new AttributeValue {
                   S = $"{roomId}"
               } },
             { "DateId", new AttributeValue {
                   N = date
               } },
             { "UserId", new AttributeValue {
                   S = user
               } },
             { "Message", new AttributeValue {
                   S = message
               } }
         }
     };
     await _DDBClient.PutItemAsync(putRequest);
 }
コード例 #29
0
        public async Task PutRecordAsync(string source, string target)
        {
            var guid    = Guid.NewGuid();
            var request = new PutItemRequest
            {
                TableName = tableName,
                Item      = new Dictionary <string, AttributeValue>()
                {
                    { "Id", new AttributeValue {
                          S = guid.ToString()
                      } },
                    { "SourceProject", new AttributeValue {
                          S = source
                      } },
                    { "TargetProject", new AttributeValue {
                          S = target
                      } }
                }
            };
            await dbClient.PutItemAsync(request);

            Console.WriteLine($"inserted link: {source} -> {target}");
        }
コード例 #30
0
ファイル: DynamoDb.cs プロジェクト: LVladymyr/AwsLocalstack
 private async Task PutItem()
 {
     var putItemRequest = new PutItemRequest()
     {
         TableName = TableName,
         Item      =
         {
             {
                 "Id", new AttributeValue()
                 {
                     N = "42"
                 }
             },
             {
                 "Name", new AttributeValue()
                 {
                     S = "Get Up Early"
                 }
             }
         }
     };
     await _dynamoClient.PutItemAsync(putItemRequest);
 }