Container for the parameters to the PutItem operation.

Creates a new item, or replaces an old item with a new item. If an item already exists in the specified table with the same primary key, the new item completely replaces the existing item. You can perform a conditional put (insert 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 .

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

NOTE: To prevent a new item from replacing an existing item, use a conditional put operation with Exists set to false for the primary key attribute, or attributes.

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

Inheritance: AmazonDynamoDBv2Request
Ejemplo n.º 1
0
        /// <summary>
        /// Just here to save my test code for adding records in case I end up needing something for it
        /// </summary>
        public void InsertRecords()
        {
            Dictionary <string, string> result = null;

            AmazonDynamoDBClient amazonDynamoDBClient = new AmazonDynamoDBClient("AKIAINS26T6JVAGVNZ2A", "qolTppubmJ5XWBl1UtHE42HPs7lULGgF2t8okG0J", RegionEndpoint.USEast1);

            Dictionary <string, AttributeValue> attributes = new Dictionary <string, AttributeValue>();
            AttributeCollection collection = new AttributeCollection();

            attributes.Add("1", new AttributeValue()
            {
                N = "1"
            });                                                    // Primary key, need to look into getting this updated automatically
            attributes.Add("firstrecord", new AttributeValue("First"));
            attributes.Add("secondrecord", new AttributeValue("secondrecord"));

            // Create PutItem request
            Amazon.DynamoDBv2.Model.PutItemRequest request = new Amazon.DynamoDBv2.Model.PutItemRequest("Test", attributes);
            try
            {
                // Issue PutItem request
                amazonDynamoDBClient.PutItem(request);
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 2
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);
        }
        public void SaveNewVideo()
        {
            var client = new AmazonDynamoDBClient();
            var request = new PutItemRequest();
            request.TableName = "Local.Area";
            request.Item = new Dictionary<string, AttributeValue>();

            var value1 = new AttributeValue
            {
               S = "103"

            };

            request.Item.Add("Description", value1);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates a user and sets the values in the GCLogin DynamoDB Table
        /// </summary>
        /// <param name="email">User's email address</param>
        /// <param name="password">Users Password</param>
        /// <returns>0 if successful, otherwise > 0</returns>
        public int CreateUser(GCUser.LoginInfo loginInfo, string password)
        {
            int response = (int)DBEnum.DBResponseCodes.DEFAULT_VALUE;
            PutItemRequest request = new PutItemRequest();
            GetItemResponse giResponse = new GetItemResponse(); // created just to dump response but won't be used ever

            // If user does NOT exist...Create User
            if ((int)DBEnum.DBResponseCodes.DOES_NOT_EXIST == dbManager.GetItem(primaryKey, loginInfo.Email, TABLE, out giResponse))
            {
                try  // Try to create User
                {
                    string accountGuid = Guid.NewGuid().ToString(); // AccountId GUID
                    string emailVerificationGuid = Guid.NewGuid().ToString(); // Email verification hash
                    char[] delimeter = { ':' }; // delimeter for password hashing
                    string[] split = pwh.CreateHash(password).Split(delimeter); // create a hash based on the pw and split it using delimeter

                    // set table to "GCLogin"
                    request.TableName = TABLE;
                    // set items to add
                    request.Item.Add(primaryKey, new AttributeValue { S = loginInfo.Email });
                    request.Item.Add(ACCOUNT_ID, new AttributeValue { S = accountGuid });
                    request.Item.Add(ENCRYPTION, new AttributeValue { S = split[(int)DBEnum.GCLoginIndex.ENCRYPTION_INDEX] });
                    request.Item.Add(ITERATIONS, new AttributeValue { S = split[(int)DBEnum.GCLoginIndex.ITERATION_INDEX] });
                    request.Item.Add(SALT_HASH, new AttributeValue { S = split[(int)DBEnum.GCLoginIndex.SALT_INDEX] });
                    request.Item.Add(PASSWORD_HASH, new AttributeValue { S = split[(int)DBEnum.GCLoginIndex.PBKDF2_INDEX] });
                    request.Item.Add(EMAIL_VERIFICATION_GUID, new AttributeValue { S = emailVerificationGuid });
                    request.Item.Add(ACCOUNT_VALIDATED, new AttributeValue { BOOL = false });
                    // put items in DB
                    dbManager.PutItem(request);

                    response = (int)DBEnum.DBResponseCodes.SUCCESS;
                    logger.WriteLog(GameLogger.LogLevel.Debug, string.Format("Created user {0} in Table {1}", loginInfo.Email, TABLE));
                }
                catch  // If creation fails
                {
                    response = (int)DBEnum.DBResponseCodes.DYNAMODB_EXCEPTION;
                    logger.WriteLog(GameLogger.LogLevel.Error, string.Format("Failed to create user {0} due to DynamoDB Exception.", loginInfo.Email));
                }
            }
            // if user DOES exist or error
            else
            {
                logger.WriteLog(GameLogger.LogLevel.Debug, string.Format("Failed to create user {0}, it already exists or another error happened.", loginInfo.Email));
                response = (int)DBEnum.DBResponseCodes.USER_EXIST;
            }

            return response;
        }
Ejemplo n.º 5
0
        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);
            }
        }
