Exemplo n.º 1
0
        public IActionResult Create([FromBody] CreateCategory Request)
        {
            ResponseModel <Category> response = new ResponseModel <Category>();

            try
            {
                Category category = _context.Categories.Where(x => x.Name == Request.Name).FirstOrDefault();
                if (category != null)
                {
                    response.Errors.Add(string.Format("This category with this {0} name already taken!", Request.Name));
                }
                if (response.Errors.Count > 0)
                {
                    return(StatusCode(400, response));
                }
                category = new Category()
                {
                    Name = Request.Name
                };
                _context.Categories.Add(category);
                _context.SaveChanges();
                _context.Entry(category).Reload();
                response.Data = category;
                return(StatusCode(201, response));
            }
            catch (Exception err)
            {
                response.Errors.Add(err.Message);
                return(StatusCode(500, response));
            }
        }
 public Task <CreateCategoryResponse> CreateCategoryAsync(CreateCategory dto)
 {
     return(Task.Run(() =>
     {
         var categoryEntity = _categoryEntityRepository.Table.Where(t => t.TypeId.Equals(dto.type_id) && t.Id.Equals(dto.parent_id)).SingleOrDefault();
         if (categoryEntity == null)
         {
             throw new RequestErrorException("父级分类不存在");
         }
         CategoryEntity entity = new CategoryEntity();
         entity.TypeId = dto.type_id;
         entity.ParentId = dto.parent_id;
         entity.Name = dto.cn_name;
         entity.OffLine = dto.off_line;
         entity.IsHot = dto.is_hot;
         entity.DisplayIndex = dto.displayindex;
         entity.CreatedDate = DateTime.Now;
         entity.IsMultiple = false;
         entity.EnName = dto.en_name;
         entity.SysName = dto.en_name;
         entity.IsSystemCategory = false;
         _categoryEntityRepository.Insert(entity);
         return new CreateCategoryResponse()
         {
             id = entity.Id
         };
     }));
 }
Exemplo n.º 3
0
        private void SubscriptionsPopupNewCategory(object sender, RoutedEventArgs e)
        {
            var treeComponent = (e.OriginalSource as MenuItem)?.DataContext as TreeComponent;

            if (treeComponent == null)
            {
                return;
            }

            var promptDialog = new PromptWindow("Create new category", "Category name");

            if (promptDialog.ShowDialog() == true)
            {
                var category = new Category()
                {
                    Title            = promptDialog.Result,
                    ParentCategoryId = (treeComponent.Item as Category)?.CategoryId
                };
                var newCategoryData = new NewCategoryData()
                {
                    Category            = category,
                    ParentTreeComponent = treeComponent
                };

                CreateCategory?.Invoke(newCategoryData);
            }
        }
Exemplo n.º 4
0
        public bool CreateCategory(CreateCategory model)
        {
            try
            {
                var entity =
                    new Category
                {
                    Id      = model.Id,
                    Name    = model.Name,
                    OwnerId = _userId,
                };

                using (var ctx = new ApplicationDbContext())
                {
                    ctx.Categories.Add(entity);
                    return(ctx.SaveChanges() == 1);
                }
            }
            catch (NullReferenceException)
            {
                return(false);
            }
            catch (ArgumentNullException)
            {
                return(false);
            }
        }
Exemplo n.º 5
0
        public async Task CreateAsync(CreateCategory command)
        {
            await _createValidator.ValidateCommandAsync(command);

            var categoriesCount = await _dbContext.Categories
                                  .Where(x => x.SiteId == command.SiteId && x.Status != StatusType.Deleted)
                                  .CountAsync();

            var sortOrder = categoriesCount + 1;

            var category = new Category(command.Id,
                                        command.SiteId,
                                        command.Name,
                                        sortOrder,
                                        command.PermissionSetId);

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

            await _dbContext.SaveChangesAsync();

            _cacheManager.Remove(CacheKeys.Categories(command.SiteId));
            _cacheManager.Remove(CacheKeys.CurrentForums(command.SiteId));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> CreateCategoryAsync([FromBody] CreateCategory command)
        {
            var category = await _categoryService.AddAsync(command);

            var categoryDto = _mapper.Map <CategoryDto>(category);

            return(Created($"{Request.Host}{Request.Path}/{category.Id}", categoryDto));
        }
Exemplo n.º 7
0
 public static Category ToEntity(this CreateCategory newCategory)
 {
     return(new Category()
     {
         Name = newCategory.Name
         , Description = newCategory.Description
         , CreationDate = newCategory.CreationDate
     });
 }
Exemplo n.º 8
0
        public async Task <IActionResult> Post(CreateCategory command)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(command));
            }

            return(await SendAsync(command.BindId(c => c.Id).Bind(c => c.UserId, UserId), resourceId : command.Id,
                                   resource : "categories"));
        }
        public async Task <Category> AddAsync(CreateCategory command)
        {
            var category = new Category(command.Name);

            await _context.Categories.AddAsync(category);

            await _context.SaveChangesAsync();

            return(category);
        }
