PutItem() public method

Creates a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item. You can perform a conditional put operation (add a new item if one with the specified primary key doesn't exist), or replace an existing item if it has certain attribute values.

In addition to putting an item, you can also return the item's attribute values in the same operation, using the ReturnValues parameter.

When you add an item, the primary key attribute(s) are the only required attributes. Attribute values cannot be null. String and Binary type attributes must have lengths greater than zero. Set type attributes cannot be empty. Requests with empty values will be rejected with a ValidationException exception.

You can request that PutItem return either a copy of the original item (before the update) or a copy of the updated item (after the update). For more information, see the ReturnValues description below.

To prevent a new item from replacing an existing item, use a conditional expression that contains the attribute_not_exists function with the name of the attribute being used as the partition key for the table. Since every record must contain that attribute, the attribute_not_exists function will only succeed if no matching item exists.

For more information about using this API, see Working with Items in the Amazon DynamoDB Developer Guide.

/// A condition specified in the operation could not be evaluated. /// /// An error occurred on the server side. /// /// An item collection is too large. This exception is only returned for tables that have /// one or more local secondary indexes. /// /// Your request rate is too high. The AWS SDKs for DynamoDB automatically retry requests /// that receive this exception. Your request is eventually successful, unless your retry /// queue is too large to finish. Reduce the frequency of requests and use exponential /// backoff. For more information, go to Error /// Retries and Exponential Backoff in the Amazon DynamoDB Developer Guide. /// /// The operation tried to access a nonexistent table or index. The resource might not /// be specified correctly, or its status might not be ACTIVE. ///
public PutItem ( PutItemRequest request ) : PutItemResponse
request Amazon.DynamoDBv2.Model.PutItemRequest Container for the necessary parameters to execute the PutItem service method.
return Amazon.DynamoDBv2.Model.PutItemResponse
        public virtual void AddImage(AmazonDynamoDBClient dynamoDbClient, string tableName, AmazonS3Client s3Client, string bucketName, string imageKey, string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {

                    // Create the upload request
                    var putObjectRequest = new PutObjectRequest
                    {
                        BucketName = bucketName,
                        Key = imageKey,
                        FilePath = filePath
                    };

                    // Upload the object
                    s3Client.PutObject(putObjectRequest);

                    // Create the put item request to submit to DynamoDB
                    var putItemRequest = new PutItemRequest
                    {
                        TableName = tableName,
                        Item = new Dictionary<string, AttributeValue>
                        {
                            {"Key", new AttributeValue {S = imageKey}},
                            {"Bucket", new AttributeValue {S = bucketName}}
                        }
                    };

                    dynamoDbClient.PutItem(putItemRequest);
                    _Default.LogMessageToPage("Added imageKey: {0}", imageKey);
                }
                else
                {
                    _Default.LogMessageToPage("Skipped imageKey: {0}", imageKey);
                }
            }
            catch (Exception ex)
            {
                _Default.LogMessageToPage("AddImage Error: {0}", ex.Message);
            }
        }
Beispiel #2
0
        public bool StorePin(Dictionary<string, object> pn)
        {
            var config = new AmazonDynamoDBConfig();
            config.ServiceURL = System.Configuration.ConfigurationManager.AppSettings["ServiceURL"];
            client = new AmazonDynamoDBClient(config);

            try
            {
                PutItemRequest putReq = new PutItemRequest
                {
                    TableName = "Pin",
                    Item = new Dictionary<string, AttributeValue>() {
                        { "Owner", new AttributeValue { S = pn["OwnerID"].ToString() } } ,
                        { "Title", new AttributeValue { S = pn["Title"].ToString() } } ,
                        { "PinDate", new AttributeValue { N = pn["PinDate"].ToString() } } ,
                        { "Latitude", new AttributeValue { S = pn["Latitude"].ToString() } } ,
                        { "Longitude", new AttributeValue { S = pn["Longitude"].ToString() } } ,
                        { "Images", new AttributeValue { SS = (List<string>)pn["Images"] } } ,
                        { "HeadshotURL", new AttributeValue { S = pn["OwnerHeadshot"].ToString() } } ,
                        { "UserName", new AttributeValue { S = pn["OwnerName"].ToString() } } ,
                        { "LastSyncDate", new AttributeValue { N = pn["LastSyncDate"].ToString() } }
                    }
                };

                PutItemResponse response = client.PutItem(putReq);
            }
            catch (AmazonDynamoDBException e) { Console.WriteLine(e.Message); }
            catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
            catch (Exception e) { Console.WriteLine(e.Message); }

            return true;
        }