Ejemplo n.º 6
0
 public static void InsertData1()
 {
     for (int i = 11; i <= 20; i++)
     {
         var Req = new PutItemRequest
         {
             TableName = "TestID",
             Item = new Dictionary<string, AttributeValue>() {
             {"Id",new AttributeValue{N=i.ToString()}},
             {"Msg",new AttributeValue{S="Test"+i}},
             {"Memo",new AttributeValue{S="Memo  "+i}}
             }
         };
         var Rsp = client.PutItem(Req);
     }
 }
        internal PutItemResponse PutItem(PutItemRequest request)
        {
            var marshaller = new PutItemRequestMarshaller();
            var unmarshaller = PutItemResponseUnmarshaller.Instance;

            return Invoke<PutItemRequest,PutItemResponse>(request, marshaller, unmarshaller);
        }
 /// <summary>
 /// Initiates the asynchronous execution of the PutItem operation.
 /// <seealso cref="Amazon.DynamoDBv2.AmazonDynamoDB.PutItem"/>
 /// </summary>
 /// 
 /// <param name="putItemRequest">Container for the necessary parameters to execute the PutItem operation on AmazonDynamoDBv2.</param>
 /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
 /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 /// 
 /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutItem
 ///         operation.</returns>
 public IAsyncResult BeginPutItem(PutItemRequest putItemRequest, AsyncCallback callback, object state)
 {
     return invokePutItem(putItemRequest, callback, state, false);
 }
 /// <summary>
 /// 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. 
 /// 
 ///  
 /// <para>
 /// In addition to putting an item, you can also return the item's attribute values in
 /// the same operation, using the <i>ReturnValues</i> parameter.
 /// </para>
 ///  
 /// <para>
 /// 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 <i>ValidationException</i> exception.
 /// </para>
 ///  
 /// <para>
 /// You can request that <i>PutItem</i> 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 <i>ReturnValues</i> description below.
 /// </para>
 ///  <note> 
 /// <para>
 /// To prevent a new item from replacing an existing item, use a conditional put operation
 /// with <i>ComparisonOperator</i> set to <code>NULL</code> for the primary key attribute,
 /// or attributes.
 /// </para>
 ///  </note> 
 /// <para>
 /// For more information about using this API, see <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html">Working
 /// with Items</a> in the <i>Amazon DynamoDB Developer Guide</i>.
 /// </para>
 /// </summary>
 /// <param name="tableName">The name of the table to contain the item.</param>
 /// <param name="item">A map of attribute name/value pairs, one for each attribute. Only the primary key attributes are required; you can optionally provide other attribute name-value pairs for the item. You must provide all of the attributes for the primary key. For example, with a hash type primary key, you only need to provide the hash attribute. For a hash-and-range type primary key, you must provide both the hash attribute and the range attribute. If you specify any attributes that are part of an index key, then the data types for those attributes must match those of the schema in the table's attribute definition. For more information about primary keys, see <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModelPrimaryKey">Primary Key</a> in the <i>Amazon DynamoDB Developer Guide</i>. Each element in the <i>Item</i> map is an <i>AttributeValue</i> object.</param>
 /// <param name="returnValues">Use <i>ReturnValues</i> if you want to get the item attributes as they appeared before they were updated with the <i>PutItem</i> request. For <i>PutItem</i>, the valid values are: <ul> <li> <code>NONE</code> - If <i>ReturnValues</i> is not specified, or if its value is <code>NONE</code>, then nothing is returned. (This setting is the default for <i>ReturnValues</i>.) </li> <li> <code>ALL_OLD</code> - If <i>PutItem</i> overwrote an attribute name-value pair, then the content of the old item is returned. </li> </ul></param>
 /// 
 /// <returns>The response from the PutItem service method, as returned by DynamoDB.</returns>
 /// <exception cref="Amazon.DynamoDBv2.Model.ConditionalCheckFailedException">
 /// A condition specified in the operation could not be evaluated.
 /// </exception>
 /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException">
 /// An error occurred on the server side.
 /// </exception>
 /// <exception cref="Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException">
 /// An item collection is too large. This exception is only returned for tables that have
 /// one or more local secondary indexes.
 /// </exception>
 /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException">
 /// The request rate is too high, or the request is too large, for the available throughput
 /// to accommodate. The AWS SDKs automatically retry requests that receive this exception;
 /// therefore, your request will eventually succeed, unless the request is too large or
 /// your retry queue is too large to finish. Reduce the frequency of requests by using
 /// the strategies listed in <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#APIRetries">Error
 /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>.
 /// </exception>
 /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException">
 /// The operation tried to access a nonexistent table or index. The resource might not
 /// be specified correctly, or its status might not be <code>ACTIVE</code>.
 /// </exception>
 public PutItemResponse PutItem(string tableName, Dictionary<string, AttributeValue> item, ReturnValue returnValues)
 {
     var request = new PutItemRequest();
     request.TableName = tableName;
     request.Item = item;
     request.ReturnValues = returnValues;
     return PutItem(request);
 }
		internal PutItemResponse PutItem(PutItemRequest request)
        {
            var task = PutItemAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return null;
            }
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Initiates the asynchronous execution of the PutItem operation.
 /// </summary>
 /// 
 /// <param name="request">Container for the necessary parameters to execute the PutItem operation on AmazonDynamoDBClient.</param>
 /// <param name="callback">An Action delegate that is invoked when the operation completes.</param>
 /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 public void PutItemAsync(PutItemRequest request, AmazonServiceCallback<PutItemRequest, PutItemResponse> callback, AsyncOptions options = null)
 {
     options = options == null?new AsyncOptions():options;
     var marshaller = new PutItemRequestMarshaller();
     var unmarshaller = PutItemResponseUnmarshaller.Instance;
     Action<AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper = null;
     if(callback !=null )
         callbackHelper = (AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) => { 
             AmazonServiceResult<PutItemRequest,PutItemResponse> responseObject 
                     = new AmazonServiceResult<PutItemRequest,PutItemResponse>((PutItemRequest)req, (PutItemResponse)res, ex , ao.State);    
                 callback(responseObject); 
         };
     BeginInvoke<PutItemRequest>(request, marshaller, unmarshaller, options, callbackHelper);
 }