Exemplo n.º 10
0
 public RegisteredCategory Create(CreateCategory newRegistry)
 {
     using (LogisticDataContext logisticDataContext = new LogisticDataContext())
     {
         var newCategory = newRegistry.ToEntity();
         logisticDataContext.Categories.Add(newCategory);
         logisticDataContext.SaveChanges();
         return(newCategory.toDTO());
     }
 }
        public async Task Should_Create_A_Category_With_Given_Description()
        {
            var command = new CreateCategory {
                Description = "Implants"
            };
            var newCategoryCode = await _handler.Handle(command);

            Assert.IsNotNull(_context.Categories.Find(newCategoryCode));
            Assert.AreEqual(command.Description, _context.Categories.Find(newCategoryCode).Description);
        }
Exemplo n.º 12
0
        public async void Should_Create_Category()
        {
            this.server.PrepareUser(UserFixture.User);
            this.server.PrepareCategory(CategoryFixture.Root);
            var toCreate = new CreateCategory(CategoryFixture.Root.Id, "new", default(Guid));

            var response = await client.Create(toCreate);

            response.HasStatusCode(HttpStatusCode.OK);
        }
        public Task <int> CreateAsync(CreateCategory model)
        {
            if (model.Type == CategoryType.DepositOnly)
            {
                model.GenerateUpcomingExpense = false;
            }

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

            return(_categoriesRepository.CreateAsync(category));
        }
Exemplo n.º 14
0
 public ActionResult CreateCategory(CreateCategory model)
 {
     if (ModelState.IsValid)
     {
         BlogSystem.IBLL.IArticleManager articleManager = new ArticleManager();
         articleManager.CreateCategory(model.CategoryName, Guid.Parse(Session["userId"].ToString()));
         return(RedirectToAction("CategoryList"));
     }
     ModelState.AddModelError(key: "", errorMessage: "您的信息有误!");
     return(View(model));
 }
