Beispiel #1
0
        public async Task UpdateAsync(UpdateCategory command)
        {
            await _updateValidator.ValidateCommandAsync(command);

            var category = await _dbContext.Categories
                           .FirstOrDefaultAsync(x =>
                                                x.SiteId == command.SiteId &&
                                                x.Id == command.Id &&
                                                x.Status != StatusType.Deleted);

            if (category == null)
            {
                throw new DataException($"Category with Id {command.Id} not found.");
            }

            category.UpdateDetails(command.Name, command.PermissionSetId);
            _dbContext.Events.Add(new Event(command.SiteId,
                                            command.UserId,
                                            EventType.Updated,
                                            typeof(Category),
                                            category.Id,
                                            new
            {
                category.Name,
                category.PermissionSetId
            }));

            await _dbContext.SaveChangesAsync();

            _cacheManager.Remove(CacheKeys.Categories(command.SiteId));
            _cacheManager.Remove(CacheKeys.CurrentForums(command.SiteId));
        }
Beispiel #2
0
        public IActionResult Update([FromBody] UpdateCategory Request)
        {
            ResponseModel <Category> response = new ResponseModel <Category>();

            try
            {
                Category category = _context.Categories.Where(x => x.Id == Request.Id).FirstOrDefault();
                if (category == null)
                {
                    response.Errors.Add(string.Format("Theres no category with this {0} id", Request.Id));
                }
                if (response.Errors.Count > 0)
                {
                    return(StatusCode(400, response));
                }
                category.Name = Request.Name;
                _context.SaveChanges();
                _context.Entry(category).Reload();
                response.Data = category;
                return(StatusCode(200, response));
            }
            catch (Exception err)
            {
                response.Errors.Add(err.Message);
                return(StatusCode(500, response));
            }
        }
        public void Should_update_category_without_parent()
        {
            // Arrange
            var command = new UpdateCategory
            {
                Id   = 1,
                Name = "test category"
            };

            var entity = new Category {
                Id = 1, Name = command.Name
            };

            var fakeRepo = new Mock <ICategoryRepository>();

            fakeRepo.Setup(m => m.Update(It.IsAny <Category>())).Returns(entity.Id);
            fakeRepo.Setup(m => m.Find(entity.Id)).Returns(entity);

            // Act
            var res = Task.Run(() => new UpdateCategoryHandler(fakeRepo.Object, _mapper).Handle(command, default)).Result;

            // Assert
            fakeRepo.Verify(x => x.Update(It.IsAny <Category>()), Times.Once());
            fakeRepo.Verify(x => x.Find(entity.Id), Times.Once());
            Assert.Equal(entity, res);
        }
Beispiel #4
0
        private void updateBtn_Click(object sender, EventArgs e)
        {
            if ((ctgry_Txt.Text == ctgry_Name) || (ctgry_Txt.Text == " "))
            {
                MessageBox.Show("Please Update With New Value");
            }

            if ((ctgry_Txt.Text != "") && (ctgry_Txt.Text != ctgry_Name))

            {
                UpdateCategory updateCategory = new UpdateCategory();
                if (updateCategory.updateCategory(ctgry_Id, ctgry_Txt.Text))
                {
                    ctgry_Txt.Text = "";
                    MessageBox.Show("Category is Updated to Database");
                    cnt = 0;

                    fillData.fillDataGridView(this.dataGridView1);
                }
                else
                {
                    MessageBox.Show("Error!! Category:" + ctgry_Txt.Text + " is not Updated to Database");
                }
            }
        }
Beispiel #5
0
        private void updateBtn_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ctgry_Id) || string.IsNullOrEmpty(ctgry_Txt.Text))
            {
                MessageBox.Show("Oops Category is not selected !! Click on Category");
            }

            else

            {
                DialogResult dialogResult = MessageBox.Show("Are You Sure ", "Deleting Category", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    UpdateCategory updateCategory = new UpdateCategory();
                    if (updateCategory.updateCategory(ctgry_Id, ctgry_Txt.Text))
                    {
                        MessageBox.Show("Category is Updated to Database");
                        cnt = 0;
                        fillData.fillDataGridView(this.dataGridView1);
                        ctgry_Txt.Text = "";
                    }
                    else
                    {
                        MessageBox.Show("Error!! Category:" + ctgry_Txt.Text + " is not Updated to Database");
                    }
                }
            }
        }