Ejemplo n.º 12
0
 /// <summary>
 /// 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. 
 /// 
 ///  
 /// <para>
 /// In addition to putting an item, you can also return the item's attribute values in
 /// the same operation, using the <i>ReturnValues</i> parameter.
 /// </para>
 ///  
 /// <para>
 /// 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 <i>ValidationException</i> exception.
 /// </para>
 ///  
 /// <para>
 /// You can request that <i>PutItem</i> 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 <i>ReturnValues</i> description below.
 /// </para>
 ///  <note> 
 /// <para>
 /// To prevent a new item from replacing an existing item, use a conditional put operation
 /// with <i>ComparisonOperator</i> set to <code>NULL</code> for the primary key attribute,
 /// or attributes.
 /// </para>
 ///  </note> 
 /// <para>
 /// For more information about using this API, see <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html">Working
 /// with Items</a> in the <i>Amazon DynamoDB Developer Guide</i>.
 /// </para>
 /// </summary>
 /// <param name="tableName">The name of the table to contain the item.</param>
 /// <param name="item">A map of attribute name/value pairs, one for each attribute. Only the primary key attributes are required; you can optionally provide other attribute name-value pairs for the item. You must provide all of the attributes for the primary key. For example, with a hash type primary key, you only need to provide the hash attribute. For a hash-and-range type primary key, you must provide both the hash attribute and the range attribute. If you specify any attributes that are part of an index key, then the data types for those attributes must match those of the schema in the table's attribute definition. For more information about primary keys, see <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModelPrimaryKey">Primary Key</a> in the <i>Amazon DynamoDB Developer Guide</i>. Each element in the <i>Item</i> map is an <i>AttributeValue</i> object.</param>
 /// <param name="returnValues">Use <i>ReturnValues</i> if you want to get the item attributes as they appeared before they were updated with the <i>PutItem</i> request. For <i>PutItem</i>, the valid values are: <ul> <li> <code>NONE</code> - If <i>ReturnValues</i> is not specified, or if its value is <code>NONE</code>, then nothing is returned. (This setting is the default for <i>ReturnValues</i>.) </li> <li> <code>ALL_OLD</code> - If <i>PutItem</i> overwrote an attribute name-value pair, then the content of the old item is returned. </li> </ul></param>
 /// 
 /// <returns>The response from the PutItem service method, as returned by DynamoDB.</returns>
 /// <exception cref="Amazon.DynamoDBv2.Model.ConditionalCheckFailedException">
 /// A condition specified in the operation could not be evaluated.
 /// </exception>
 /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException">
 /// An error occurred on the server side.
 /// </exception>
 /// <exception cref="Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException">
 /// An item collection is too large. This exception is only returned for tables that have
 /// one or more local secondary indexes.
 /// </exception>
 /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException">
 /// The request rate is too high, or the request is too large, for the available throughput
 /// to accommodate. The AWS SDKs automatically retry requests that receive this exception;
 /// therefore, your request will eventually succeed, unless the request is too large or
 /// your retry queue is too large to finish. Reduce the frequency of requests by using
 /// the strategies listed in <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#APIRetries">Error
 /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>.
 /// </exception>
 /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException">
 /// The operation tried to access a nonexistent table or index. The resource might not
 /// be specified correctly, or its status might not be <code>ACTIVE</code>.
 /// </exception>
 public void PutItemAsync(string tableName, Dictionary<string, AttributeValue> item, ReturnValue returnValues, AmazonServiceCallback<PutItemRequest, PutItemResponse> callback, AsyncOptions options = null)
 {
     var request = new PutItemRequest();
     request.TableName = tableName;
     request.Item = item;
     request.ReturnValues = returnValues;
     PutItemAsync(request, callback, options);
 }