Exemplo n.º 15
0
        public async Task <IActionResult> Add(CreateCategory category)
        {
            if (ModelState.IsValid)
            {
                await _categoryService.CreateAsync(category);

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

            return(View(category));
        }
Exemplo n.º 16
0
        public async Task <IHttpActionResult> Post(CreateCategory item)
        {
            if (ModelState.IsValid)
            {
                CategoryDto category = _mapper.Map <CreateCategory, CategoryDto>(item);
                category = await _categoryService.Create(category);

                return(Ok(category));
            }

            return(BadRequest(ModelState));
        }
    /// <summary>
    /// This Draws the Right Hand Panel that shows the "Create Category" options
    /// </summary>
    void DrawRightHandCreateCategoryPanel()
    {
        //have the name be the only permanent option
        cName = EditorGUILayout.TextField("Name: ", cName);

        //==STRINGS==
        //draw all of the strings that we've made
        DrawAllListItems("String Name: ", strings);
        //have a button to create new strings
        DrawAddFieldButton("Add A String", strings);

        //==FLOATS==
        //draw all of the floats
        DrawAllListItems("Float Name: ", floats);
        //have a button to add a float
        DrawAddFieldButton("Add A Float", floats);

        //==INTS==
        //draw all of the ints
        DrawAllListItems("Int Name: ", ints);
        //have a button to add an int
        DrawAddFieldButton("Add An Int", ints);

        //==BOOLS==
        //draw all of the bools
        DrawAllListItems("Bool Name: ", bools);
        //have a button to add a bool
        DrawAddFieldButton("Add A bool", bools);

        //==VECTOR 3S==
        //draw all of the Vector3s
        DrawAllListItems("Vector3 Name: ", vector3s);
        //have a button to add a vector3
        DrawAddFieldButton("Add A Vector3", vector3s);
        //!!!ADD ADDITIONAL VARIABLES HERE!!!

        GUILayout.Space(spaceBetweenButtons);

        //Save all current entered fields into a new Category
        if (GUILayout.Button("Create Category"))
        {
            currentCategoryDataHolder = new CategoryDataHolder();

            currentCategoryDataHolder.PopulateDataStructure(cName, strings, floats, ints, bools, vector3s);
            //!!!ADD ADDITIONAL VARIABLES HERE!!!

            //Create the Category using the variables we've made
            CreateCategory.CreateCategoryObject(currentCategoryDataHolder);

            //Clear our global variables
            ResetData();
        }
    }
Exemplo n.º 18
0
        public async Task CreateCategory_InvalidData_ShouldReturnBadRequest(string name)
        {
            var command = new CreateCategory
            {
                Name = name
            };
            var payload = GetPayload(command);

            var response = await Client.PostAsync(BaseUrl, payload);

            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }
Exemplo n.º 19
0
        protected void btnCreate_Click(object sender, EventArgs e)
        {
            var    folder   = Server.MapPath("~/uploads");
            string fileName = Path.GetFileName(FileUploadImage.PostedFile.FileName);
            string filePath = "~/uploads/" + fileName;

            //string fileExtension = Path.GetExtension(FileUploadImage.FileName);



            if (FileUploadImage.HasFile)
            {
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }
                else
                {
                    lblAlert.Text = "Folder already exists";
                }

                if (NameTB.Text == "")
                {
                    lblAlert.Text = "Category name cannot be empty";
                }
                else
                {
                    FileUploadImage.PostedFile.SaveAs(Server.MapPath(filePath));


                    CreateCategory cat = new CreateCategory(NameTB.Text, filePath);

                    int result = cat.AddNewCategory();
                    if (result == 1)
                    {
                        lblAlert.Text      = "category created";
                        lblAlert.ForeColor = Color.Green;
                        Response.Redirect("ViewAllCategory.aspx");
                    }
                    else
                    {
                        lblAlert.Text      = "Unable to create a category";
                        lblAlert.ForeColor = Color.Red;
                    }
                }
            }
            else
            {
                lblAlert.Text      = "Please choose a file to upload";
                lblAlert.ForeColor = Color.Red;
            }
        }
Exemplo n.º 20
0
        // POST api/<controller>
        public async Task <IHttpActionResult> Post([FromBody] CreateCategory value)
        {
            try
            {
                await _commandBus.SendAsync(value);

                return(ResponseMessage(Request.CreateResponse(HttpStatusCode.Created, value.Category.Guid)));
            }
            catch (Exception error)
            {
                return(InternalServerError(error));
            }
        }
Exemplo n.º 21
0
        public async Task <Category> Handle(CreateCategory message, CancellationToken cancellationToken)
        {
            var category = new Category()
            {
                Name     = message.Name,
                ParentId = message.ParentId,
                UserId   = message.UserId
            };

            var created = categoryRepository.Create(category);
            await categoryRepository.Save();

            return(created);
        }
Exemplo n.º 22
0
        public void createCategory()
        {
            CreateCategory newCategory = new CreateCategory();

            newCategory.ShowDialog();

            CategoryModel ctg      = new CategoryModel(newCategory.categoryName);
            ListViewItem  category = new ListViewItem(newCategory.categoryName, _form.listViewLibrary.Groups[2]);

            category.Selected = true;

            categories.Add(ctg);
            _form.listViewLibrary.Items.Add(category);
            Json.saveToJson(@".\categories.json", categories);
        }
Exemplo n.º 23
0
        public IActionResult Create(CreateCategory model)
        {
            if (ModelState.IsValid)
            {
                var result = new CreateCategoryResult();
                result = Helper.ApiHelper <CreateCategoryResult> .HttpPostAsync("api/category/create", "POST", model);

                if (result.CategoryId > 0)
                {
                    return(RedirectToAction("tables"));
                }
                ModelState.AddModelError("", result.Message);
                return(View(model));
            }
            return(View(model));
        }
