Example #1
0
        public IList <ErrorStatus> Validate(DeleteItemRequest request)
        {
            var errors = new List <ErrorStatus>();

            var ItemOwner = _itemsRepository.GetUserByItemId(request.ItemId);

            if (ItemOwner == null)
            {
                errors.Add(new ErrorStatus("ITEM_NOT_FOUND"));
                return(errors);
            }

            if (string.IsNullOrEmpty(ItemOwner.Id.ToString()))
            {
                errors.Add(new ErrorStatus("ITEM_NOT_FOUND")); // kaip cia validatinti
                return(errors);
            }


            if (request.UserId != ItemOwner.Id)
            {
                errors.Add(new ErrorStatus("UNAUTHORIZED_ACCESS"));
                return(errors);
            }
            if (request.ItemId < 1)
            {
                errors.Add(new ErrorStatus("WRONG_ID"));
            }

            return(errors);
        }
Example #2
0
        public async static Task <int> MainDeleteAsync(SongDescription DeleteSong)
        {
            Dictionary <string, AttributeValue> conditions = new Dictionary <string, AttributeValue>();

            if (DeleteSong != null)
            {
                if (DeleteSong.Artist != null && DeleteSong.Artist != "")
                {
                    conditions.Add("Artist", new AttributeValue {
                        S = DeleteSong.Artist
                    });
                }

                if (DeleteSong.SongTitle != null && DeleteSong.SongTitle != "")
                {
                    conditions.Add("SongTitle", new AttributeValue {
                        S = DeleteSong.SongTitle
                    });
                }
            }
            DeleteItemRequest request = new DeleteItemRequest
            {
                TableName = tableName,
                Key       = conditions
            };

            await client.DeleteItemAsync(request);

            return(200);
        }
Example #3
0
        /// <summary>
        /// Delete an entry from a DynamoDB table
        /// </summary>
        /// <param name="tableName">The name of the table to delete an entry</param>
        /// <param name="keys">The table entry keys for the entry to be deleted</param>
        /// <param name="conditionExpression">Optional conditional expression</param>
        /// <param name="conditionValues">Optional field/attribute values used in the conditional expression</param>
        /// <returns></returns>
        public Task DeleteEntryAsync(string tableName, Dictionary <string, AttributeValue> keys, string conditionExpression = "", Dictionary <string, AttributeValue> conditionValues = null)
        {
            if (Logger.IsEnabled(LogLevel.Trace))
            {
                Logger.Trace("Deleting table {0}  entry with key(s) {1}", tableName, Utils.DictionaryToString(keys));
            }

            try
            {
                var request = new DeleteItemRequest
                {
                    TableName = tableName,
                    Key       = keys
                };

                if (!string.IsNullOrWhiteSpace(conditionExpression))
                {
                    request.ConditionExpression = conditionExpression;
                }

                if (conditionValues != null && conditionValues.Keys.Count > 0)
                {
                    request.ExpressionAttributeValues = conditionValues;
                }

                return(ddbClient.DeleteItemAsync(request));
            }
            catch (Exception exc)
            {
                Logger.Warn(ErrorCode.StorageProviderBase,
                            $"Intermediate error deleting entry from the table {tableName}.", exc);
                throw;
            }
        }
        private async Task RemoveLikeRecord(UserId userId, PhotoId photoId)
        {
            logWriter.LogInformation($"{nameof(RemoveLikeRecord)}({nameof(userId)} = '{userId}', {nameof(photoId)} = '{photoId}')");

            var photo = await photoRepository.GetPhotoById(photoId, Guid.Empty);

            var newLikeCount = photo.LikeCount - 1;

            var deleteItemRequest = new DeleteItemRequest(
                tableName,
                Mappers.PhotoLike.ToDbKey(new PhotoLikeRecord
            {
                UserId      = userId,
                PhotoId     = photoId,
                CreatedTime = system.Time.UtcNow
            }));

            try
            {
                await dynamoDbCore.DeleteItem(deleteItemRequest);
                await UpdateLikeCount(photo, newLikeCount);
            }
            catch (Exception ex)
            {
                logWriter.LogError(ex, $"Error in {nameof(RemoveLikeRecord)}({nameof(userId)} = '{userId}', {nameof(photoId)} = '{photoId}'):\n{ex.ToString()}");
                throw;
            }
        }
