Container for the parameters to the UpdateItem operation.

Edits an existing item's attributes, or inserts a new item if it does not already exist. You can put, delete, or add attribute values. You can also perform a conditional update (insert a new attribute name-value pair if it doesn't exist, or replace an existing name-value pair if it has certain expected attribute values).

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

Inheritance: AmazonDynamoDBv2Request
Esempio n. 1
0
        public override void Run()
        {
            var req = new UpdateItemRequest()
            {
                TableName = "counters",
                UpdateExpression = "ADD id :incr",
                ReturnValues = new ReturnValue("UPDATED_NEW")
            };
            req.Key.Add("table_name", new AttributeValue("user"));
            req.ExpressionAttributeValues.Add(":incr", new AttributeValue() { N = "1" });
            req.UpdateExpression = "ADD id :incr";

            var resp = DynamoDBClient.Instance.UpdateItem(req);
            short newId = short.Parse(resp.Attributes["id"].N);

            using (var ctx = new DynamoDBContext(DynamoDBClient.Instance))
            {
                User user = new User()
                {
                    id = newId,
                    accesskey = Guid.NewGuid()
                };
                ctx.Save(user);
            }
            Console.WriteLine("User [" + newId + "] has been added");

            if (Program.IsInteractive)
                Program.ToMainMenu();
        }
Esempio n. 2
0
        private static void ConditionalWriteSample(AmazonDynamoDBClient client)
        {
            Table table = Table.LoadTable(client, "Actors");
            Document d = table.GetItem("Christian Bale");

            int version = d["Version"].AsInt();
            double height = d["Height"].AsDouble();

            Console.WriteLine("Retrieved Item Version #" + version.ToString());

            var request = new UpdateItemRequest
            {
                Key = new Dictionary<string, AttributeValue>() { { "Name", new AttributeValue { S = "Christian Bale" } } },
                ExpressionAttributeNames = new Dictionary<string, string>()
                {
                    {"#H", "Height"},
                    {"#V", "Version"}
                },
                ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
                {
                    {":ht", new AttributeValue{N=(height+.01).ToString()}},
                    {":incr", new AttributeValue{N="1"}},
                    {":v", new AttributeValue{N=version.ToString()}}
                },
                UpdateExpression = "SET #V = #V + :incr, #H = :ht",
                ConditionExpression = "#V = :v",
                TableName = "Actors"
            };

            try
            {
                Console.ReadKey();
                var response = client.UpdateItem(request);
                Console.WriteLine("Updated succeeded.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Update failed. " + ex.Message);
            }

            Console.ReadKey();
        }
        public async Task UpdatePollStateAsync(string id, string state)
        {
            UpdateItemRequest updateRequest = new UpdateItemRequest
            {
                TableName = "PollDefinition",
                Key = new Dictionary<string, AttributeValue>
                {
                    {"Id", new AttributeValue {S = id } }
                },
                AttributeUpdates = new Dictionary<string, AttributeValueUpdate>
                {
                    {"State", new AttributeValueUpdate
                        {
                            Value = new AttributeValue{ S =  state },
                            Action = AttributeAction.PUT
                        }
                    }
                }
            };

            await this._dynamoDBClient.UpdateItemAsync(updateRequest);
        }
        /// <summary>
        /// Increment the vote count for an option and return back the latest voting results for poll
        /// </summary>
        /// <param name="id"></param>
        /// <param name="optionId"></param>
        /// <returns></returns>
        public async Task<Dictionary<string,int>> SubmitVoteAsync(string id, string optionId)
        {
            var request = new UpdateItemRequest
            {
                TableName = "PollDefinition",
                Key = new Dictionary<string, AttributeValue>
                    {
                        {"Id", new AttributeValue {S = id } }
                    },
                UpdateExpression = "ADD Options.#id.Votes :increment",
                ExpressionAttributeValues = new Dictionary<string, AttributeValue>
                    {
                        {":increment", new AttributeValue{N = "1"}}
                    },
                ExpressionAttributeNames = new Dictionary<string, string>
                    {
                        {"#id", optionId }
                    },
                ReturnValues = ReturnValue.ALL_NEW
            };


            var response = await this._dynamoDBClient.UpdateItemAsync(request);

            // Convert the Options attribute to just a dictionary of option id and votes.
            var currentVotes = new Dictionary<string, int>();
            var optionsAttribute = response.Attributes.FirstOrDefault(x => string.Equals(x.Key, "Options", StringComparison.OrdinalIgnoreCase));

            foreach (var optionKvp in optionsAttribute.Value.M)
            {
                var votes = int.Parse(optionKvp.Value.M["Votes"].N);
                currentVotes[optionKvp.Key] = votes;
            }

            return currentVotes;
        }
Esempio n. 5
0
 internal void ApplyExpression(UpdateItemRequest request, DynamoDBEntryConversion conversion)
 {
     request.ConditionExpression = this.ExpressionStatement;
     request.ExpressionAttributeNames = new Dictionary<string,string>(this.ExpressionAttributeNames);
     request.ExpressionAttributeValues = ConvertToAttributeValues(this.ExpressionAttributeValues, conversion);
 }