Ejemplo n.º 13
0
        internal Document PutItemHelper(Document doc, PutItemOperationConfig config, bool isAsync)
        {
            var currentConfig = config ?? new PutItemOperationConfig();

            PutItemRequest req = new PutItemRequest
            {
                TableName = TableName,
                Item = doc.ToAttributeMap()
            };
            req.BeforeRequestEvent += isAsync ?
                new RequestEventHandler(UserAgentRequestEventHandlerAsync) :
                new RequestEventHandler(UserAgentRequestEventHandlerSync);
            if (currentConfig.ReturnValues == ReturnValues.AllOldAttributes)
                req.ReturnValues = EnumMapper.Convert(currentConfig.ReturnValues);
            if (currentConfig.Expected != null && currentConfig.ExpectedState != null)
                throw new InvalidOperationException("Expected and ExpectedState cannot be set at the same time");
            if (currentConfig.Expected != null)
                req.Expected = currentConfig.Expected.ToExpectedAttributeMap();
            if (currentConfig.ExpectedState != null &&
                currentConfig.ExpectedState.ExpectedValues != null &&
                currentConfig.ExpectedState.ExpectedValues.Count > 0)
            {
                req.Expected = currentConfig.ExpectedState.ToExpectedAttributeMap();
                if (req.Expected.Count > 1)
                    req.ConditionalOperator = EnumMapper.Convert(currentConfig.ExpectedState.ConditionalOperator);
            }

            var resp = DDBClient.PutItem(req);
            doc.CommitChanges();

            Document ret = null;
            if (currentConfig.ReturnValues == ReturnValues.AllOldAttributes)
            {
                ret = Document.FromAttributeMap(resp.Attributes);
            }
            return ret;
        }