Example #5
0
        public async Task ReleaseLock(string Id)
        {
            if (_mutex.WaitOne())
            {
                try
                {
                    _localLocks.Remove(Id);
                }
                finally
                {
                    _mutex.Set();
                }
            }

            try
            {
                var req = new DeleteItemRequest()
                {
                    TableName = _tableName,
                    Key       = new Dictionary <string, AttributeValue>
                    {
                        { "id", new AttributeValue(Id) }
                    },
                    ConditionExpression       = "lock_owner = :nodeId",
                    ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                    {
                        { ":nodeId", new AttributeValue(_nodeId) }
                    }
                };
                await _client.DeleteItemAsync(req);
            }
            catch (ConditionalCheckFailedException)
            {
            }
        }
Example #6
0
        internal Document DeleteHelper(Key key, DeleteItemOperationConfig config, bool isAsync)
        {
            var currentConfig = config ?? new DeleteItemOperationConfig();

            var req = new DeleteItemRequest
            {
                TableName = TableName,
                Key       = key
            };

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

            var attributes = DDBClient.DeleteItem(req).Attributes;

            Document ret = null;

            if (currentConfig.ReturnValues == ReturnValues.AllOldAttributes)
            {
                ret = Document.FromAttributeMap(attributes);
            }
            return(ret);
        }
        public async Task ServiceClientExampleAsync()
        {
            try
            {
                var request = new DeleteItemRequest
                {
                    TableName = "RetailDatabase",
                    Key       = new Dictionary <string, AttributeValue>
                    {
                        { "pk", new AttributeValue {
                              S = "*****@*****.**"
                          } },
                        { "sk", new AttributeValue {
                              S = "metadata"
                          } }
                    }
                };

                var response = await amazonDynamoDB.DeleteItemAsync(request);

                Console.WriteLine($"DeleteItem succeeded.");
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
                throw;
            }
        }
Example #8
0
        public static async Task DeleteItemAsync()
        {
            #region service_client_delete
            using (var ddbClient = new AmazonDynamoDBClient())
            {
                var request = new DeleteItemRequest
                {
                    TableName = "TODOList",
                    Key       = new Dictionary <string, AttributeValue>
                    {
                        { "User", new AttributeValue {
                              S = "serviceclient-testuser"
                          } },
                        { "ListId", new AttributeValue {
                              S = "generated-list-id"
                          } }
                    }
                };

                var response = await ddbClient.DeleteItemAsync(request);

                Console.WriteLine("Item Deleted");
            }
            #endregion
        }
Example #9
0
        private DeleteItemRequest DeleteItemRequest(int id, string registeredDate)
        {
            var request = new DeleteItemRequest()
            {
                Key = new Dictionary <string, AttributeValue>
                {
                    { "Id", new AttributeValue {
                          N = id.ToString()
                      } },
                    { "RegisterDateTime", new AttributeValue {
                          N = registeredDate
                      } }
                },
                ExpressionAttributeNames = new Dictionary <string, string>
                {
                    { "#id", "Id" }
                },
                ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                {
                    { ":newid", new AttributeValue {
                          N = id.ToString()
                      } }
                },
                TableName           = "MyTest",
                ReturnValues        = "ALL_OLD",
                ConditionExpression = "#id = :newid"
            };

            return(request);
        }
Example #10
0
        private void btnDelete_Click(object sender, EventArgs e)
        {
            var request = new DeleteItemRequest().WithTableName("Snapshot").WithKey(new Key().WithHashKeyElement(new AttributeValue().WithS("1")).
                                                                                    WithRangeKeyElement(new AttributeValue().WithN("1")));

            DeleteItemResponse r = client.DeleteItem(request);
        }
Example #11
0
        public int DeleteItem(string primaryKeyName, string primaryKeyValue, string table)
        {
            int response = (int)DBEnum.DBResponseCodes.DEFAULT_VALUE;

            DeleteItemRequest request = new DeleteItemRequest(); // generate new deleterequest

            request.TableName = table;                           // set to table name
            request.Key       = new Dictionary <string, AttributeValue>()
            {
                { primaryKeyName, new AttributeValue {
                      S = primaryKeyValue
                  } }
            };
            try
            {
                this.client.DeleteItem(request);
                response = (int)DBEnum.DBResponseCodes.SUCCESS;
            }
            catch
            {
                response = (int)DBEnum.DBResponseCodes.DYNAMODB_EXCEPTION;
            }

            return(response);
        }