Beispiel #6
0
        public bool UpdateCategory(UpdateCategory model)
        {
            try
            {
                using (var ctx = new ApplicationDbContext())
                {
                    var entity =
                        ctx
                        .Categories
                        .SingleOrDefault(e => e.Id == model.Id && e.OwnerId == _userId);

                    entity.Name = model.Name;

                    return(ctx.SaveChanges() == 1);
                }
            }
            catch (NullReferenceException)
            {
                return(false);
            }
            catch (ArgumentNullException)
            {
                return(false);
            }
        }
        public void Handle(UpdateCategory message)
        {
            _log.Info("Edit: start to handle [{0}]", message.GetType().Name);

            // TODO: will refactor later
            _mongoClient = new MongoClient(new MongoUrl("mongodb://127.0.0.1:27017"));
            var db = _mongoClient.GetDatabase("magazine");

            if (db == null)
            {
                db = _mongoClient.GetDatabase("magazine");
            }

            var col = db.GetCollection <CategoryViewResponse>("categories");

            if (col == null)
            {
                db.CreateCollection("categories");
                col = db.GetCollection <CategoryViewResponse>("categories");
            }

            var filter = Builders <CategoryViewResponse> .Filter.Eq("_id", message.Key);

            var update = Builders <CategoryViewResponse> .Update.Set("Name", message.Name);

            var result = col.UpdateOne(filter, update);
        }
Beispiel #8
0
        public async Task <IActionResult> Put(Guid id, UpdateCategory command)
        {
            command.Id = id;

            await Dispatcher.SendAsync(command);

            return(NoContent());
        }
Beispiel #9
0
 public async Task <ExecuteResult> Update(UpdateCategory updateCategory)
 {
     return(await categoryRepository.UpdateCategory(new UpdateCategoryDTO
     {
         Id = updateCategory.Id,
         Name = updateCategory.Name,
         AuditedUserId = updateCategory.AuditedUserId
     }));
 }
 public static Category ToEntity(this UpdateCategory updateCategory)
 {
     return(new Category()
     {
         Id = updateCategory.Id
         , Name = updateCategory.Name
         , Description = updateCategory.Description
         , CreationDate = updateCategory.CreationDate
     });
 }
Beispiel #11
0
        public async Task <IActionResult> UpdateCategory(Guid id, [FromBody] UpdateCategory command)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(command));
            }

            return(await SendAsync(command.Bind(c => c.Id, id).Bind(c => c.UserId, UserId), resourceId : command.Id,
                                   resource : "categories"));
        }
Beispiel #12
0
        public async Task <ActionResult> Put(int code, UpdateCategory updateCategory)
        {
            if (code != updateCategory.Code)
            {
                return(BadRequest());
            }

            await _mediator.Send(updateCategory);

            return(NoContent());
        }
        public async Task <IActionResult> Edit(UpdateCategory category)
        {
            if (ModelState.IsValid)
            {
                await _categoryService.UpdateAsync(category);

                return(RedirectToAction("Index", "Home", new { area = "Admin" }));
            }

            return(View(category));
        }
        public async Task UpdateAsync(UpdateCategory model)
        {
            if (model.Type == CategoryType.DepositOnly)
            {
                model.GenerateUpcomingExpense = false;
            }

            var category = _mapper.Map <Category>(model);

            await _categoriesRepository.UpdateAsync(category);
        }
Beispiel #15
0
 public RegisteredCategory Update(UpdateCategory updateRegistry)
 {
     using (LogisticDataContext logisticDataContext = new LogisticDataContext())
     {
         var categoryToUpdate = updateRegistry.ToEntity();
         logisticDataContext.Categories.Attach(categoryToUpdate);
         logisticDataContext.Entry(categoryToUpdate).State = System.Data.Entity.EntityState.Modified;
         logisticDataContext.SaveChanges();
         return(categoryToUpdate.toDTO());
     }
 }
        public ActionResult PUT(int id, UpdateCategory category)
        {
            var service = new CategoryService();

            if (!service.Exists(id))
            {
                return(NotFound());
            }

            service.UpdateCategory(id, category);
            return(NoContent());
        }