Esempio n. 6
0
 public static void Update1(int Id)
 {
     var Req = new UpdateItemRequest()
     {
         TableName = "TestID",
         Key = new Dictionary<string, AttributeValue>() { { "Id", new AttributeValue { N = Id.ToString() } } },
         AttributeUpdates = new Dictionary<string, AttributeValueUpdate>() {
         {"Msg",new AttributeValueUpdate{Action="PUT",Value=new AttributeValue{S="Test Update"+Id.ToString()}} }
         }
     };
     var Rsp = client.UpdateItem(Req);
 }
        /// <summary>
        /// Initiates the asynchronous execution of the UpdateItem operation.
        /// <seealso cref="Amazon.DynamoDBv2.IAmazonDynamoDB"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the UpdateItem 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<UpdateItemResponse> UpdateItemAsync(UpdateItemRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new UpdateItemRequestMarshaller();
            var unmarshaller = UpdateItemResponseUnmarshaller.Instance;

            return InvokeAsync<UpdateItemRequest,UpdateItemResponse>(request, marshaller, 
                unmarshaller, cancellationToken);
        }
 /// <summary>
 /// Initiates the asynchronous execution of the UpdateItem operation.
 /// <seealso cref="Amazon.DynamoDBv2.AmazonDynamoDB.UpdateItem"/>
 /// </summary>
 /// 
 /// <param name="updateItemRequest">Container for the necessary parameters to execute the UpdateItem 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 EndUpdateItem
 ///         operation.</returns>
 public IAsyncResult BeginUpdateItem(UpdateItemRequest updateItemRequest, AsyncCallback callback, object state)
 {
     return invokeUpdateItem(updateItemRequest, callback, state, false);
 }
 /// <summary>
 /// Edits an existing item's attributes, or adds a new item to the table if it does not
 /// already exist. You can put, delete, or add attribute values. You can also perform
 /// a conditional update on an existing item (insert a new attribute name-value pair if
 /// it doesn't exist, or replace an existing name-value pair if it has certain expected
 /// attribute values). If conditions are specified and the item does not exist, then the
 /// operation fails and a new item is not created. 
 /// 
 ///  
 /// <para>
 /// You can also return the item's attribute values in the same <i>UpdateItem</i> operation
 /// using the <i>ReturnValues</i> parameter.
 /// </para>
 /// </summary>
 /// <param name="tableName">The name of the table containing the item to update. </param>
 /// <param name="key">The primary key of the item to be updated. Each element consists of an attribute name and a value for that attribute. For the primary key, you must provide all of the attributes. 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.</param>
 /// <param name="attributeUpdates"><important> This is a legacy parameter, for backward compatibility. New applications should use <i>UpdateExpression</i> instead. Do not combine legacy parameters and expression parameters in a single API call; otherwise, DynamoDB will return a <i>ValidationException</i> exception. This parameter can be used for modifying top-level attributes; however, it does not support individual list or map elements. </important> The names of attributes to be modified, the action to perform on each, and the new value for each. If you are updating an attribute that is an index key attribute for any indexes on that table, the attribute type must match the index key type defined in the <i>AttributesDefinition</i> of the table description. You can use <i>UpdateItem</i> to update any nonkey attributes. Attribute values cannot be null. String and Binary type attributes must have lengths greater than zero. Set type attributes must not be empty. Requests with empty values will be rejected with a <i>ValidationException</i> exception. Each <i>AttributeUpdates</i> element consists of an attribute name to modify, along with the following: <ul> <li> <i>Value</i> - The new value, if applicable, for this attribute. </li> <li> <i>Action</i> - A value that specifies how to perform the update. This action is only valid for an existing attribute whose data type is Number or is a set; do not use <code>ADD</code> for other data types.  If an item with the specified primary key is found in the table, the following values perform the following actions: <ul> <li> <code>PUT</code> - Adds the specified attribute to the item. If the attribute already exists, it is replaced by the new value.  </li> <li> <code>DELETE</code> - Removes the attribute and its value, if no value is specified for <code>DELETE</code>. The data type of the specified value must match the existing value's data type. If a set of values is specified, then those values are subtracted from the old set. For example, if the attribute value was the set <code>[a,b,c]</code> and the <code>DELETE</code> action specifies <code>[a,c]</code>, then the final attribute value is <code>[b]</code>. Specifying an empty set is an error. </li> <li> <code>ADD</code> - Adds the specified value to the item, if the attribute does not already exist. If the attribute does exist, then the behavior of <code>ADD</code> depends on the data type of the attribute: <ul> <li> If the existing attribute is a number, and if <i>Value</i> is also a number, then <i>Value</i> is mathematically added to the existing attribute. If <i>Value</i> is a negative number, then it is subtracted from the existing attribute. <note> If you use <code>ADD</code> to increment or decrement a number value for an item that doesn't exist before the update, DynamoDB uses 0 as the initial value. Similarly, if you use <code>ADD</code> for an existing item to increment or decrement an attribute value that doesn't exist before the update, DynamoDB uses <code>0</code> as the initial value. For example, suppose that the item you want to update doesn't have an attribute named <i>itemcount</i>, but you decide to <code>ADD</code> the number <code>3</code> to this attribute anyway. DynamoDB will create the <i>itemcount</i> attribute, set its initial value to <code>0</code>, and finally add <code>3</code> to it. The result will be a new <i>itemcount</i> attribute, with a value of <code>3</code>. </note> </li> <li> If the existing data type is a set, and if <i>Value</i> is also a set, then <i>Value</i> is appended to the existing set. For example, if the attribute value is the set <code>[1,2]</code>, and the <code>ADD</code> action specified <code>[3]</code>, then the final attribute value is <code>[1,2,3]</code>. An error occurs if an <code>ADD</code> action is specified for a set attribute and the attribute type specified does not match the existing set type.  Both sets must have the same primitive data type. For example, if the existing data type is a set of strings, <i>Value</i> must also be a set of strings. </li> </ul> </li> </ul> If no item with the specified key is found in the table, the following values perform the following actions:  <ul> <li> <code>PUT</code> - Causes DynamoDB to create a new item with the specified primary key, and then adds the attribute.  </li> <li> <code>DELETE</code> - Nothing happens, because attributes cannot be deleted from a nonexistent item. The operation succeeds, but DynamoDB does not create a new item. </li> <li> <code>ADD</code> - Causes DynamoDB to create an item with the supplied primary key and number (or set of numbers) for the attribute value. The only data types allowed are Number and Number Set. </li> </ul> </li> </ul> If you provide 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.</param>
 /// <param name="returnValues">Use <i>ReturnValues</i> if you want to get the item attributes as they appeared either before or after they were updated. For <i>UpdateItem</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>UpdateItem</i> overwrote an attribute name-value pair, then the content of the old item is returned. </li> <li> <code>UPDATED_OLD</code> - The old versions of only the updated attributes are returned. </li> <li> <code>ALL_NEW</code> - All of the attributes of the new version of the item are returned. </li> <li> <code>UPDATED_NEW</code> - The new versions of only the updated attributes are returned. </li> </ul></param>
 /// 
 /// <returns>The response from the UpdateItem 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 UpdateItemResponse UpdateItem(string tableName, Dictionary<string, AttributeValue> key, Dictionary<string, AttributeValueUpdate> attributeUpdates, ReturnValue returnValues)
 {
     var request = new UpdateItemRequest();
     request.TableName = tableName;
     request.Key = key;
     request.AttributeUpdates = attributeUpdates;
     request.ReturnValues = returnValues;
     return UpdateItem(request);
 }
		internal UpdateItemResponse UpdateItem(UpdateItemRequest request)
        {
            var task = UpdateItemAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return null;
            }
        }
 /// <summary>
 /// Initiates the asynchronous execution of the UpdateItem operation.
 /// </summary>
 /// 
 /// <param name="request">Container for the necessary parameters to execute the UpdateItem 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 UpdateItemAsync(UpdateItemRequest request, AmazonServiceCallback<UpdateItemRequest, UpdateItemResponse> callback, AsyncOptions options = null)
 {
     options = options == null?new AsyncOptions():options;
     var marshaller = new UpdateItemRequestMarshaller();
     var unmarshaller = UpdateItemResponseUnmarshaller.Instance;
     Action<AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper = null;
     if(callback !=null )
         callbackHelper = (AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) => { 
             AmazonServiceResult<UpdateItemRequest,UpdateItemResponse> responseObject 
                     = new AmazonServiceResult<UpdateItemRequest,UpdateItemResponse>((UpdateItemRequest)req, (UpdateItemResponse)res, ex , ao.State);    
                 callback(responseObject); 
         };
     BeginInvoke<UpdateItemRequest>(request, marshaller, unmarshaller, options, callbackHelper);
 }
 /// <summary>
 /// Edits an existing item's attributes, or adds a new item to the table if it does not
 /// already exist. You can put, delete, or add attribute values. You can also perform
 /// a conditional update on an existing item (insert a new attribute name-value pair if
 /// it doesn't exist, or replace an existing name-value pair if it has certain expected
 /// attribute values). If conditions are specified and the item does not exist, then the
 /// operation fails and a new item is not created. 
 /// 
 ///  
 /// <para>
 /// You can also return the item's attribute values in the same <i>UpdateItem</i> operation
 /// using the <i>ReturnValues</i> parameter.
 /// </para>
 /// </summary>
 /// <param name="tableName">The name of the table containing the item to update. </param>
 /// <param name="key">The primary key of the item to be updated. Each element consists of an attribute name and a value for that attribute. For the primary key, you must provide all of the attributes. 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.</param>
 /// <param name="attributeUpdates"><important> There is a newer parameter available. Use <i>UpdateExpression</i> instead. Note that if you use <i>AttributeUpdates</i> and <i>UpdateExpression</i> at the same time, DynamoDB will return a <i>ValidationException</i> exception. This parameter can be used for modifying top-level attributes; however, it does not support individual list or map elements. </important> The names of attributes to be modified, the action to perform on each, and the new value for each. If you are updating an attribute that is an index key attribute for any indexes on that table, the attribute type must match the index key type defined in the <i>AttributesDefinition</i> of the table description. You can use <i>UpdateItem</i> to update any nonkey attributes. Attribute values cannot be null. String and Binary type attributes must have lengths greater than zero. Set type attributes must not be empty. Requests with empty values will be rejected with a <i>ValidationException</i> exception. Each <i>AttributeUpdates</i> element consists of an attribute name to modify, along with the following: <ul> <li> <i>Value</i> - The new value, if applicable, for this attribute. </li> <li> <i>Action</i> - A value that specifies how to perform the update. This action is only valid for an existing attribute whose data type is Number or is a set; do not use <code>ADD</code> for other data types.  If an item with the specified primary key is found in the table, the following values perform the following actions: <ul> <li> <code>PUT</code> - Adds the specified attribute to the item. If the attribute already exists, it is replaced by the new value.  </li> <li> <code>DELETE</code> - Removes the attribute and its value, if no value is specified for <code>DELETE</code>. The data type of the specified value must match the existing value's data type. If a set of values is specified, then those values are subtracted from the old set. For example, if the attribute value was the set <code>[a,b,c]</code> and the <code>DELETE</code> action specifies <code>[a,c]</code>, then the final attribute value is <code>[b]</code>. Specifying an empty set is an error. </li> <li> <code>ADD</code> - Adds the specified value to the item, if the attribute does not already exist. If the attribute does exist, then the behavior of <code>ADD</code> depends on the data type of the attribute: <ul> <li> If the existing attribute is a number, and if <i>Value</i> is also a number, then <i>Value</i> is mathematically added to the existing attribute. If <i>Value</i> is a negative number, then it is subtracted from the existing attribute. <note> If you use <code>ADD</code> to increment or decrement a number value for an item that doesn't exist before the update, DynamoDB uses 0 as the initial value. Similarly, if you use <code>ADD</code> for an existing item to increment or decrement an attribute value that doesn't exist before the update, DynamoDB uses <code>0</code> as the initial value. For example, suppose that the item you want to update doesn't have an attribute named <i>itemcount</i>, but you decide to <code>ADD</code> the number <code>3</code> to this attribute anyway. DynamoDB will create the <i>itemcount</i> attribute, set its initial value to <code>0</code>, and finally add <code>3</code> to it. The result will be a new <i>itemcount</i> attribute, with a value of <code>3</code>. </note> </li> <li> If the existing data type is a set, and if <i>Value</i> is also a set, then <i>Value</i> is appended to the existing set. For example, if the attribute value is the set <code>[1,2]</code>, and the <code>ADD</code> action specified <code>[3]</code>, then the final attribute value is <code>[1,2,3]</code>. An error occurs if an <code>ADD</code> action is specified for a set attribute and the attribute type specified does not match the existing set type.  Both sets must have the same primitive data type. For example, if the existing data type is a set of strings, <i>Value</i> must also be a set of strings. </li> </ul> </li> </ul> If no item with the specified key is found in the table, the following values perform the following actions:  <ul> <li> <code>PUT</code> - Causes DynamoDB to create a new item with the specified primary key, and then adds the attribute.  </li> <li> <code>DELETE</code> - Nothing happens, because attributes cannot be deleted from a nonexistent item. The operation succeeds, but DynamoDB does not create a new item. </li> <li> <code>ADD</code> - Causes DynamoDB to create an item with the supplied primary key and number (or set of numbers) for the attribute value. The only data types allowed are Number and Number Set. </li> </ul> </li> </ul> If you provide 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.</param>
 /// <param name="returnValues">Use <i>ReturnValues</i> if you want to get the item attributes as they appeared either before or after they were updated. For <i>UpdateItem</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>UpdateItem</i> overwrote an attribute name-value pair, then the content of the old item is returned. </li> <li> <code>UPDATED_OLD</code> - The old versions of only the updated attributes are returned. </li> <li> <code>ALL_NEW</code> - All of the attributes of the new version of the item are returned. </li> <li> <code>UPDATED_NEW</code> - The new versions of only the updated attributes are returned. </li> </ul></param>
 /// 
 /// <returns>The response from the UpdateItem 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 UpdateItemAsync(string tableName, Dictionary<string, AttributeValue> key, Dictionary<string, AttributeValueUpdate> attributeUpdates, ReturnValue returnValues, AmazonServiceCallback<UpdateItemRequest, UpdateItemResponse> callback, AsyncOptions options = null)
 {
     var request = new UpdateItemRequest();
     request.TableName = tableName;
     request.Key = key;
     request.AttributeUpdates = attributeUpdates;
     request.ReturnValues = returnValues;
     UpdateItemAsync(request, callback, options);
 }