Exemplo n.º 24
0
        public void HandleAsync_ShouldInvokeSpecificMethods()
        {
            var command = new CreateCategory
            {
                ResourceId = Guid.NewGuid(),
                Name       = "name"
            };

            _handler.Invoking(async x => await x.HandleAsync(command))
            .Should()
            .NotThrow();

            _categoryService.Verify(x => x.CreateAsync(command.ResourceId, command.Name), Times.Once);
            _categoryService.Verify(x => x.GetOrFailAsync(command.ResourceId), Times.Once);
            _eventPublisher.Verify(x => x.PublishAsync(It.IsAny <CategoryCreated>()), Times.Once);
        }
        /// <summary>
        /// function that create view for category main
        /// </summary>
        /// <param name="catid">category id</param>
        /// <param name="projid">project id</param>
        /// <returns>returns updated model to show in the view</returns>
        public CreateCategory CatEditView(int?catid, int projid)
        {
            ReviseDBEntities con = new ReviseDBEntities();
            int    cat           = con.categories.Find(catid).CatId;
            int    limit         = con.projCats.Where(c => c.catId == catid).SingleOrDefault(p => p.projId == projid).totalLimit ?? 0;
            string catName       = con.categories.Find(catid).CatName;
            var    ShowView      = new CreateCategory()
            {
                catid      = cat,
                catname    = catName,
                totalLimit = limit,
                projid     = projid
            };

            return(ShowView);
        }
Exemplo n.º 26
0
 public IActionResult Create(CreateCategory model)
 {
     if (ModelState.IsValid)
     {
         if (categoryRepository.CreateCategory(model) > 0)
         {
             return(RedirectToAction(actionName: "Index", controllerName: "Category"));
         }
         else
         {
             ModelState.AddModelError("", "Tên Danh Mục Đả Tồn Tại");
             return(View(model));
         }
     }
     return(View(model));
 }
Exemplo n.º 27
0
        public async Task Create_Category_Command_Should_Create_Entity()
        {
            var user = new User(Guid.NewGuid(), "*****@*****.**");
            await _dbFixture.InsertAsync(user);

            var command      = new CreateCategory(Guid.NewGuid(), "Category 1", user.Id);
            var creationTask = await _rabbitMqFixture.SubscribeAndGetAsync <CategoryCreated, Category>(_dbFixture.GetEntityTask, command.Id);

            await _rabbitMqFixture.PublishAsync(command);

            var createdEntity = await creationTask.Task;

            createdEntity.Id.ShouldBe(command.Id);
            createdEntity.Name.ShouldBe(command.Name);
            createdEntity.Creator.ShouldBe(command.UserId);
            createdEntity.CreatedAt.ShouldNotBeNull();
        }
        public async Task GivenValidNameCategoryShouldBeCreated()
        {
            var command = new CreateCategory
            {
                Name = "Books",
                DefaultOperationType = OperationTypeEnum.Expense
            };
            var payload  = Payload(command);
            var response = await Client.PostAsync("category", payload);

            response.StatusCode.ShouldBeEquivalentTo(HttpStatusCode.Created);
            response.Headers.Location.ToString().ShouldBeEquivalentTo($"category/{command.Name}");

            var user = await GetCategoryAsync(command.Name);

            user.Name.ShouldBeEquivalentTo(command.Name);
        }
Exemplo n.º 29
0
        public void HandleAsync_Insert_ShouldCreateNewCategory()
        {
            //Arrange
            CreateCategory command = new CreateCategory(Guid.NewGuid(), "Testing Category Name", "testing category deskripsi");

            _stubMongoRepository.Setup(x => x.AddAsync(It.IsAny <Category>())).Verifiable();
            _stubBusPublisher.Setup(x => x.PublishAsync(It.IsAny <CategoryCreated>(), _stubCorrelationContext.Object)).Verifiable();

            var mockCreateCategoryCommand = new CreateCategoryCommand(_stubMongoRepository.Object, _stubBusPublisher.Object);

            //Act
            mockCreateCategoryCommand.HandleAsync(command, _stubCorrelationContext.Object);

            //Assert
            _stubMongoRepository.Verify();
            _stubBusPublisher.Verify();
        }
        public async Task <ActionResult <object> > CreateAsync(CreateCategory model)
        {
            try
            {
                var category = await model.Create(LinnworksClient);

                return(Ok(new
                {
                    category.Id,
                    category.Name
                }));
            }
            catch (LinnworksBadRequestException badRequest)
            {
                return(BadRequest(badRequest.ErrorResponse));
            }
        }
        public HttpResponseMessage Post(CreateCategory model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, ModelState);
            }

            var category = new Category().Merge(model);
            category.UserId = UserId;

            DataContext.Categories.Add(category);
            DataContext.SaveChanges();

            return Request.CreateResponse(
                HttpStatusCode.Created,
                category.AsModel());
        }