public async Task SetPhotoState(UserId userId, PhotoId photoId, PhotoState photoState)
        {
            logWriter.LogInformation($"{nameof(SetPhotoState)}({nameof(userId)} = '{userId}', {nameof(photoId)} = '{photoId}', {nameof(photoState)} = '{photoState}'");

            var request = new UpdateItemRequest
            {
                TableName = tableName,
                Key       = new Dictionary <string, AttributeValue>
                {
                    { FieldMappings.PartitionKey, new AttributeValue(photoId.ToDbValue()) },
                    { FieldMappings.SortKey, new AttributeValue(photoId.ToDbValue()) }
                },
                UpdateExpression          = $"SET {FieldMappings.Photo.State} = :newstate",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    {
                        ":newstate", new AttributeValue
                        {
                            S = photoState.ToString()
                        }
                    }
                }
            };

            await dynamoDbCore.UpdateItem(request);
        }
Beispiel #2
0
        public async Task UpdateMovie(int userId, MovieUpdateRequest updateRequest)
        {
            var request = new UpdateItemRequest
            {
                TableName = TableName,
                Key       = new Dictionary <string, AttributeValue>
                {
                    { "UserId", new AttributeValue {
                          N = userId.ToString()
                      } },
                    { "MovieName", new AttributeValue {
                          S = updateRequest.MovieName
                      } }
                },
                AttributeUpdates = new Dictionary <string, AttributeValueUpdate>
                {
                    { "Ranking", new AttributeValueUpdate
                      {
                          Action = AttributeAction.PUT,
                          Value  = new AttributeValue {
                              N = updateRequest.Ranking.ToString()
                          }
                      } },
                    { "RankedDateTime", new AttributeValueUpdate
                      {
                          Action = AttributeAction.PUT,
                          Value  = new AttributeValue {
                              S = DateTime.UtcNow.ToString()
                          }
                      } }
                }
            };

            await _dynamoDbClient.UpdateItemAsync(request);
        }
        public async Task UpdateAsync(Team item)
        {
            var request = new UpdateItemRequest()
            {
                TableName = Constants.TeamTableName,
                Key       = new Dictionary <string, AttributeValue>()
                {
                    { "TeamId", new AttributeValue()
                      {
                          S = item.TeamId
                      } }
                },
                UpdateExpression          = "set #Name = :Name",
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>()
                {
                    { ":Name", new AttributeValue()
                      {
                          S = item.Name
                      } }
                },
                ExpressionAttributeNames = new Dictionary <string, string>()
                {
                    { "#Name", "Name" }
                }
            };

            await _dbClient.UpdateItemAsync(request);
        }