Esempio n. 13
0
        public void UpdateItem(string ConnectionString, string tableName, string whereparam, string expressionText, string columnName, string abbvrName, string updatedValue)
        {
            Connection c = new Connection();
            var client = c.ConnectAmazonDynamoDB(ConnectionString);

            var request = new UpdateItemRequest
            {
                TableName = tableName,
                Key = new Dictionary<string, AttributeValue>() { { "TableName", new AttributeValue { S = whereparam } } },
                ExpressionAttributeNames = new Dictionary<string, string>()
                {
                    {abbvrName, columnName}
                },
                ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
                {
                    {expressionText,new AttributeValue {N = updatedValue}},
                },

                // This expression does the following:
                // 1) Adds two new authors to the list
                // 2) Reduces the price
                // 3) Adds a new attribute to the item
                // 4) Removes the ISBN attribute from the item
                UpdateExpression = "SET " + expressionText +  "=" + expressionText + "-" +  expressionText
            };
        }
Esempio n. 14
0
        public int UpdateItem(UpdateItemRequest request)
        {
            int response = (int)DBEnum.DBResponseCodes.DEFAULT_VALUE;

            try
            {
                this.client.UpdateItem(request);
                response = (int)DBEnum.DBResponseCodes.SUCCESS;
            }
            catch
            {
                response = (int)DBEnum.DBResponseCodes.DYNAMODB_EXCEPTION;
            }

            return response;
        }