Beispiel #17
0
    public void UpdateCategory(int id, UpdateCategory updateCategory)
    {
        if (!Exists(id))
        {
            return;
        }

        var category = DbContext.Categories.First(e => e.CategoryId == id);

        category.Description = updateCategory.Description;
        DbContext.SaveChanges();
    }
        public async Task Put_Should_Send_UpdateCategory_Command()
        {
            var mediatorMock = new Mock <IMediator>();
            var controller   = new CategoriesController(mediatorMock.Object);
            var command      = new UpdateCategory {
                Code = 1
            };

            await controller.Put(1, command);

            mediatorMock.Verify(m => m.Send(command, It.IsAny <CancellationToken>()), Times.Once);
        }
        public async Task Put_Should_Return_HttpNoContent()
        {
            var mediatorMock = new Mock <IMediator>();
            var controller   = new CategoriesController(mediatorMock.Object);
            var command      = new UpdateCategory {
                Code = 1
            };

            var result = await controller.Put(1, command);

            Assert.IsInstanceOfType(result, typeof(NoContentResult));
        }
Beispiel #20
0
        public async Task <Category> Handle(UpdateCategory message, CancellationToken cancellationToken)
        {
            var category = await categoryRepository.Find(message.Id);

            category.Name     = message.Name;
            category.ParentId = message.ParentId;
            category.Color    = message.Color;

            await categoryRepository.Save();

            return(category);
        }
        public async Task <GeneralCategory> Update(UpdateCategory updatedRegistry)
        {
            using (InventoryDB db = new InventoryDB())
            {
                Category categoryToUpdate = await db.Categories.FindAsync(updatedRegistry.Id);

                updatedRegistry.Update(categoryToUpdate);
                await db.SaveChangesAsync();

                return(categoryToUpdate.toDTO());
            }
        }
        public async Task <ActionResult> Update([FromBody] UpdateCategory data, string productFor, string productType)
        {
            try
            {
                var checkData = MH.CheckForDatas("ProductFor", productFor, "ProductType", productType, "ProductDB", "Category");
                if (checkData != null)
                {
                    var objectId = BsonSerializer.Deserialize <Category>(checkData).Id;
                    var filter   = Builders <BsonDocument> .Filter.Eq("_id", objectId);

                    if (data.ProductFor != null)
                    {
                        var objectName = data.ProductFor + "-" + BsonSerializer.Deserialize <Category>(MH.CheckForDatas("_id", objectId, null, null, "ProductDB", "Category")).ProductType;
                        await MH.UpdateCategoryDetails(BsonSerializer.Deserialize <Category>(checkData).Id, productFor, productType, data.ProductFor, "ProductFor", objectName + ".jpg");
                    }
                    if (data.ProductType != null)
                    {
                        var objectName = BsonSerializer.Deserialize <Category>(MH.CheckForDatas("_id", objectId, null, null, "ProductDB", "Category")).ProductFor + "-" + data.ProductType;
                        await MH.UpdateCategoryDetails(BsonSerializer.Deserialize <Category>(checkData).Id, productFor, productType, data.ProductType, "ProductType", objectName + ".jpg");
                    }
                    if (data.Description != null)
                    {
                        var update = await MH.UpdateSingleObject(filter, "ProductDB", "Category", Builders <BsonDocument> .Update.Set("Description", data.Description));
                    }
                    return(Ok(new ResponseData
                    {
                        Code = "200",
                        Message = "Updated",
                        Data = null
                    }));
                }
                else
                {
                    return(BadRequest(new ResponseData
                    {
                        Code = "404",
                        Message = "Category not found",
                        Data = null
                    }));
                }
            }
            catch (Exception ex)
            {
                LoggerDataAccess.CreateLog("CategoryController", "Update", ex.Message);
                return(BadRequest(new ResponseData
                {
                    Code = "400",
                    Message = "Failed",
                    Data = ex.Message
                }));
            }
        }