Ejemplo n.º 14
0
        public int PutItem(PutItemRequest request)
        {
            int response = (int)DBEnum.DBResponseCodes.DEFAULT_VALUE;

            try
            {
                this.client.PutItem(request);   // use the DynamoDB PutItem API
                response = (int)DBEnum.DBResponseCodes.SUCCESS;
            }

            catch
            {
                response = (int)DBEnum.DBResponseCodes.DYNAMODB_EXCEPTION;
            }

            return response;
        }
Ejemplo n.º 15
0
 internal void ApplyExpression(PutItemRequest request, DynamoDBEntryConversion conversion)
 {
     request.ConditionExpression = this.ExpressionStatement;
     request.ExpressionAttributeNames = new Dictionary<string, string>(this.ExpressionAttributeNames);
     request.ExpressionAttributeValues = ConvertToAttributeValues(this.ExpressionAttributeValues, conversion);
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Initiates the asynchronous execution of the PutItem operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the PutItem operation on AmazonDynamoDBClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        /// 
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPutItem
        ///         operation.</returns>
        public IAsyncResult BeginPutItem(PutItemRequest request, AsyncCallback callback, object state)
        {
            var marshaller = new PutItemRequestMarshaller();
            var unmarshaller = PutItemResponseUnmarshaller.Instance;

            return BeginInvoke<PutItemRequest>(request, marshaller, unmarshaller,
                callback, state);
        }
Ejemplo n.º 17
0
        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
            }
        }