Esempio n. 15
0
        /// <summary>
        /// Updates the users credentials
        /// </summary>
        /// <param name="loginInfo">Uses GCUser.LoginInfo.Email to validate the email address</param>
        /// <param name="oldPassword">Old password to validate</param>
        /// <param name="newPassword">New password to set to</param>
        /// <returns>0 if successful, otherwise > 0</returns>
        public int UpdateCredentials(GCUser.LoginInfo loginInfo, string oldPassword, string newPassword)
        {
            int response = (int)DBEnum.DBResponseCodes.DEFAULT_VALUE;
            GetItemResponse giResponse = new GetItemResponse();

            // validate to see if user exist
            if ((int)DBEnum.DBResponseCodes.SUCCESS == SetUserLoginInfo(loginInfo))
            {
                // validate password correct
                if (pwh.ValidatePassword(oldPassword, string.Format("{0}:{1}:{2}:{3}",
                    loginInfo.Encryption,
                    loginInfo.Iterations,
                    loginInfo.SaltHash,
                    loginInfo.PasswordHash)))
                {
                    char[] delimiter = { ':' }; // delimiter for password hash
                    string[] split = pwh.CreateHash(newPassword).Split(delimiter); // split the string into array

                    UpdateItemRequest request = new UpdateItemRequest();
                    request.TableName = TABLE;  // set table to "GCLogin"
                    request.Key = new Dictionary<string, AttributeValue>() { { primaryKey, new AttributeValue { S = loginInfo.Email } } };
                    request.UpdateExpression = string.Format("SET #s =:{0}, #p =:{1}", SALT_HASH, PASSWORD_HASH);

                    request.ExpressionAttributeNames = new Dictionary<string, string>
                    {
                        { "#s", SALT_HASH },
                        { "#p", PASSWORD_HASH }
                    };

                    request.ExpressionAttributeValues = new Dictionary<string, AttributeValue>
                    {
                        {string.Format(":{0}",SALT_HASH), new AttributeValue {S = split[(int)DBEnum.GCLoginIndex.SALT_INDEX] } },
                        {string.Format(":{0}",PASSWORD_HASH), new AttributeValue {S = split[(int)DBEnum.GCLoginIndex.PBKDF2_INDEX] } }
                    };
                    dbManager.UpdateItem(request);

                    logger.WriteLog(GameLogger.LogLevel.Debug, string.Format("User: {0} credentials updated.", loginInfo.Email));
                    response = (int)DBEnum.DBResponseCodes.SUCCESS;
                }
                // if not correct set response > 0
                else
                {
                    logger.WriteLog(GameLogger.LogLevel.Debug, string.Format("Failed to update User: {0} credentials.", loginInfo.Email));
                    response = (int)DBEnum.DBResponseCodes.INVALID_USERNAME_PASSWORD;
                }
            }

            // user does not exist
            else
            {
                logger.WriteLog(GameLogger.LogLevel.Debug, string.Format("User: {0} credentials updated.", loginInfo.Email));
                response = (int)DBEnum.DBResponseCodes.DOES_NOT_EXIST;
            }

            return response;
        }
        /// <summary>
        /// Initiates the asynchronous execution of the UpdateItem operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the UpdateItem 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 EndUpdateItem
        ///         operation.</returns>
        public IAsyncResult BeginUpdateItem(UpdateItemRequest request, AsyncCallback callback, object state)
        {
            var marshaller = new UpdateItemRequestMarshaller();
            var unmarshaller = UpdateItemResponseUnmarshaller.Instance;

            return BeginInvoke<UpdateItemRequest>(request, marshaller, unmarshaller,
                callback, state);
        }
 /// <summary>
 /// Edits an existing item's attributes, or adds a new item to the table if it does not
 /// already exist. You can put, delete, or add attribute values. You can also perform
 /// a conditional update on an existing item (insert a new attribute name-value pair if
 /// it doesn't exist, or replace an existing name-value pair if it has certain expected
 /// attribute values). If conditions are specified and the item does not exist, then the
 /// operation fails and a new item is not created. 
 /// 
 ///  
 /// <para>
 /// You can also return the item's attribute values in the same <i>UpdateItem</i> operation
 /// using the <i>ReturnValues</i> parameter.
 /// </para>
 /// </summary>
 /// <param name="tableName">The name of the table containing the item to update. </param>
 /// <param name="key">The primary key of the item to be updated. Each element consists of an attribute name and a value for that attribute. For the primary key, you must provide all of the attributes. 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.</param>
 /// <param name="attributeUpdates"><important> This is a legacy parameter, for backward compatibility. New applications should use <i>UpdateExpression</i> instead. Do not combine legacy parameters and expression parameters in a single API call; otherwise, DynamoDB will return a <i>ValidationException</i> exception. This parameter can be used for modifying top-level attributes; however, it does not support individual list or map elements. </important> The names of attributes to be modified, the action to perform on each, and the new value for each. If you are updating an attribute that is an index key attribute for any indexes on that table, the attribute type must match the index key type defined in the <i>AttributesDefinition</i> of the table description. You can use <i>UpdateItem</i> to update any nonkey attributes. Attribute values cannot be null. String and Binary type attributes must have lengths greater than zero. Set type attributes must not be empty. Requests with empty values will be rejected with a <i>ValidationException</i> exception. Each <i>AttributeUpdates</i> element consists of an attribute name to modify, along with the following: <ul> <li> <i>Value</i> - The new value, if applicable, for this attribute. </li> <li> <i>Action</i> - A value that specifies how to perform the update. This action is only valid for an existing attribute whose data type is Number or is a set; do not use <code>ADD</code> for other data types.  If an item with the specified primary key is found in the table, the following values perform the following actions: <ul> <li> <code>PUT</code> - Adds the specified attribute to the item. If the attribute already exists, it is replaced by the new value.  </li> <li> <code>DELETE</code> - Removes the attribute and its value, if no value is specified for <code>DELETE</code>. The data type of the specified value must match the existing value's data type. If a set of values is specified, then those values are subtracted from the old set. For example, if the attribute value was the set <code>[a,b,c]</code> and the <code>DELETE</code> action specifies <code>[a,c]</code>, then the final attribute value is <code>[b]</code>. Specifying an empty set is an error. </li> <li> <code>ADD</code> - Adds the specified value to the item, if the attribute does not already exist. If the attribute does exist, then the behavior of <code>ADD</code> depends on the data type of the attribute: <ul> <li> If the existing attribute is a number, and if <i>Value</i> is also a number, then <i>Value</i> is mathematically added to the existing attribute. If <i>Value</i> is a negative number, then it is subtracted from the existing attribute. <note> If you use <code>ADD</code> to increment or decrement a number value for an item that doesn't exist before the update, DynamoDB uses 0 as the initial value. Similarly, if you use <code>ADD</code> for an existing item to increment or decrement an attribute value that doesn't exist before the update, DynamoDB uses <code>0</code> as the initial value. For example, suppose that the item you want to update doesn't have an attribute named <i>itemcount</i>, but you decide to <code>ADD</code> the number <code>3</code> to this attribute anyway. DynamoDB will create the <i>itemcount</i> attribute, set its initial value to <code>0</code>, and finally add <code>3</code> to it. The result will be a new <i>itemcount</i> attribute, with a value of <code>3</code>. </note> </li> <li> If the existing data type is a set, and if <i>Value</i> is also a set, then <i>Value</i> is appended to the existing set. For example, if the attribute value is the set <code>[1,2]</code>, and the <code>ADD</code> action specified <code>[3]</code>, then the final attribute value is <code>[1,2,3]</code>. An error occurs if an <code>ADD</code> action is specified for a set attribute and the attribute type specified does not match the existing set type.  Both sets must have the same primitive data type. For example, if the existing data type is a set of strings, <i>Value</i> must also be a set of strings. </li> </ul> </li> </ul> If no item with the specified key is found in the table, the following values perform the following actions:  <ul> <li> <code>PUT</code> - Causes DynamoDB to create a new item with the specified primary key, and then adds the attribute.  </li> <li> <code>DELETE</code> - Nothing happens, because attributes cannot be deleted from a nonexistent item. The operation succeeds, but DynamoDB does not create a new item. </li> <li> <code>ADD</code> - Causes DynamoDB to create an item with the supplied primary key and number (or set of numbers) for the attribute value. The only data types allowed are Number and Number Set. </li> </ul> </li> </ul> If you provide 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.</param>
 /// <param name="returnValues">Use <i>ReturnValues</i> if you want to get the item attributes as they appeared either before or after they were updated. For <i>UpdateItem</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>UpdateItem</i> overwrote an attribute name-value pair, then the content of the old item is returned. </li> <li> <code>UPDATED_OLD</code> - The old versions of only the updated attributes are returned. </li> <li> <code>ALL_NEW</code> - All of the attributes of the new version of the item are returned. </li> <li> <code>UPDATED_NEW</code> - The new versions of only the updated attributes are returned. </li> </ul></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 UpdateItem 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<UpdateItemResponse> UpdateItemAsync(string tableName, Dictionary<string, AttributeValue> key, Dictionary<string, AttributeValueUpdate> attributeUpdates, ReturnValue returnValues, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
 {
     var request = new UpdateItemRequest();
     request.TableName = tableName;
     request.Key = key;
     request.AttributeUpdates = attributeUpdates;
     request.ReturnValues = returnValues;
     return UpdateItemAsync(request, cancellationToken);
 }