Beispiel #23
0
 public IActionResult UpdateCategory(UpdateCategory updateCategory)
 {
     if (!ModelState.IsValid)
     {
         return(BadRequest("Enter the correct values"));
     }
     var(result, succeeded) = _commonServices.UpdateCategory(updateCategory);
     if (succeeded)
     {
         return(Ok(result));
     }
     return(BadRequest(result));
 }
        public async Task <IActionResult> Edit(int id, [Bind("CategoryName,Description,Picture")]
                                               UpdateCategory category)
        {
            if (ModelState.IsValid)
            {
                var updatedCategory = Mapper.ToCategory(category);
                await _categoryService.UpdateCategoryAsync(id, updatedCategory);

                return(RedirectToAction(nameof(Index)));
            }

            return(NotFound());
        }
Beispiel #25
0
        public async Task <IHttpActionResult> PutAsync([FromBody] UpdateCategory updateCategory)
        {
            var command = new UpdateCategoryCommand(updateCategory.Title, updateCategory.Id);

            _categoryManager.Update(command);
            if (_domainNotification.HasNotifications())
            {
                _domainNotification.Notify().ToList().ForEach(error => ModelState.AddModelError(error.Key, error.Value));
                return(await Task.FromResult(BadRequest(ModelState)));
            }

            return(await Task.FromResult(Ok(_categoryUpdated.Notify())));
        }
        public async Task <IActionResult> Create([Bind("CategoryName,Description,Picture")] UpdateCategory categories)
        {
            if (!ModelState.IsValid)
            {
                return(View(categories));
            }

            var category = Mapper.ToCategory(categories);

            await _categoryService.CreateCategoryAsync(category);

            return(RedirectToAction(nameof(Index)));
        }
 private void buttonSelectUpdate_Click(object sender, EventArgs e)
 {
     if (isCategorySelected)
     {
         UpdateCategory updateCategory = new UpdateCategory();
         updateCategory.Show();
     }
     else
     {
         UpdateProduct updateProduct = new UpdateProduct();
         updateProduct.Show();
     }
 }
        public async Task UpdateAsync(int id, UpdateCategory command)
        {
            if (await _context.Categories.ExistsInDatabaseAsync(id) == false)
            {
                throw new CorruptedOperationException("Category doesn't exist.");
            }

            var category = await _context.Categories.GetById(id).SingleOrDefaultAsync();

            category.Update(command.Name);

            _context.Categories.Update(category);
            await _context.SaveChangesAsync();
        }
        public async Task UpdateCategory_NotExistingCategory_ShouldReturnBadRequest()
        {
            var id = GuidHelper.GetGuidFromInt(123);

            var command = new UpdateCategory
            {
                Name = "new-name"
            };
            var paylaod = GetPayload(command);

            var response = await Client.PutAsync($"{BaseUrl}/{id}", paylaod);

            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }
Beispiel #30
0
        public object Post(UpdateCategory request)
        {
            try
            {
                icategoryService.UpdateCategory(request.Category);
            }
            catch
            {
                return(null);
            }
            // STATUS CODE

            return(null);
        }
Beispiel #31
0
        public static ResultState UpdateCategory(this DiscourseApi api, int categoryId, string newName, int? parentCategory, string username = DefaultUsername)
        {
            var route = String.Format("/c/{0}", categoryId);
            var data = new UpdateCategory(categoryId, newName, parentCategory);

            var result = api.ExecuteRequest<RestResponse>(route, Method.PUT, true, username, null, data);

            switch (result.StatusCode)
            {
                case (HttpStatusCode) 422:
                    return ResultState.Unchanged;
                case HttpStatusCode.Accepted:
                    return ResultState.Modified;
                default:
                    return ResultState.Error;
                    }
        }
        public HttpResponseMessage Put(UpdateCategory model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, ModelState);
            }

            var category = DataContext.Categories.Find(model.Id);

            if ((category == null) || (category.UserId != UserId))
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            category.Merge(model);
            DataContext.SaveChanges();

            return Request.CreateResponse(HttpStatusCode.NoContent);
        }