Example #12
0
        public async Task DeleteAsync(string id, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            DeleteItemRequest deleteItem = DynamoDbParser.GetDeleteItemRequest(id);
            await client.DeleteItemAsync(deleteItem, cancellationToken);
        }
Example #13
0
        /// <summary>
        /// <para>Deletes a single item in a table by primary key. You can perform a conditional delete operation that deletes the item if it exists, or
        /// if it has an expected attribute value.</para> <para>In addition to deleting an item, you can also return the item's attribute values in the
        /// same operation, using the <i>ReturnValues</i> parameter.</para> <para>Unless you specify conditions, the <i>DeleteItem</i> is an idempotent
        /// operation; running it multiple times on the same item or attribute does <i>not</i> result in an error response.</para> <para>Conditional
        /// deletes are useful for only deleting items if specific conditions are met. If those conditions are met, DynamoDB performs the delete.
        /// Otherwise, the item is not deleted. </para>
        /// </summary>
        ///
        /// <param name="deleteItemRequest">Container for the necessary parameters to execute the DeleteItem service method on AmazonDynamoDBv2.</param>
        ///
        /// <returns>The response from the DeleteItem 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 <DeleteItemResponse> DeleteItemAsync(DeleteItemRequest deleteItemRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new DeleteItemRequestMarshaller();
            var unmarshaller = DeleteItemResponseUnmarshaller.GetInstance();

            return(Invoke <IRequest, DeleteItemRequest, DeleteItemResponse>(deleteItemRequest, marshaller, unmarshaller, signer, cancellationToken));
        }
Example #14
0
        private static void DeleteSampleProduct(int id, string tableName)
        {
            switch (provider)
            {
            case Provider.NOSQL:
                var request = new DeleteItemRequest
                {
                    TableName = tableName,
                    Key       = new Dictionary <string, AttributeValue>()
                    {
                        { "Id", new AttributeValue {
                              N = id.ToString()
                          } }
                    },
                };
                var response = client.DeleteItem(request);
                break;

            case Provider.MSSQL:
                new Product()
                {
                    Id = { Value = id }
                }.Delete();
                break;
            }
        }
Example #15
0
        protected override void deleteItem()
        {
            var request = new DeleteItemRequest().WithTableName(tableName).WithKey(
                new Key().WithHashKeyElement(new AttributeValue().WithS(dataOwnerID)));

            DeleteItemResponse r = client.DeleteItem(request);
        }