Esempio n. 18
0
        public void CRUDSamples()
        {
            EnsureTables();

            PutSample();

            {
                #region GetItem Sample

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

                // Define item key
                //  Hash-key of the target item is string value "Mark Twain"
                //  Range-key of the target item is string value "The Adventures of Tom Sawyer"
                Dictionary<string, AttributeValue> key = new Dictionary<string, AttributeValue>
                {
                    { "Author", new AttributeValue { S = "Mark Twain" } },
                    { "Title", new AttributeValue { S = "The Adventures of Tom Sawyer" } }
                };

                // Create GetItem request
                GetItemRequest request = new GetItemRequest
                {
                    TableName = "SampleTable",
                    Key = key,
                };

                // Issue request
                var result = client.GetItem(request);

                // View response
                Console.WriteLine("Item:");
                Dictionary<string, AttributeValue> item = result.Item;
                foreach (var keyValuePair in item)
                {
                    Console.WriteLine("{0} : S={1}, N={2}, SS=[{3}], NS=[{4}]",
                        keyValuePair.Key,
                        keyValuePair.Value.S,
                        keyValuePair.Value.N,
                        string.Join(", ", keyValuePair.Value.SS ?? new List<string>()),
                        string.Join(", ", keyValuePair.Value.NS ?? new List<string>()));
                }

                #endregion
            }

            {
                #region UpdateItem Sample

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

                // Define item key
                //  Hash-key of the target item is string value "Mark Twain"
                //  Range-key of the target item is string value "The Adventures of Tom Sawyer"
                Dictionary<string, AttributeValue> key = new Dictionary<string, AttributeValue>
                {
                    { "Author", new AttributeValue { S = "Mark Twain" } },
                    { "Title", new AttributeValue { S = "The Adventures of Tom Sawyer" } }
                };

                // Define attribute updates
                Dictionary<string, AttributeValueUpdate> updates = new Dictionary<string, AttributeValueUpdate>();
                // Update item's Setting attribute
                updates["Setting"] = new AttributeValueUpdate()
                {
                    Action = AttributeAction.PUT,
                    Value = new AttributeValue { S = "St. Petersburg, Missouri" }
                };
                // Remove item's Bibliography attribute
                updates["Bibliography"] = new AttributeValueUpdate()
                {
                    Action = AttributeAction.DELETE
                };   
                // Add a new string to the item's Genres SS attribute
                updates["Genres"] = new AttributeValueUpdate()
                {
                    Action = AttributeAction.ADD,
                    Value = new AttributeValue { SS = new List<string> { "Bildungsroman" } }
                };

                // Create UpdateItem request
                UpdateItemRequest request = new UpdateItemRequest
                {
                    TableName = "SampleTable",
                    Key = key,
                    AttributeUpdates = updates
                };

                // Issue request
                client.UpdateItem(request);

                #endregion
            }

            {
                #region DeleteItem Sample

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

                // Define item key
                //  Hash-key of the target item is string value "Mark Twain"
                //  Range-key of the target item is string value "The Adventures of Tom Sawyer"
                Dictionary<string, AttributeValue> key = new Dictionary<string, AttributeValue>
                {
                    { "Author", new AttributeValue { S = "Mark Twain" } },
                    { "Title", new AttributeValue { S = "The Adventures of Tom Sawyer" } }
                };

                // Create DeleteItem request
                DeleteItemRequest request = new DeleteItemRequest
                {
                    TableName = "SampleTable",
                    Key = key
                };

                // Issue request
                client.DeleteItem(request);

                #endregion
            }
        }
        /// <summary>
        /// <para> Edits an existing item's attributes, or inserts a new item if it does not already exist. You can put, delete, or add attribute
        /// values. You can also perform a conditional update (insert a new attribute name-value pair if it doesn't exist, or replace an existing
        /// name-value pair if it has certain expected attribute values).</para> <para>In addition to updating an item, you can also return the item's
        /// attribute values in the same operation, using the <i>ReturnValues</i> parameter.</para>
        /// </summary>
        /// 
        /// <param name="updateItemRequest">Container for the necessary parameters to execute the UpdateItem service method on AmazonDynamoDBv2.</param>
        /// 
        /// <returns>The response from the UpdateItem 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<UpdateItemResponse> UpdateItemAsync(UpdateItemRequest updateItemRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new UpdateItemRequestMarshaller();
            var unmarshaller = UpdateItemResponseUnmarshaller.GetInstance();
            return Invoke<IRequest, UpdateItemRequest, UpdateItemResponse>(updateItemRequest, marshaller, unmarshaller, signer, cancellationToken);
        }
        /// <summary>
        /// Initiates the asynchronous execution of the UpdateItem operation.
        /// <seealso cref="Amazon.DynamoDBv2.IAmazonDynamoDB.UpdateItem"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the UpdateItem 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<UpdateItemResponse> UpdateItemAsync(UpdateItemRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new UpdateItemRequestMarshaller();
            var unmarshaller = UpdateItemResponseUnmarshaller.GetInstance();
            var response = await Invoke<IRequest, UpdateItemRequest, UpdateItemResponse>(request, marshaller, unmarshaller, signer, cancellationToken)
                .ConfigureAwait(continueOnCapturedContext: false);
            return response;
        }
 IAsyncResult invokeUpdateItem(UpdateItemRequest updateItemRequest, AsyncCallback callback, object state, bool synchronized)
 {
     IRequest irequest = new UpdateItemRequestMarshaller().Marshall(updateItemRequest);
     var unmarshaller = UpdateItemResponseUnmarshaller.GetInstance();
     AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
     Invoke(result);
     return result;
 }
        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();
        }
 /// <summary>
 /// <para> Edits an existing item's attributes, or inserts a new item if it does not already exist. You can put, delete, or add attribute
 /// values. You can also perform a conditional update (insert a new attribute name-value pair if it doesn't exist, or replace an existing
 /// name-value pair if it has certain expected attribute values).</para> <para>In addition to updating an item, you can also return the item's
 /// attribute values in the same operation, using the <i>ReturnValues</i> parameter.</para>
 /// </summary>
 /// 
 /// <param name="updateItemRequest">Container for the necessary parameters to execute the UpdateItem service method on AmazonDynamoDBv2.</param>
 /// 
 /// <returns>The response from the UpdateItem service method, as returned by AmazonDynamoDBv2.</returns>
 /// 
 /// <exception cref="ItemCollectionSizeLimitExceededException"/>
 /// <exception cref="ResourceNotFoundException"/>
 /// <exception cref="ConditionalCheckFailedException"/>
 /// <exception cref="ProvisionedThroughputExceededException"/>
 /// <exception cref="InternalServerErrorException"/>
 public UpdateItemResponse UpdateItem(UpdateItemRequest updateItemRequest)
 {
     IAsyncResult asyncResult = invokeUpdateItem(updateItemRequest, null, null, true);
     return EndUpdateItem(asyncResult);
 }