Ejemplo n.º 18
0
 /// <summary>
 /// 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. 
 /// 
 ///  
 /// <para>
 /// In addition to putting an item, you can also return the item's attribute values in
 /// the same operation, using the <i>ReturnValues</i> parameter.
 /// </para>
 ///  
 /// <para>
 /// 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 <i>ValidationException</i> exception.
 /// </para>
 ///  
 /// <para>
 /// You can request that <i>PutItem</i> 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 <i>ReturnValues</i> description below.
 /// </para>
 ///  <note> 
 /// <para>
 /// To prevent a new item from replacing an existing item, use a conditional put operation
 /// with <i>ComparisonOperator</i> set to <code>NULL</code> for the primary key attribute,
 /// or attributes.
 /// </para>
 ///  </note> 
 /// <para>
 /// For more information about using this API, see <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html">Working
 /// with Items</a> in the <i>Amazon DynamoDB Developer Guide</i>.
 /// </para>
 /// </summary>
 /// <param name="tableName">The name of the table to contain the item.</param>
 /// <param name="item">A map of attribute name/value pairs, one for each attribute. Only the primary key attributes are required; you can optionally provide other attribute name-value pairs for the item. You must provide all of the attributes for the primary key. For example, with a hash type primary key, you only need to provide the hash attribute. For a hash-and-range type primary key, you must provide both the hash attribute and the range attribute. If you specify any attributes that are part of an index key, then the data types for those attributes must match those of the schema in the table's attribute definition. For more information about primary keys, see <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModelPrimaryKey">Primary Key</a> in the <i>Amazon DynamoDB Developer Guide</i>. Each element in the <i>Item</i> map is an <i>AttributeValue</i> object.</param>
 /// <param name="returnValues">Use <i>ReturnValues</i> if you want to get the item attributes as they appeared before they were updated with the <i>PutItem</i> request. For <i>PutItem</i>, the valid values are: <ul> <li> <code>NONE</code> - If <i>ReturnValues</i> is not specified, or if its value is <code>NONE</code>, then nothing is returned. (This setting is the default for <i>ReturnValues</i>.) </li> <li> <code>ALL_OLD</code> - If <i>PutItem</i> overwrote an attribute name-value pair, then the content of the old item is returned. </li> </ul> <note>Other "Valid Values" are not relevant to PutItem.</note></param>
 /// <param name="cancellationToken">
 ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
 /// </param>
 /// 
 /// <returns>The response from the PutItem service method, as returned by DynamoDB.</returns>
 /// <exception cref="Amazon.DynamoDBv2.Model.ConditionalCheckFailedException">
 /// A condition specified in the operation could not be evaluated.
 /// </exception>
 /// <exception cref="Amazon.DynamoDBv2.Model.InternalServerErrorException">
 /// An error occurred on the server side.
 /// </exception>
 /// <exception cref="Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException">
 /// An item collection is too large. This exception is only returned for tables that have
 /// one or more local secondary indexes.
 /// </exception>
 /// <exception cref="Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException">
 /// 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 <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#APIRetries">Error
 /// Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>.
 /// </exception>
 /// <exception cref="Amazon.DynamoDBv2.Model.ResourceNotFoundException">
 /// The operation tried to access a nonexistent table or index. The resource might not
 /// be specified correctly, or its status might not be <code>ACTIVE</code>.
 /// </exception>
 public Task<PutItemResponse> PutItemAsync(string tableName, Dictionary<string, AttributeValue> item, ReturnValue returnValues, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
 {
     var request = new PutItemRequest();
     request.TableName = tableName;
     request.Item = item;
     request.ReturnValues = returnValues;
     return PutItemAsync(request, cancellationToken);
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Initiates the asynchronous execution of the PutItem operation.
        /// <seealso cref="Amazon.DynamoDBv2.IAmazonDynamoDB.PutItem"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the PutItem operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
		public async Task<PutItemResponse> PutItemAsync(PutItemRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new PutItemRequestMarshaller();
            var unmarshaller = PutItemResponseUnmarshaller.GetInstance();
            var response = await Invoke<IRequest, PutItemRequest, PutItemResponse>(request, marshaller, unmarshaller, signer, cancellationToken)
                .ConfigureAwait(continueOnCapturedContext: false);
            return response;
        }
        /// <summary>
        /// <para>Creates a new item, or replaces an old item with a new item. If an item already exists in the specified table with the same primary
        /// key, the new item completely replaces the existing item. You can perform a conditional put (insert a new item if one with the specified
        /// primary key doesn't exist), or replace an existing item if it has certain attribute values. </para> <para>In addition to putting an item,
        /// you can also return the item's attribute values in the same operation, using the <i>ReturnValues</i> parameter.</para> <para>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
        /// <i>ValidationException</i> .</para> <para>You can request that <i>PutItem</i> return either a copy of the old item (before the update) or a
        /// copy of the new item (after the update). For more information, see the <i>ReturnValues</i> description.</para> <para><b>NOTE:</b> To prevent
        /// a new item from replacing an existing item, use a conditional put operation with Exists set to false for the primary key attribute, or
        /// attributes. </para> <para>For more information about using this API, see <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html">Working with Items</a> in the Amazon DynamoDB
        /// Developer Guide.</para>
        /// </summary>
        /// 
        /// <param name="putItemRequest">Container for the necessary parameters to execute the PutItem service method on AmazonDynamoDBv2.</param>
        /// 
        /// <returns>The response from the PutItem service method, as returned by AmazonDynamoDBv2.</returns>
        /// 
        /// <exception cref="T:Amazon.DynamoDBv2.Model.ItemCollectionSizeLimitExceededException" />
        /// <exception cref="T:Amazon.DynamoDBv2.Model.ResourceNotFoundException" />
        /// <exception cref="T:Amazon.DynamoDBv2.Model.ConditionalCheckFailedException" />
        /// <exception cref="T:Amazon.DynamoDBv2.Model.ProvisionedThroughputExceededException" />
        /// <exception cref="T:Amazon.DynamoDBv2.Model.InternalServerErrorException" />
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
		public Task<PutItemResponse> PutItemAsync(PutItemRequest putItemRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new PutItemRequestMarshaller();
            var unmarshaller = PutItemResponseUnmarshaller.GetInstance();
            return Invoke<IRequest, PutItemRequest, PutItemResponse>(putItemRequest, marshaller, unmarshaller, signer, cancellationToken);
        }
Ejemplo n.º 21
0
        public void Post_100_Todos_with_AWSSDK()
        {
            db.Sequences.Reset<Todo>();
            db.DeleteTable<Todo>();
            db.CreateTable<Todo>();

            var incrRequest = new UpdateItemRequest
            {
                TableName = "Seq",
                Key = new Dictionary<string, AttributeValue> {
                    {"Id", new AttributeValue { S = "Todo" } }
                },
                AttributeUpdates = new Dictionary<string, AttributeValueUpdate> {
                    {
                        "Counter",
                        new AttributeValueUpdate {
                            Action = AttributeAction.ADD,
                            Value = new AttributeValue { N = 100.ToString() }
                        }
                    }
                },
                ReturnValues = ReturnValue.ALL_NEW,
            };

            var response = awsDb.UpdateItem(incrRequest);
            var nextSequences = Convert.ToInt64(response.Attributes["Counter"].N);

            for (int i = 0; i < 100; i++)
            {
                var putRequest = new PutItemRequest("Todo",
                    new Dictionary<string, AttributeValue> {
                        { "Id", new AttributeValue { N = (nextSequences - 100 + i).ToString() } },
                        { "Content", new AttributeValue("TODO " + i) },
                        { "Order", new AttributeValue { N = i.ToString() } },
                        { "Done", new AttributeValue { BOOL = false } },
                    });

                awsDb.PutItem(putRequest);
            }

            db.ScanAll<Todo>()
                .OrderBy(x => x.Id)
                .PrintDump();
        }
 IAsyncResult invokePutItem(PutItemRequest putItemRequest, AsyncCallback callback, object state, bool synchronized)
 {
     IRequest irequest = new PutItemRequestMarshaller().Marshall(putItemRequest);
     var unmarshaller = PutItemResponseUnmarshaller.GetInstance();
     AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
     Invoke(result);
     return result;
 }
Ejemplo n.º 23
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;
        }
 /// <summary>
 /// <para>Creates a new item, or replaces an old item with a new item. If an item already exists in the specified table with the same primary
 /// key, the new item completely replaces the existing item. You can perform a conditional put (insert a new item if one with the specified
 /// primary key doesn't exist), or replace an existing item if it has certain attribute values. </para> <para>In addition to putting an item,
 /// you can also return the item's attribute values in the same operation, using the <i>ReturnValues</i> parameter.</para> <para>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
 /// <i>ValidationException</i> .</para> <para>You can request that <i>PutItem</i> return either a copy of the old item (before the update) or a
 /// copy of the new item (after the update). For more information, see the <i>ReturnValues</i> description.</para> <para><b>NOTE:</b> To prevent
 /// a new item from replacing an existing item, use a conditional put operation with Exists set to false for the primary key attribute, or
 /// attributes. </para> <para>For more information about using this API, see Working with Items in the <i>Amazon DynamoDB Developer Guide</i>
 /// .</para>
 /// </summary>
 /// 
 /// <param name="putItemRequest">Container for the necessary parameters to execute the PutItem service method on AmazonDynamoDBv2.</param>
 /// 
 /// <returns>The response from the PutItem service method, as returned by AmazonDynamoDBv2.</returns>
 /// 
 /// <exception cref="ItemCollectionSizeLimitExceededException"/>
 /// <exception cref="ResourceNotFoundException"/>
 /// <exception cref="ConditionalCheckFailedException"/>
 /// <exception cref="ProvisionedThroughputExceededException"/>
 /// <exception cref="InternalServerErrorException"/>
 public PutItemResponse PutItem(PutItemRequest putItemRequest)
 {
     IAsyncResult asyncResult = invokePutItem(putItemRequest, null, null, true);
     return EndPutItem(asyncResult);
 }
Ejemplo n.º 25
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;
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Initiates the asynchronous execution of the PutItem operation.
        /// <seealso cref="Amazon.DynamoDBv2.IAmazonDynamoDB"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the PutItem operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<PutItemResponse> PutItemAsync(PutItemRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new PutItemRequestMarshaller();
            var unmarshaller = PutItemResponseUnmarshaller.Instance;

            return InvokeAsync<PutItemRequest,PutItemResponse>(request, marshaller, 
                unmarshaller, cancellationToken);
        }