Beispiel #4
0
        public long Increment <T>(object hash, string fieldName, long amount = 1)
        {
            var type    = DynamoMetadata.GetType <T>();
            var request = new UpdateItemRequest
            {
                TableName        = type.Name,
                Key              = Converters.ToAttributeKeyValue(this, type.HashKey, hash),
                AttributeUpdates = new Dictionary <string, AttributeValueUpdate> {
                    {
                        fieldName,
                        new AttributeValueUpdate {
                            Action = AttributeAction.ADD,
                            Value  = new AttributeValue {
                                N = amount.ToString()
                            }
                        }
                    }
                },
                ReturnValues = ReturnValue.ALL_NEW,
            };

            var response = DynamoDb.UpdateItem(request);

            return(response.Attributes.Count > 0
                ? Convert.ToInt64(response.Attributes[fieldName].N)
                : 0);
        }
        public async Task <UpdateItemResponse> UpdateItem(UpdateItemRequest request)
        {
            try
            {
                Validate(request.Item);
                var itemToBeUpdated = new Item()
                {
                    Id          = Convert.ToInt32(request.Item.Id),
                    Name        = request.Item.Name,
                    Description = request.Item.Description,
                    Price       = Convert.ToDecimal(request.Item.Price)
                };
                var result = await _inventoryRepository.UpdateItem(itemToBeUpdated);

                return(result ? new UpdateItemResponse() :
                       new UpdateItemResponse()
                {
                    ErrorMessage = "The item with the specified id could not be updated!"
                });
            }
            catch (Exception ex)
            {
                return(new UpdateItemResponse()
                {
                    ErrorMessage = ex.Message
                });
            }
        }
        /*--------------------------------------------------------------------------
         *                             UpdatingMovie_async
         *--------------------------------------------------------------------------*/
        public static async Task <bool> UpdatingMovie_async(UpdateItemRequest updateRequest, bool report)
        {
            UpdateItemResponse updateResponse = null;

            operationSucceeded = false;
            operationFailed    = false;
            if (report)
            {
                Console.WriteLine("  -- Trying to update a movie item...");
                updateRequest.ReturnValues = "ALL_NEW";
            }

            try
            {
                updateResponse = await client.UpdateItemAsync(updateRequest);

                Console.WriteLine("     -- SUCCEEDED in updating the movie item!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("     -- FAILED to update the movie item, because:\n       {0}.", ex.Message);
                if (updateResponse != null)
                {
                    Console.WriteLine("     -- The status code was " + updateResponse.HttpStatusCode.ToString( ));
                }
                operationFailed = true; return(false);
            }
            if (report)
            {
                Console.WriteLine("     Here is the updated movie informtion:");
                Console.WriteLine(movieAttributesToJson(updateResponse.Attributes));
            }
            operationSucceeded = true;
            return(true);
        }
Beispiel #7
0
        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);
        }
        public async Task UpdateAsync(AppUser user, CancellationToken cancellationToken)
        {
            var updatedAtUtc = new DateTimeOffset(user.UpdatedAtUtc).ToUnixTimeSeconds();

            var request = new UpdateItemRequest
            {
                TableName = DynamoTables.LOGON_APPUSERS,
                Key       = new Dictionary <string, AttributeValue>
                {
                    { "Email", new AttributeValue {
                          S = user.Email
                      } }
                },
                AttributeUpdates = new Dictionary <string, AttributeValueUpdate>
                {
                    { "Name", new AttributeValueUpdate {
                          Value = new AttributeValue(user.Name)
                      } },
                    { "UpdatedAtUtc", new AttributeValueUpdate {
                          Value = new AttributeValue {
                              N = updatedAtUtc.ToString()
                          }
                      } },
                }
            };

            await _client.UpdateAsync(request, cancellationToken);
        }
Beispiel #9
0
        private async Task <int> IssueANewUserId()
        {
            string tableName = "UsersCatalog";

            var request = new UpdateItemRequest
            {
                Key = new Dictionary <string, AttributeValue>()
                {
                    { "Id", new AttributeValue {
                          N = "0"
                      } }
                },
                ExpressionAttributeNames = new Dictionary <string, string>()
                {
                    { "#id", "NewId" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>()
                {
                    { ":incr", new AttributeValue {
                          N = "1"
                      } }
                },
                UpdateExpression = "SET #id = #id + :incr",
                ReturnValues     = ReturnValue.ALL_NEW,
                TableName        = tableName
            };

            var response = await Client.UpdateItemAsync(request);

            return(int.Parse(response.Attributes["NewId"].N));
        }
Beispiel #10
0
        public HttpResponseMessage Update(string ticket, Item item)
        {
            var securityProvider = new SecurityProvider(_connectionString);

            var sessionInfo = securityProvider.GetSessionInfo(ticket);

            if (sessionInfo == null)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            var updateRequest = new UpdateItemRequest
            {
                Item   = item,
                UserId = sessionInfo.User.Id
            };

            var handler = new UpdateItemHandler(_connectionString);

            var response = handler.Handle(updateRequest);

            var httpStatusCode = ResolveStatusCode(response);

            return(Request.CreateResponse(httpStatusCode, response));
        }
        internal UpdateItemResponse UpdateItem(UpdateItemRequest request)
        {
            var marshaller   = new UpdateItemRequestMarshaller();
            var unmarshaller = UpdateItemResponseUnmarshaller.Instance;

            return(Invoke <UpdateItemRequest, UpdateItemResponse>(request, marshaller, unmarshaller));
        }
Beispiel #12
0
        /// Edits an entry in the database
        /// @param primaryKey - key of entry to edit
        /// @param attributeKey - attribute key that will be changed or added
        /// @param attributeValue - the value for the specified attributeKey
        protected async Task <bool> SetItemsAttribute(AttributeValue primaryKey, string attributeKey, AttributeValue attributeValue)
        {
            var updateRequest = new UpdateItemRequest
            {
                TableName = tableName,
                Key       = new Dictionary <string, AttributeValue>
                {
                    { primaryPartitionKey, primaryKey }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":attr", attributeValue },
                },
                UpdateExpression = "SET " + attributeKey + " = :attr"
            };

            try
            {
                await client.UpdateItemAsync(updateRequest);

                return(true);
            }
            catch (Exception e)
            {
                log.WARN("DatabaseClient", "SetItemsAttribute", "EXCEPTION: " + e.Message);
                return(false);
            }
        }
        /// <summary>
        /// M Not In Use : Test Method -- Testt Data with Hard code value
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="item"></param>
        public void UpdateItemAttributes <T>(T item) where T : class
        {
            UpdateItemRequest updateRequest = new UpdateItemRequest()
            {
                TableName = "CustomerAPI",
                Key       = new Dictionary <string, AttributeValue>
                {
                    { "EmailAddress", new AttributeValue {
                          S = "*****@*****.**"
                      } },
                    { "UserType", new AttributeValue {
                          S = "Customer"
                      } }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":r", new AttributeValue {
                          S = "5.5"
                      } },
                    { ":p", new AttributeValue {
                          S = "Everything happens all at once!"
                      } }
                    //    ,
                    //{ ":a", new AttributeValue {
                    //      SS = { "Larry","Moe","Curly" }
                    //  } }
                },
                UpdateExpression = "SET AuthData.AuthToken = :r, AuthData.IssuedOn = :p",
                ReturnValues     = "UPDATED_NEW"
            };

            DynamoClient.UpdateItem(updateRequest);
        }