Example #16
0
        public async Task <DeleteItemResponse> DeleteItems <T>(T tabelaInterna, string nomeTabela)
        {
            try
            {
                table = Table.LoadTable(_dynamoClient, nomeTabela);
                //
                DynamoDBContext db = new DynamoDBContext(_dynamoClient);
                //
                Document documentRequest = db.ToDocument(tabelaInterna);
                //Mapeando os campos
                chave = table.ToAttributeMap(documentRequest);
                //Verificar quais campos são necessarios
                chave = Utils.VerificarChaves(chave, table);
                //
                var deleteRequest = new DeleteItemRequest(nomeTabela, chave);
                //
                var deleteResponse = await _dynamoClient.DeleteItemAsync(deleteRequest, cancellationToken);

                //
                db.Dispose();
                //
                return(deleteResponse);
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #17
0
        public void DeleteItem(string PrimaryKeyID, string TableName)
        {
            try
            {
                context.Logger.LogLine("DynamoDBHelper::DeleteItem()=> TableName = " + TableName);
                context.Logger.LogLine("DynamoDBHelper::DeleteItem()=> PKID =  " + PrimaryKeyID);

                Table table = Table.LoadTable(client, TableName);

                Dictionary <string, AttributeValue> key =
                    new Dictionary <string, AttributeValue>
                {
                    { "PrimaryKeyID1", new AttributeValue {
                          S = PrimaryKeyID
                      } }
                };

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

                // Issue request
                client.DeleteItemAsync(request).GetAwaiter().GetResult();
                context.Logger.LogLine("DynamoDBHelper::DeleteItem() -- Delete Operation succeeded");
            }
            catch (Exception ex)
            {
                context.Logger.LogLine("DynamoDBHelper::DeleteItem() -- " + ex.Message);
                context.Logger.LogLine("DynamoDBHelper::DeleteItem() -- " + ex.StackTrace);
            }
        }
Example #18
0
        public async Task <APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            LambdaLogger.Log(JObject.FromObject(request).ToString());
            try {
                var connectionId = request.RequestContext.ConnectionId;
                LambdaLogger.Log("ConnectionId:" + connectionId);

                Dictionary <string, AttributeValue> attributes = new Dictionary <string, AttributeValue>();
                attributes["ConnectionId"] = new AttributeValue {
                    S = connectionId
                };

                DeleteItemRequest ddbRequest = new DeleteItemRequest()
                {
                    TableName = Environment.GetEnvironmentVariable("DynamoChatTable"),
                    Key       = attributes
                };
                DeleteItemResponse ddbResponse = ddbClient.DeleteItemAsync(ddbRequest).Result;

                return(new APIGatewayProxyResponse
                {
                    StatusCode = 200,
                    Body = "Disconnected."
                });
            } catch (Exception e) {
                context.Logger.LogLine("Error connecting: " + e.Message);
                context.Logger.LogLine(e.StackTrace);
                return(new APIGatewayProxyResponse
                {
                    StatusCode = 500,
                    Body = $"Failed to connect: {e.Message}"
                });
            }
        }
Example #19
0
        public void Delete(long id)
        {
            var request = new DeleteItemRequest
            {
                TableName = "employee",
                Key       = new Dictionary <string, AttributeValue>()
                {
                    { "id", new AttributeValue {
                          S = id.ToString()
                      } }
                },
                ReturnValues = new ReturnValue("ALL_OLD"),
            };

            DeleteItemResponse x = dynamodbClient.DeleteItemAsync(request).Result;

            if (x.HttpStatusCode != System.Net.HttpStatusCode.OK && x.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception("Unable to delete Employee");
            }

            if (x.Attributes.Count == 0)
            {
                throw new KeyNotFoundException("Employee not found");
            }

            return;
        }
Example #20
0
 private async static Task DeleteItem(DocumentServiceDefinition.DocumentServiceDefinitionClient documentClient)
 {
     var input = new DeleteItemRequest {
         Id = 9
     };
     var reply = await documentClient.DeleteItemAsync(input);
 }
        // snippet-end:[DynamoDB.dotnetv3.dynamodb-basics.BatchWriteItem]

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

        /// <summary>
        /// Deletes a single item from a DynamoDB table.
        /// </summary>
        /// <param name="client">The initialized DynamoDB client object.</param>
        /// <param name="tableName">The name of the table from which the item
        /// will be deleted.</param>
        /// <param name="movieToDelete">A movie object containing the title and
        /// year of the movie to delete.</param>
        /// <returns>A Boolean value indicating the success or failure of the
        /// delete operation.</returns>
        public static async Task <bool> DeleteItemAsync(
            AmazonDynamoDBClient client,
            string tableName,
            Movie movieToDelete)
        {
            var key = new Dictionary <string, AttributeValue>
            {
                ["title"] = new AttributeValue {
                    S = movieToDelete.Title
                },
                ["year"] = new AttributeValue {
                    N = movieToDelete.Year.ToString()
                },
            };

            var request = new DeleteItemRequest
            {
                TableName = tableName,
                Key       = key,
            };

            var response = await client.DeleteItemAsync(request);

            return(response.HttpStatusCode == System.Net.HttpStatusCode.OK);
        }
Example #22
0
        public async Task DeleteAllBuddies()
        {
            var request = new ScanRequest
            {
                TableName = _tableName
            };

            var response = await _dynamoDbClient.ScanAsync(request);

            var items = response.Items.Select(Map);

            foreach (var item in items)
            {
                var deleteRequest = new DeleteItemRequest
                {
                    TableName = _tableName,
                    Key       = new Dictionary <string, AttributeValue>
                    {
                        ["Id"] = new AttributeValue {
                            S = item.Id
                        }
                    }
                };

                await _dynamoDbClient.DeleteItemAsync(deleteRequest);
            }
        }
Example #23
0
        /// <summary>
        /// Delete item from a DynamoDB table.
        /// </summary>
        /// <param name="client">An initialized DynamoDB client.</param>
        /// <param name="table">The table from which the item will be removed.</param>
        /// <param name="id">The Id of the item to remove.</param>
        /// <param name="area">A string representing the value of the Area attribute.</param>
        /// <returns>A DeleteItemResponse object representing the response from the
        /// DeleteItemAsync call.</returns>
        public static async Task <DeleteItemResponse> RemoveItemAsync(
            IAmazonDynamoDB client,
            string table,
            string id,
            string area)
        {
            var request = new DeleteItemRequest
            {
                TableName = table,
                Key       = new Dictionary <string, AttributeValue>()
                {
                    {
                        "ID",
                        new AttributeValue {
                            S = id
                        }
                    },
                    {
                        "Area",
                        new AttributeValue {
                            S = area
                        }
                    },
                },
            };

            var response = await client.DeleteItemAsync(request);

            return(response);
        }
        internal DeleteItemResponse DeleteItem(DeleteItemRequest request)
        {
            var marshaller   = new DeleteItemRequestMarshaller();
            var unmarshaller = DeleteItemResponseUnmarshaller.Instance;

            return(Invoke <DeleteItemRequest, DeleteItemResponse>(request, marshaller, unmarshaller));
        }
Example #25
0
        public async Task ReleaseLock(string Id)
        {
            _lockTracker.Remove(Id);

            try
            {
                var req = new DeleteItemRequest()
                {
                    TableName = _tableName,
                    Key       = new Dictionary <string, AttributeValue>
                    {
                        { "id", new AttributeValue(Id) }
                    },
                    ConditionExpression       = "lock_owner = :node_id",
                    ExpressionAttributeValues = new Dictionary <string, AttributeValue>
                    {
                        { ":node_id", new AttributeValue(_nodeId) }
                    }
                };
                await _client.DeleteItemAsync(req);
            }
            catch (ConditionalCheckFailedException)
            {
            }
        }
Example #26
0
        public HttpResponseMessage Delete(string ticket, int itemId)
        {
            var securityProvider = new SecurityProvider(_connectionString);

            var sessionInfo = securityProvider.GetSessionInfo(ticket);

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

            var deleteRequest = new DeleteItemRequest
            {
                ItemId = itemId,
                UserId = sessionInfo.User.Id,
            };

            var handler = new DeleteItemHandler(_connectionString);

            var response = handler.Handle(deleteRequest);

            var httpStatusCode = ResolveStatusCode(response);

            return(Request.CreateResponse(httpStatusCode, response));
        }
Example #27
0
        //delete query
        public static void DeleteItem(string id, string tableName)
        {
            try
            {
                AmazonDynamoDBClient client;
                using (client = new AmazonDynamoDBClient(MyAWSConfigs.DynamodbRegion))
                {
                    Dictionary <string, AttributeValue> key = new Dictionary <string, AttributeValue>
                    {
                        { "id", new AttributeValue {
                              S = id
                          } },
                    };

                    DeleteItemRequest deleteItemRequest = new DeleteItemRequest
                    {
                        Key       = key,
                        TableName = tableName,
                    };

                    client.DeleteItem(deleteItemRequest);
                }
            }
            catch (AmazonDynamoDBException e)
            {
                Console.WriteLine("AmazonDynamoDBException: " + e);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e);
            }
        }
        public override async Task <DeleteItemResponse> DeleteItem(DeleteItemRequest request, ServerCallContext context)
        {
            try
            {
                var cartCommander = _commandFactory.RepositoryAsync <Domain.Cart>();
                var cartQuery     = _queryFactory.QueryEfRepository <Domain.Cart>();

                var cart = await cartQuery.GetFullCartAsync(request.CartId.ConvertTo <Guid>());

                var cartItem = cart.FindCartItem(request.ProductId.ConvertTo <Guid>());

                cart.RemoveCartItem(cartItem.Id);
                await cart.CalculateCartAsync(TaxType.NoTax, _catalogGateway, _promoGateway, _shippingGateway);

                await cartCommander.UpdateAsync(cart);

                return(new DeleteItemResponse {
                    ProductId = cartItem.Product.ProductId.ToString()
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                throw new RpcException(new Status(StatusCode.Internal, ex.Message));
            }
        }
Example #29
0
        public async Task delete_should_returns_no_content_when_called_with_right_id(DeleteItemRequest request)
        {
            var client   = _factory.CreateClient();
            var response = await client.DeleteAsync($"/api/items/{request.Id}");

            response.StatusCode.ShouldBe(HttpStatusCode.NoContent);
        }
Example #30
0
 public DeleteItemHttpContent(DeleteItemRequest request, string pkName, string?skName, string?tablePrefix) : base("DynamoDB_20120810.DeleteItem")
 {
     _request     = request;
     _pkName      = pkName;
     _skName      = skName;
     _tablePrefix = tablePrefix;
 }