Beispiel #3
0
        public bool InsertUser(Dictionary<string, object> us)
        {
            var config = new AmazonDynamoDBConfig();
            config.ServiceURL = System.Configuration.ConfigurationManager.AppSettings["ServiceURL"];
            client = new AmazonDynamoDBClient(config);

            try
            {
                PutItemRequest putReq = new PutItemRequest
                {
                    TableName = "User",
                    Item = new Dictionary<string, AttributeValue>() {
                        { "UserID", new AttributeValue { S = us["userID"].ToString() } } ,
                        { "UserName", new AttributeValue { S = us["userName"].ToString() } } ,
                        { "HeadshotURL", new AttributeValue { S = us["headshotURL"].ToString() } } ,
                        { "IsPayUser", new AttributeValue { S = us["IsPayUser"].ToString() } } ,
                        { "RegistDate", new AttributeValue { N = us["registDate"].ToString() } } ,
                        { "LastLoginDate", new AttributeValue { N = us["lastLoginDate"].ToString() } } ,
                        { "LastSyncDate", new AttributeValue { N = us["lastSyncDate"].ToString() } }
                    }
                };

                PutItemResponse response = client.PutItem(putReq);
            }
            catch (AmazonDynamoDBException e) { Console.WriteLine(e.Message); }
            catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
            catch (Exception e) { Console.WriteLine(e.Message); }

            //using (PinContext context = new PinContext(PinConnString))
            //{

            //    context.Entry(us).State = EntityState.Added;

            //    context.SaveChanges();
            //}
            return true;
        }
        private void PutSample()
        {
            {
                #region PutItem Sample 1

                // Create a client
                AmazonDynamoDBClient client = new AmazonDynamoDBClient();

                // Define item attributes
                Dictionary<string, AttributeValue> attributes = new Dictionary<string, AttributeValue>();
                // Author is hash-key
                attributes["Author"] = new AttributeValue { S = "Mark Twain" };
                // Title is range-key
                attributes["Title"] = new AttributeValue { S = "The Adventures of Tom Sawyer" };
                // Other attributes
                attributes["Year"] = new AttributeValue { N = "1876" };
                attributes["Setting"] = new AttributeValue { S = "Missouri" };
                attributes["Pages"] = new AttributeValue { N = "275" };
                attributes["Genres"] = new AttributeValue
                {
                    SS = new List<string> { "Satire", "Folk", "Children's Novel" }
                };

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

                // Issue PutItem request
                client.PutItem(request);

                #endregion
            }
        }
        protected void submitButton_Click(object sender, EventArgs e)
        {
            if (inId.Value != "" && inQid.Value != "" && txtQuestion.Text != "" && txtCorrectAnswer.Text != "" && txtOptions0.Text != "")
            {
                string message = "";
                int iCount = 0;
                int iNewCount = 0;
                List<string> txtOptionsList = new List<string>();
                foreach (TextBox textBox in divTest.Controls.OfType<TextBox>())
                {
                    if (!string.IsNullOrEmpty(textBox.Text))
                    {
                        {
                            if (textBox.ID == "txtOptions" + iNewCount)
                            {
                                iNewCount = iNewCount + 1;
                                message = textBox.Text;
                            }
                            txtOptionsList.Add(message);
                        }
                    }
                }

                string alpha = "ABCDEFGHIJKLMNOPQRSTUVQXYZ";

                Dictionary<string, AttributeValue> attValue = new Dictionary<string, AttributeValue>();
                int alphabet = 0;
                for (int i = 0; i <= txtOptionsList.Count - 1; i++)
                {
                    {
                        AttributeValue attribute = new AttributeValue();
                        attribute.S = txtOptionsList[i];
                        attValue.Add(alpha[alphabet].ToString().ToLower(), attribute);
                        alphabet = alphabet + 1;
                    }
                }
                AmazonDynamoDBClient client = new AmazonDynamoDBClient();
                // Amazon.DynamoDBv2.DocumentModel.Table table = Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(client, "Event");		+                // Amazon.DynamoDBv2.DocumentModel.Table table = Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(client, "Event");
                client.PutItem("QuizQuestion", new Dictionary<string, AttributeValue>

            {
            { "eventId", new AttributeValue { S = inId.Value } },
            { "questionId", new AttributeValue { S = inQid.Value } },
            { "question", new AttributeValue { S = txtQuestion.Text } },
            { "questionType", new AttributeValue { S = ddlQuestionType.SelectedItem.Text } },
            { "correctAnswer", new AttributeValue { S = txtCorrectAnswer.Text } },
            //{ "endTime", new AttributeValue { S = "28/10/2017 4:00 PM" } },
            //{ "startTime", new AttributeValue { S = "28/10/2016 4:00 PM" } },
            { "options", new AttributeValue {
            M = attValue
            }
            }
            });
                string script = "alert(\"Successfully created the Question.\");";
                ScriptManager.RegisterStartupScript(this, GetType(),
                                      "ServerControlScript", script, true);

                Response.Redirect("Question.aspx");

            }
            else
            {
                string script = "alert(\"Please fill all the data.\");";
                ScriptManager.RegisterStartupScript(this, GetType(),
                                      "ServerControlScript", script, true);
            }
        }
        public void Can_put_item_with_null_value()
        {
            var db = new AmazonDynamoDBClient("keyId", "key", new AmazonDynamoDBConfig
            {
                ServiceURL = "http://localhost:8000",
            });

            try
            {
                db.DeleteTable(new DeleteTableRequest
                {
                    TableName = "Test",
                });

                Thread.Sleep(1000);
            }
            catch (Exception) { /*ignore*/ }

            db.CreateTable(new CreateTableRequest
            {
                TableName = "Test",
                KeySchema = new List<KeySchemaElement>
                {
                    new KeySchemaElement
                    {
                        AttributeName = "Id",
                        KeyType = "HASH"
                    }
                },
                AttributeDefinitions = new List<AttributeDefinition>
                {
                    new AttributeDefinition
                    {
                        AttributeName = "Id",
                        AttributeType = "N",
                    }
                },
                ProvisionedThroughput = new ProvisionedThroughput
                {
                    ReadCapacityUnits = 10,
                    WriteCapacityUnits = 5,
                }
            });

            Thread.Sleep(1000);

            db.PutItem(new PutItemRequest
            {
                TableName = "Test",
                Item = new Dictionary<string, AttributeValue>
                {
                    { "Id", new AttributeValue { N = "1" } },
                    { "Name", new AttributeValue { S = "Foo"} },
                    { "Empty", new AttributeValue { NULL = true } },
                }
            });

            var response = db.GetItem(new GetItemRequest
            {
                TableName = "Test",
                ConsistentRead = true,
                Key = new Dictionary<string, AttributeValue> {
                    { "Id", new AttributeValue { N = "1" } }
                }
            });

            Assert.That(response.IsItemSet);
            Assert.That(response.Item["Id"].N, Is.EqualTo("1"));
            Assert.That(response.Item["Name"].S, Is.EqualTo("Foo"));
            Assert.That(response.Item["Empty"].NULL);
        }
        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);
        }