Ejemplo n.º 27
0
        internal Document PutItemHelper(Document doc, PutItemOperationConfig config, bool isAsync)
        {
            var currentConfig = config ?? new PutItemOperationConfig();

            PutItemRequest req = new PutItemRequest
            {
                TableName = TableName,
                Item = doc.ToAttributeMap()
            };
            req.BeforeRequestEvent += isAsync ?
                new RequestEventHandler(UserAgentRequestEventHandlerAsync) :
                new RequestEventHandler(UserAgentRequestEventHandlerSync);
            if (currentConfig.Expected != null)
                req.Expected = currentConfig.Expected.ToExpectedAttributeMap();
            if (currentConfig.ReturnValues == ReturnValues.AllOldAttributes)
            {
                req.ReturnValues = EnumToStringMapper.Convert(currentConfig.ReturnValues);
            }

            var resp = DDBClient.PutItem(req);
            doc.CommitChanges();

            Document ret = null;
            if (currentConfig.ReturnValues == ReturnValues.AllOldAttributes)
            {
                ret = Document.FromAttributeMap(resp.Attributes);
            }
            return ret;
        }
Ejemplo n.º 28
0
        internal Document PutItemHelper(Document doc, PutItemOperationConfig config, bool isAsync)
        {
            var currentConfig = config ?? new PutItemOperationConfig();

            PutItemRequest req = new PutItemRequest
            {
                TableName = TableName,
                Item = doc.ToAttributeMap(Conversion)
            };
            ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)req).AddBeforeRequestHandler(isAsync ?
                new RequestEventHandler(UserAgentRequestEventHandlerAsync) :
                new RequestEventHandler(UserAgentRequestEventHandlerSync));

            if (currentConfig.ReturnValues == ReturnValues.AllOldAttributes)
                req.ReturnValues = EnumMapper.Convert(currentConfig.ReturnValues);

            ValidateConditional(currentConfig);


            if (currentConfig.Expected != null)
            {
                req.Expected = currentConfig.Expected.ToExpectedAttributeMap(Conversion);
            }
            else if (currentConfig.ExpectedState != null &&
                currentConfig.ExpectedState.ExpectedValues != null &&
                currentConfig.ExpectedState.ExpectedValues.Count > 0)
            {
                req.Expected = currentConfig.ExpectedState.ToExpectedAttributeMap(Conversion);
                if (req.Expected.Count > 1)
                    req.ConditionalOperator = EnumMapper.Convert(currentConfig.ExpectedState.ConditionalOperator);
            }
            else if (currentConfig.ConditionalExpression != null && currentConfig.ConditionalExpression.IsSet)
            {
                currentConfig.ConditionalExpression.ApplyExpression(req, this.Conversion);
            }

            var resp = DDBClient.PutItem(req);
            doc.CommitChanges();

            Document ret = null;
            if (currentConfig.ReturnValues == ReturnValues.AllOldAttributes)
            {
                ret = Document.FromAttributeMap(resp.Attributes);
            }
            return ret;
        }
Ejemplo n.º 29
0
		internal PutItemResponse PutItem(PutItemRequest request)
        {
            var task = PutItemAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                throw e.InnerException;
            }
        }