Beispiel #14
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();
            }
        }
        public void AtomicCounter(string id, string attribute, int value)
        {
            var request = new UpdateItemRequest
            {
                TableName = AWSDynamoTableConfig.TableName,
                Key       = new Dictionary <string, AttributeValue>
                {
                    { AWSDynamoTableConfig.KeyName, new AttributeValue {
                          S = id
                      } }
                },
                AttributeUpdates = new Dictionary <string, AttributeValueUpdate>()
                {
                    {
                        attribute,
                        new AttributeValueUpdate {
                            Action = "ADD", Value = new AttributeValue {
                                N = value.ToString()
                            }
                        }
                    },
                },
            };

            client.UpdateItem(request);
        }
        public async Task <bool> UpdateBookAvailability(string id, string available)
        {
            try
            {
                var key = new Dictionary <string, AttributeValue>
                {
                    { "Id", new AttributeValue {
                          S = id
                      } },
                };
                var updates = new Dictionary <string, AttributeValueUpdate>();
                updates["Available"] = new AttributeValueUpdate()
                {
                    Action = AttributeAction.PUT,
                    Value  = new AttributeValue {
                        S = available
                    }
                };

                var request = new UpdateItemRequest
                {
                    TableName        = Constants.BOOK_TABLE_NAME,
                    Key              = key,
                    AttributeUpdates = updates
                };

                await dynamoDBClient.UpdateItemAsync(request);

                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Beispiel #17
0
        public static void FreezeMoney(string contractId)
        {
            UpdateItemRequest request = new UpdateItemRequest()
            {
                TableName = assetTableName,
                Key       = new Dictionary <string, AttributeValue>()
                {
                    {
                        "ContractId", new AttributeValue {
                            S = contractId
                        }
                    }
                },
                ExpressionAttributeNames = new Dictionary <string, string>()
                {
                    { "#InstrumentId", "InstrumentId" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>()
                {
                    {
                        ":incr", new AttributeValue {
                            N = "1"
                        }
                    }
                },
                UpdateExpression = "SET #InstrumentId = #InstrumentId + :incr"
            };

            var response = amazonDynamoDbClient.UpdateItemAsync(request);

            response.Wait();
        }
Beispiel #18
0
        public void Test2InsertNumberSet()
        {
            var tableName = "GameHistory";

            CreateGameHistoryTable(tableName);

            var userIds = GenerateDummyUserIds();

            var dict = new Dictionary <string, AttributeValueUpdate>();

            dict["Userids"] = new AttributeValueUpdate {
                Action = "PUT",
                Value  = new AttributeValue {
                    NS = userIds.ToList()
                }
            };

            var request = new UpdateItemRequest {
                TableName = tableName,
                Key       = new Dictionary <string, AttributeValue>()
                {
                    { "GameId", new AttributeValue {
                          N = "12345"
                      } }
                },
                AttributeUpdates = dict
            };

            var response = Client.UpdateItem(request);

            Assert.AreEqual(response.HttpStatusCode, HttpStatusCode.OK);
        }
Beispiel #19
0
        public void SetTweeted(Quote statement)
        {
            LambdaLogger.Log($"Setting tweeted for statement for uuid {statement.uuid}\n");
            AmazonDynamoDBClient client = new AmazonDynamoDBClient();

            var request = new UpdateItemRequest
            {
                TableName = "WisdomOfAvasarala",
                Key       = new Dictionary <string, AttributeValue>()
                {
                    { "uuid", new AttributeValue {
                          S = statement.uuid
                      } }
                },
                ExpressionAttributeNames = new Dictionary <string, string>()
                {
                    { "#T", "tweeted" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>()
                {
                    { ":t", new AttributeValue {
                          S = "1"
                      } }
                },
                UpdateExpression = "SET #T = :t"
            };

            var response = client.UpdateItemAsync(request).Result;
        }
Beispiel #20
0
        public async Task ServiceClientExampleAsync()
        {
            try
            {
                // Define the name of a user account to update. Note that in this example, we have to alias "name" using ExpressionAttributeNames as name is a reserved word in DynamoDB.
                var request = new UpdateItemRequest
                {
                    TableName = "RetailDatabase",
                    Key       = new Dictionary <string, AttributeValue>
                    {
                        { "pk", new AttributeValue("*****@*****.**") },
                        { "sk", new AttributeValue("metadata") },
                    },
                    UpdateExpression         = "set #n = :nm",
                    ExpressionAttributeNames = new Dictionary <string, string>
                    {
                        { "#n", "name" },
                    },
                    ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                    {
                        { ":nm", new AttributeValue("Big Jim Bob") },
                    },
                    ReturnValues = ReturnValue.ALL_NEW
                };

                var response = await amazonDynamoDB.UpdateItemAsync(request);

                Console.WriteLine($"UpdateItem succeeded.");
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
                throw;
            }
        }
Beispiel #21
0
        public async Task <IEnumerable <OnlineProfile> > DeleteSocialProfile(OnlineProfile profile, UserId userId)
        {
            logWriter.LogInformation($"{nameof(DeleteSocialProfile)}({nameof(profile.Type)}={profile.Type}, {nameof(profile.Profile)}={profile.Profile}, {nameof(userId)}={userId.Value})");
            var user = await GetUserById(userId);

            var onlineProfiles = user.OnlineProfiles?.ToList() ?? new List <OnlineProfile>();
            int profileIndex   = onlineProfiles.FindIndex(x =>
                                                          x.Type == profile.Type &&
                                                          x.Profile.Equals(profile.Profile, StringComparison.OrdinalIgnoreCase));

            if (profileIndex >= 0)
            {
                var               dbItem           = Mappers.UserModel.ToDbItem(user);
                string            updateExpression = $"REMOVE OnlineProfiles[{profileIndex}]";
                UpdateItemRequest request          = new UpdateItemRequest
                {
                    TableName        = tableName,
                    Key              = Mappers.UserModel.ToDbKey(user),
                    UpdateExpression = updateExpression
                };
                await dynamoDbCore.UpdateItem(request);

                onlineProfiles.RemoveAt(profileIndex);
                user.OnlineProfiles = onlineProfiles;
            }

            return(onlineProfiles);
        }
Beispiel #22
0
 public UpdateItemHttpContent(UpdateItemRequest request, string?tablePrefix, string pkName, string skName) : base("DynamoDB_20120810.UpdateItem")
 {
     _request     = request;
     _tablePrefix = tablePrefix;
     _pkName      = pkName;
     _skName      = skName;
 }
        public async Task UpdateDownloadedCounter(string fileName)
        {
            var request = new UpdateItemRequest
            {
                TableName = _databaseConfiguration.DownloadCounterTable,
                Key       = new Dictionary <string, AttributeValue>
                {
                    { "FileName", new AttributeValue {
                          S = fileName
                      } }
                },
                AttributeUpdates = new Dictionary <string, AttributeValueUpdate>()
                {
                    {
                        "Downloaded",
                        new AttributeValueUpdate {
                            Action = "ADD", Value = new AttributeValue {
                                N = "1"
                            }
                        }
                    },
                },
            };

            await _dynamoDbClient.UpdateItemAsync(request);
        }
Beispiel #24
0
        public void LikeReview(Category category, Guid id)
        {
            var keys = new Dictionary <string, AttributeValue>();

            keys.Add("Category", new AttributeValue {
                N = ((int)category).ToString()
            });
            keys.Add("Id", new AttributeValue {
                S = id.ToString()
            });

            var updateExpression = "ADD #a :increment";

            var expressionAttributeNames = new Dictionary <string, string>();

            expressionAttributeNames.Add("#a", "Likes");

            var expressionAttributeValues = new Dictionary <string, AttributeValue>();

            expressionAttributeValues.Add(":increment", new AttributeValue {
                N = "1"
            });

            var updateItemRequest = new UpdateItemRequest();

            updateItemRequest.TableName                 = _tableName;
            updateItemRequest.Key                       = keys;
            updateItemRequest.UpdateExpression          = updateExpression;
            updateItemRequest.ExpressionAttributeNames  = expressionAttributeNames;
            updateItemRequest.ExpressionAttributeValues = expressionAttributeValues;

            // do we need something from the response? maybe the new amount of likes?
            var response = _dbClient.UpdateItem(updateItemRequest);
        }
Beispiel #25
0
        public async Task <int> UpdateProducto(ProductoDto newProducto)
        {
            AmazonDynamoDBClient client = new AmazonDynamoDBClient();
            string tableName            = "Productos";

            var request = new UpdateItemRequest
            {
                TableName = tableName,
                Key       = new Dictionary <string, AttributeValue>()
                {
                    { "Id", new AttributeValue {
                          N = newProducto.id.ToString()
                      } }
                },
                ExpressionAttributeNames = new Dictionary <string, string>()
                {
                    { "#I", "Inventario" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>()
                {
                    { ":inventario", new AttributeValue {
                          N = newProducto.inventario.ToString()
                      } }
                },

                UpdateExpression = "SET #I = :inventario"
            };
            var response = await client.UpdateItemAsync(request);

            return(1);
        }
Beispiel #26
0
        public async static Task <UpdateItemResponse> MainUpdateAsync(SongDescription UpdateSong)
        {
            Dictionary <string, AttributeValue> key = new Dictionary <string, AttributeValue>
            {
                { "Artist", new AttributeValue {
                      S = UpdateSong.Artist
                  } },
                { "SongTitle", new AttributeValue {
                      S = UpdateSong.SongTitle
                  } },
            };
            Dictionary <string, AttributeValueUpdate> updates = new Dictionary <string, AttributeValueUpdate>();

            updates["Duration"] = new AttributeValueUpdate()
            {
                Action = AttributeAction.PUT,
                Value  = new AttributeValue {
                    S = UpdateSong.Duration
                }
            };
            var request = new UpdateItemRequest
            {
                TableName        = tableName,
                Key              = key,
                AttributeUpdates = updates,
                ReturnValues     = "UPDATED_NEW"
            };

            UpdateItemResponse r = await client.UpdateItemAsync(request);

            return(r);
        }
        public IActionResult Patch(int id,
                                   [FromHeader] String clientId,
                                   [FromHeader] String clientSecret,
                                   [FromBody] UpdateItemRequest data)
        {
            var userId = UsersManager.ValidateUser(clientId, clientSecret);

            if (userId == 0)
            {
                this.Response.StatusCode = 401;
                return(Json(new { status = StatusMessages.UserNotFound }));
            }
            else
            {
                if (ItemsManager.UpdateItem(id, userId, data.caption, data.description, data.order, data.url))
                {
                    return(Json(new { status = StatusMessages.OK }));
                }
                else
                {
                    this.Response.StatusCode = 404;
                    return(Json(new { status = StatusMessages.ItemNotFound }));
                }
            }
        }
Beispiel #28
0
        public async Task UpdateItem()
        {
            var updateItemRequest = new UpdateItemRequest()
            {
                TableName = "GameScores",
                Key       = new Dictionary <string, AttributeValue>()
                {
                    { "UserId", new AttributeValue()
                      {
                          S = "101"
                      } },
                    { "GameTitle", new AttributeValue()
                      {
                          S = "Galaxy Invaders"
                      } }
                },
                AttributeUpdates = new Dictionary <string, AttributeValueUpdate>()
                {
                    { "TopScore", new AttributeValueUpdate()
                      {
                          Action = "ADD", Value = new AttributeValue()
                          {
                              N = "1"
                          }
                      } }
                }, ReturnValues = ReturnValue.ALL_NEW
            };

            var result = await DynamoDBHelper.Client.UpdateItemAsync(updateItemRequest);
        }
Beispiel #29
0
        public async Task <bool> UpdateItem(long id, UpdateItemRequest updateItemRequest)
        {
            bool resp;

            try
            {
                if (id <= 0L)
                {
                    throw new Exception("Id of item must be greater than zero.");
                }

                var dataVendorExists = await CheckIfVendorExists(updateItemRequest.IdVendor);

                if (dataVendorExists)
                {
                    var itemTable = _mapper.Map <ItemTable>(updateItemRequest);
                    itemTable.Id = id;
                    resp         = await UpdateItemTable(itemTable);
                }
                else
                {
                    throw new Exception("ItemVendor doesn't exists.");
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return(resp);
        }
Beispiel #30
0
        public async Task <IActionResult> UpdateItem([FromBody] UpdateItemRequest request)
        {
            try
            {
                var res = await _dynamoClient.UpdateItemAsync(request);

                return(new JsonResult(res)
                {
                    StatusCode = 200
                });
            }
            catch (AmazonDynamoDBException addbe)
            {
                return(AmazonExceptionHandlers.HandleAmazonDynamoDBException(addbe));
            }
            catch (AmazonServiceException ase)
            {
                AmazonExceptionHandlers.HandleAmazonServiceExceptionException(ase);
            }
            catch (AmazonClientException ace)
            {
                AmazonExceptionHandlers.HandleAmazonClientExceptionException(ace);
            }
            return(StatusCode(500));
        }
Beispiel #31
0
 /// <remarks/>
 public void UpdateItemAsync(UpdateItemRequest UpdateItemRequest) {
     this.UpdateItemAsync(UpdateItemRequest, null);
 }
Beispiel #32
0
 /// <remarks/>
 public void UpdateItemAsync(UpdateItemRequest UpdateItemRequest, object userState) {
     if ((this.UpdateItemOperationCompleted == null)) {
         this.UpdateItemOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateItemOperationCompleted);
     }
     this.InvokeAsync("UpdateItem", new object[] {
                 UpdateItemRequest}, this.UpdateItemOperationCompleted, userState);
 }
        public ActionResult Edit(int id, FormCollection collection)
        {
            var cid=0;
            if (GlobeInfo.GetWebInfo.GetValue("isneedcates") == "1")
            {
                cid = collection["CatsId"].TryTo(0);
                if (cid <= 0) return Content("请选择商品的类目");
            }
            else
            {
                cid = 0;
            }
            var stock = collection["MaxStore"].IsEmpty() ? "99999" : collection["MaxStore"];
            var d = Commodity.GetDetail(id, "Stock,ItemTitle");
            var buylimit = collection["BuyLimit"];
            var title = collection["Product"];
            var subTitle = collection["Feature"];
            var msgTitle = collection["CouponMessage"];
            var saletype = collection["GoodsType"];
            var itemcode = collection["OuterId"];
            var price = collection["Price"];
            var volume = collection["Volume"];
            var weight = collection["Weight"];
            var marketPrice = collection["MarketPrice"];
            var imgs = GetImages(collection["Thumbs"]);
            var postType = collection["PostType"];
            var onTime = collection["PostTime"];
            var couponTemplateId = collection["CouponFareType"].IsEmpty()?"0": collection["CouponTemplate"];
            var expressTemplateId = collection["FareType"].IsEmpty()?"0": collection["FareTemplate"];
            var catsinshop = collection["ShopCategorys"];
            var propValues = collection["PropValue"];
            var inventoryCount = int.Parse(collection["InventoryCount"]);
            var detail = collection["Detail"];
            var seoTitle = collection["SeoTitle"];
            var seoKeywords = collection["SeoKeywords"];
            var seoDescription = collection["SeoDescription"];
            var expiredType = collection["ExpiredType"].TryTo(0);
            
            var extItemCatIds = collection["extItemCatIds"];
            var suitShops =
                collection["SuitShop"].IsEmpty()
                    ? ""
                    : collection["SuitShop"].Deserialize<IDictionary<int, string>>()
                        .Select(e => e.Key)
                        .ToArray()
                        .ContactString(",");

            var expiredTime = 0;
            if (!collection["ExpiredTime"].IsEmpty())
            {
                expiredTime = collection["ExpiredTime"].TryTo<string, DateTime>().ToUnix();
            }

            if (expiredType == 1)
            {
                expiredTime = collection["ExpiredLastTime"].TryTo<string, DateTime>().ToUnix();
            }
            var isrecomm = collection["IsRecomm"];
            var integrallimit = collection["Integrallimit"];
            var additionInfo = ProcessSkuFxPrice(collection["MinFxPrice"], collection["MaxFxPrice"]);
            List<string> customNames;
            var customSkus = GetCustomSkus(collection, out customNames);
            var updateItem = new UpdateItemRequest
            {
                Integrallimit = integrallimit.TryTo(0),
                InventoryCount = inventoryCount,
                ExtItemCatIds = extItemCatIds,
                BuyLimit = buylimit.TryTo(0),
                Volume = volume.TryTo(0.0),
                Weight = weight.TryTo(0.0),
                AdditionalInfo = additionInfo,
                CouponTemplateId = couponTemplateId.TryTo(0),
                ItemPropValues = propValues,
                CustomSpecNames = customNames.Serialize(),
                CustomSkus = customSkus.Serialize(),
                Description = detail,
                FreightTemplateId = expressTemplateId.TryTo(0),
                ItemCode = itemcode,
                IsRecommend = isrecomm.TryTo(0) == 1 ? 1 : 0,
                ItemTitle = title,
                MsgTitle = msgTitle,
                OnShelfTime = onTime.IsEmpty() ? 0 : onTime.TryTo<string, DateTime>().ToUnix(),
                OnShelfType = postType.TryTo(0),
                SaleType = saletype == "goods" ? 1 : 3,
                SubTitle = subTitle,
                Price = price.TryTo(0.0),
                Pictures = imgs,
                Stock = stock.TryTo(0),
                ItemPartnerIds = suitShops,
                MarketPrice = marketPrice.TryTo(0.0),
                ShopCatIds = Commodity.FilterAllCategoriesInShop(catsinshop).ContactString(","),
                ItemCatId = cid,
                ExpireTime = expiredTime,
                ItemId = id,
                SeoDescription = seoDescription,
                SeoKeyword = seoKeywords,
                SeoTitle = seoTitle,
                ExpireRule = expiredType,
                ExpireDays = collection["DuringDay"].TryTo(0),
                ExpireStart = collection["ExpiredStartTime"].TryTo<string, DateTime>().ToUnix()
            };
            var r = YunShop.Core.YunClient.Instance.Execute(updateItem, Member.Token);
            var result = !r.IsError && r.Result;
            if (result)
            {
                CacheManage.ItemListCache.Remove(id);
                CacheManage.ItemDetailCache.Remove(id);
                //TempData["success"] = "“" + title + "”商品已成功修改";
                var goods = YunClient.Instance.Execute(new GetItemRequest { Id = id,NeedPromotion=true }).Item;

                if (goods != null)
                {
                    new Yun.ClientCache.CacheFunc().Delete(YunShop.Core.DataProvider.Commodity._cacheName, "Id", id.ToString());
                    new Yun.ClientCache.CacheFunc().Insert(YunShop.Core.DataProvider.Commodity._cacheName, "Id", GoodsDetailInSql.ConvertGoodsInSql(goods),
                    new[]
                        {
                            "CategoryId", "AreaId", "IsRecommend", "ItemTitle", "MarketPrice", "OffShelfTime","OnShelfTime", "Partners", "Price", "Sales", "SaleType", "Stock", "UpdateTime","SaleType","ShopId","Recommend","CompanyId"
                        });
                }
            }
            
            return Content(r.IsError ? r.ErrMsg : r.Result?1.ToString():"修改失败");
        }