Esempio n. 24
0
        internal Document UpdateHelper(Document doc, Key key, UpdateItemOperationConfig config, bool isAsync)
        {
            var currentConfig = config ?? new UpdateItemOperationConfig();

            // If the keys have been changed, treat entire document as having changed
            bool haveKeysChanged = HaveKeysChanged(doc);
            bool updateChangedAttributesOnly = !haveKeysChanged;

            var attributeUpdates = doc.ToAttributeUpdateMap(updateChangedAttributesOnly);
            foreach (var keyName in this.keyNames)
            {
                attributeUpdates.Remove(keyName);
            }

            UpdateItemRequest req = new UpdateItemRequest
            {
                TableName = TableName,
                Key = key,
                AttributeUpdates = attributeUpdates.Count == 0 ? null : attributeUpdates, // pass null if keys-only update
                ReturnValues = EnumToStringMapper.Convert(currentConfig.ReturnValues)
            };
            req.BeforeRequestEvent += isAsync ?
                new RequestEventHandler(UserAgentRequestEventHandlerAsync) :
                new RequestEventHandler(UserAgentRequestEventHandlerSync);
            if (currentConfig.Expected != null)
                req.Expected = currentConfig.Expected.ToExpectedAttributeMap();

            var resp = DDBClient.UpdateItem(req);
            var returnedAttributes = resp.Attributes;
            doc.CommitChanges();

            Document ret = null;
            if (currentConfig.ReturnValues != ReturnValues.None)
            {
                ret = Document.FromAttributeMap(returnedAttributes);
            }
            return ret;
        }
        internal UpdateItemResponse UpdateItem(UpdateItemRequest request)
        {
            var marshaller = new UpdateItemRequestMarshaller();
            var unmarshaller = UpdateItemResponseUnmarshaller.Instance;

            return Invoke<UpdateItemRequest,UpdateItemResponse>(request, marshaller, unmarshaller);
        }
Esempio n. 26
0
		internal UpdateItemResponse UpdateItem(UpdateItemRequest request)
        {
            var task = UpdateItemAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                throw e.InnerException;
            }
        }
Esempio n. 27
0
        internal Document UpdateHelper(Document doc, Key key, UpdateItemOperationConfig config, bool isAsync)
        {
            var currentConfig = config ?? new UpdateItemOperationConfig();

            // If the keys have been changed, treat entire document as having changed
            bool haveKeysChanged = HaveKeysChanged(doc);
            bool updateChangedAttributesOnly = !haveKeysChanged;

            var attributeUpdates = doc.ToAttributeUpdateMap(Conversion, updateChangedAttributesOnly);
            foreach (var keyName in this.KeyNames)
            {
                attributeUpdates.Remove(keyName);
            }

            UpdateItemRequest req = new UpdateItemRequest
            {
                TableName = TableName,
                Key = key,
                AttributeUpdates = attributeUpdates.Count == 0 ? null : attributeUpdates, // pass null if keys-only update
                ReturnValues = EnumMapper.Convert(currentConfig.ReturnValues)
            };


            ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)req).AddBeforeRequestHandler(isAsync ?
                new RequestEventHandler(UserAgentRequestEventHandlerAsync) :
                new RequestEventHandler(UserAgentRequestEventHandlerSync)
                );

            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);

                string statement;
                Dictionary<string, AttributeValue> expressionAttributeValues;
                Dictionary<string, string> expressionAttributeNames;
                Common.ConvertAttributeUpdatesToUpdateExpression(attributeUpdates, out statement, out expressionAttributeValues, out expressionAttributeNames);

                req.AttributeUpdates = null;
                req.UpdateExpression = statement;

                if (req.ExpressionAttributeValues == null)
                    req.ExpressionAttributeValues = expressionAttributeValues;
                else
                {
                    foreach (var kvp in expressionAttributeValues)
                        req.ExpressionAttributeValues.Add(kvp.Key, kvp.Value);
                }

                if (req.ExpressionAttributeNames == null)
                    req.ExpressionAttributeNames = expressionAttributeNames;
                else
                {
                    foreach (var kvp in expressionAttributeNames)
                        req.ExpressionAttributeNames.Add(kvp.Key, kvp.Value);
                }
            }

            var resp = DDBClient.UpdateItem(req);
            var returnedAttributes = resp.Attributes;
            doc.CommitChanges();

            Document ret = null;
            if (currentConfig.ReturnValues != ReturnValues.None)
            {
                ret = Document.FromAttributeMap(returnedAttributes);
            }
            return ret;
        }
        public virtual void UpdateIfMatch(AmazonDynamoDBClient ddbClient, string tableName, string email, string company,
            string firstNameTarget, string firstNameMatch)
        {
            // Build the request
            var updateItemRequest = new UpdateItemRequest
            {
                TableName = tableName,
                Key = new Dictionary<string, AttributeValue>
                {
                    {"Company", new AttributeValue {S = company}},
                    {"Email", new AttributeValue {S = email}}
                },
                Expected = new Dictionary<string, ExpectedAttributeValue>
                {
                    {"First", new ExpectedAttributeValue {Value = new AttributeValue {S = firstNameMatch}}}
                },
                AttributeUpdates = new Dictionary<string, AttributeValueUpdate>
                {
                    {
                        "First",
                        new AttributeValueUpdate {Action = "PUT", Value = new AttributeValue {S = firstNameTarget}}
                    }
                }
            };

            // Submit request
            ddbClient.UpdateItem(updateItemRequest);
        }