Пример #1
0
        public virtual ActionResult UpdateCategory(CategoryEditViewModel model)
        {
            var category = new Category();

            if (model.Parent_Id > 0)
            {
                var parentCategory = _categoryService.GetById(model.Parent_Id);
                category.Parent = parentCategory;
            }
            else
            {
                category.Parent = null;
            }
            category.Id   = model.Id;
            category.Name = model.Name;

            _categoryService.Update(category);

            if (_unitOfWork.SaveAllChanges() > 0)
            {
                return(RedirectToAction(actionName: MVC.admin.Category.ActionNames.DetailsCategory, routeValues: new { Id = model.Id }));
            }
            else
            {
                TempData["updateCategory"] = Helperalert.alert(new AlertViewModel
                {
                    Alert  = AlertOperation.SurveyOperation(StatusOperation.DuplicateName),
                    Status = AlertMode.info
                });
                return(RedirectToAction(actionName: MVC.admin.Category.ActionNames.UpdateCategory,
                                        routeValues: new { Id = model.Id }));
            }
        }
Пример #2
0
        public virtual ActionResult UpdateCategory(int?Id)
        {
            int id;

            if (int.TryParse(Id.ToString(), out id))
            {
                if (_categoryService.IsExistById(id))
                {
                    ViewBag.selectParent = new SelectList(_categoryService.GetAllRoot(), "Id", "Name");
                    var list  = _categoryService.GetById(Id);
                    var model = new CategoryEditViewModel {
                        Id = list.Id, Name = list.Name, Parent_Id = list.Parent.Id
                    };
                    return(View(model: model));
                }
                else
                {
                    return(RedirectToAction(actionName: MVC.admin.Category.ActionNames.Index,
                                            controllerName: MVC.admin.Category.Name));
                }
            }
            else
            {
                return(RedirectToAction(actionName: MVC.admin.Category.ActionNames.Index,
                                        controllerName: MVC.admin.Category.Name));
            }
        }
Пример #3
0
        public async Task <IActionResult> EditCategory(CategoryEditViewModel categoryView)
        {
            if (categoryView.CategoryImage != null)
            {
                using (var memoryStream = new MemoryStream())
                {
                    await categoryView.CategoryImage.CopyToAsync(memoryStream);

                    categoryView.Category.CategoryImage = memoryStream.ToArray();
                    categoryView.Category.ImageMimeType = categoryView.CategoryImage.ContentType;
                }
            }
            if (ModelState.IsValid)
            {
                var category = new Category
                {
                    Name          = categoryView.Category.Name,
                    Price         = categoryView.Category.Price,
                    CategoryImage = categoryView.Category.CategoryImage
                };

                categoryRepository.SaveCategory(categoryView.Category);
                TempData["message"] = $"{categoryView.Category.Name} has been saved";
                return(RedirectToAction("CategoryList"));
            }
            else
            {
                // there is something wrong with the data values
                return(View(categoryView));
            }
        }
Пример #4
0
        public ActionResult EditCategory(CategoryEditViewModel model)
        {
            var item = _mapper.Map <CategoryEditViewModel, Category>(model);

            var result = new DataResponse <int>();

            if (model.CategoryId.Value == 0)
            {
                result = _category.AddCategory(item);
            }
            else
            {
                result = _category.UpdateCategory(item);
            }

            //if (result.Success)
            //{
            //    var data = _mapper.Map<Category, CategoryViewModel>(_category.GetCategory(result.data));

            //    return PartialView("_CategoryListItem", data);
            //}
            //else
            //{
            //    return Json(result);
            //}
            return(Json(result));
        }
Пример #5
0
        public ActionResult EditCategory(int id = 0, int page = 1)
        {
            var _category = _categoryRepository.Category(id);
            CategoryEditViewModel model;

            if (_category != null)
            {
                var _posts = _postRepository.PostsForCategory(_category.UrlSlug, page, PAGESIZE);
                model = new CategoryEditViewModel
                {
                    Category      = _category,
                    IncludedPosts = _posts
                };
            }
            else
            {
                var newCategory = new Category {
                    Id = 0
                };
                model = new CategoryEditViewModel
                {
                    Category      = newCategory,
                    IncludedPosts = null
                };
            }
            return(PartialView("_EditCategory", model));
        }
Пример #6
0
        public ActionResult Edit(CategoryEditViewModel model)
        {
            // Check if the provided data is valid, if not rerender the edit view
            // so the user can correct and resubmit the edit form
            if (ModelState.IsValid)
            {
                // Retrieve the employee being edited from the database
                Category Category = categoryRepository.GetCategory(model.Id);
                // Update the employee object with the data in the model object
                Category.Name = model.Name;

                // If the user wants to change the photo, a new photo will be
                // uploaded and the Photo property on the model object receives
                // the uploaded photo. If the Photo property is null, user did
                // not upload a new photo and keeps his existing photo


                Category updatedCategory = categoryRepository.Update(Category);
                if (updatedCategory != null)
                {
                    return(RedirectToAction("index"));
                }
                else
                {
                    return(NotFound());
                }
            }

            return(View(model));
        }
Пример #7
0
        public ActionResult Create()
        {
            var model = new CategoryEditViewModel();

            loadParentId();
            return(View(model));
        }
 public IActionResult Edit(string id)
 {
     try
     {
         var category = categoryRepository.Get(int.Parse(id));
         if (category != null && !category.IsDelete)
         {
             var edit = new CategoryEditViewModel()
             {
                 ImagePath    = category.ImagePath,
                 CategoryName = category.CategoryName,
                 CategoryId   = category.CategoryId
             };
             return(View(edit));
         }
         else
         {
             ViewBag.id = id;
             return(View("~/Views/Error/CategoryNotFound.cshtml"));
         }
     }
     catch (Exception)
     {
         ViewBag.id = id;
         return(View("~/Views/Error/CategoryNotFound.cshtml"));
     }
 }
Пример #9
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            CategoryListParameter parameter = (CategoryListParameter)e.Parameter;

            ViewModel = new CategoryListViewModel(domainFacade);

            // Just to show the loading wheel.
            await Task.Delay(100);

            IEnumerable <CategoryModel> models = await queryDispatcher.QueryAsync(new ListAllCategory());

            foreach (CategoryModel model in models)
            {
                CategoryEditViewModel viewModel = new CategoryEditViewModel(domainFacade, model.Key, model.Name, model.Description, model.Color);
                if (parameter.Key.Equals(model.Key))
                {
                    viewModel.IsSelected = true;
                }

                ViewModel.Items.Add(viewModel);
            }

            UpdateSelectedItemView();
            ContentLoaded?.Invoke(this, EventArgs.Empty);
        }
        public ActionResult Edit(CategoryEditViewModel model, int id)
        {
            if (ModelState.IsValid)
            {
                var category = _unitOfWork.Categories.Get(id);

                category.Name     = model.Name;
                category.Alias    = model.Name.ToUrlSlug();
                category.ParentId = model.ParentId;

                if (model.Image != null)
                {
                    category.ImageMimeType = model.Image.ContentType;

                    using (MemoryStream ms = new MemoryStream())
                    {
                        model.Image.InputStream.Seek(0, SeekOrigin.Begin);
                        model.Image.InputStream.CopyTo(ms);
                        category.Image = ms.GetBuffer();
                    }
                }

                _unitOfWork.Complete();

                return(RedirectToAction("Index"));
            }

            model.Categories = new SelectList(_unitOfWork.Categories.GetAll(), "Id", "Name", model.ParentId);
            return(View(model));
        }
Пример #11
0
        public async Task <IActionResult> Create(CategoryEditViewModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest("Invalid ModelState"));
                }

                var request = new CreateCategoryRequest
                {
                    RouteName   = model.RouteName,
                    Note        = model.Note,
                    DisplayName = model.DisplayName
                };

                await _categoryService.CreateAsync(request);

                DeleteOpmlFile();

                return(Json(model));
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error Create Category.");

                ModelState.AddModelError("", e.Message);
                return(ServerError(e.Message));
            }
        }
Пример #12
0
        public async Task CanEdit(SliceFixture fixture)
        {
            // Arrange
            var category = new Category
            {
                Name = "Category"
            };

            await fixture.InsertAsync(category);

            // Act
            var editQuery = new Edit.Query
            {
                CategoryId = category.Id
            };

            CategoryEditViewModel viewModel = await fixture.SendAsync(editQuery);

            var command = Mapper.Map <Edit.Command>(viewModel);

            command.Name = "New category name";

            await fixture.SendAsync(command);

            // Assert
            var categoryInDb = await fixture
                               .ExecuteDbContextAsync(db => db
                                                      .Categories
                                                      .FirstOrDefaultAsync(c => c.Id == category.Id));

            categoryInDb.Name.ShouldBe(command.Name);
        }
Пример #13
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            CategoryListParameter parameter = e.GetParameterOrDefault <CategoryListParameter>();

            ViewModel = new CategoryListViewModel(commandDispatcher, navigator);

            // Bind events.
            handlers.Add(eventHandlers.AddUiThread <CategoryCreated>(ViewModel, Dispatcher));
            handlers.Add(eventHandlers.AddUiThread <CategoryRenamed>(ViewModel, Dispatcher));
            handlers.Add(eventHandlers.AddUiThread <CategoryDescriptionChanged>(ViewModel, Dispatcher));
            handlers.Add(eventHandlers.AddUiThread <CategoryColorChanged>(ViewModel, Dispatcher));
            handlers.Add(eventHandlers.AddUiThread <CategoryIconChanged>(ViewModel, Dispatcher));
            handlers.Add(eventHandlers.AddUiThread <CategoryDeleted>(ViewModel, Dispatcher));

            // Just to show the loading wheel.
            await Task.Delay(100);

            IEnumerable <CategoryModel> models = await queryDispatcher.QueryAsync(new ListAllCategory());

            foreach (CategoryModel model in models)
            {
                CategoryEditViewModel viewModel = new CategoryEditViewModel(commandDispatcher, navigator, model.Key, model.Name, model.Description, model.Color, model.Icon);
                if (parameter.Key.Equals(model.Key))
                {
                    viewModel.IsSelected = true;
                }

                ViewModel.Items.Add(viewModel);
            }

            UpdateSelectedItemView();
            ContentLoaded?.Invoke(this, EventArgs.Empty);
        }
Пример #14
0
        public ActionResult Create()
        {
            var model = new CategoryEditViewModel();

            loadParentId();
            return View(model);
        }
        public CategoryEditViewModel LoadCategoryEditViewModel()
        {
            CategoryEditViewModel model = new CategoryEditViewModel();

            List <ICategoryData> categories = _categoryRepository.LoadCategories();

            foreach (ICategoryData category in categories)
            {
                List <SubCategoryViewModel> subCategories = new List <SubCategoryViewModel>();

                foreach (ISubCategoryData subCategory in category.SubCategories)
                {
                    subCategories.Add(new SubCategoryViewModel()
                    {
                        Id    = subCategory.Id,
                        Name  = subCategory.Name,
                        Order = subCategory.Order,
                        Url   = subCategory.Url
                    });
                }

                model.Categories.Add(new CategoryViewModel()
                {
                    Id            = category.Id,
                    IsMainMenu    = category.IsMainMenu,
                    Name          = category.Name,
                    Order         = category.Order,
                    Url           = category.Url,
                    SubCategories = subCategories
                });
            }
            return(model);
        }
        public async Task <IHttpActionResult> EditCategory([FromBody] CategoryEditViewModel newCategory)
        {
            var userId = User.Identity.GetUserId();

            if (userId == null)
            {
                return(this.Unauthorized());
            }

            if (newCategory.Name.Length < 1)
            {
                return(this.BadRequest("Please add category."));
            }

            var category = await uow.CategoryService.GetCategoryById(newCategory.Id);

            if (category == null)
            {
                return(NotFound());
            }

            category.Name = newCategory.Name;

            await uow.CategoryService.EditCategory(category);

            return(Ok("Category is edited"));
        }
Пример #17
0
        public ActionResult Edit([FromBody] CategoryEditViewModel categoryEditView)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Category category = this.category.GetCategoryWithAttributes(categoryEditView.ID);
                    category.Name = categoryEditView.CategoryName;
                    category.CategoryAttributes.Clear();
                    foreach (var item in categoryEditView.AttributesID)
                    {
                        category.CategoryAttributes.Add(new CategoryAttributes()
                        {
                            CategoryAttributeId = item
                        });
                    }
                    this.category.Edit(category);
                    this.category.SaveAll();
                    return(Ok("Category has been changed"));
                }

                return(Ok("Category data is not valid"));
            }
            catch
            {
                return(BadRequest("Category Data is not valid"));
            }
        }
Пример #18
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Name,Description,ShortDescription,Icon")] CategoryEditViewModel newCategoryData)
        {
            if (id != newCategoryData.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                // Старые данные объекта
                Category category = newCategoryData.GetModelByViewModel();

                try
                {
                    db.Update(category);
                    await db.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CategoryExists(newCategoryData.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction("List"));
            }
            return(View(newCategoryData));
        }
Пример #19
0
        public Response CreateCategory(CategoryEditViewModel createRequest)
        {
            return(TryExecute(() =>
            {
                createRequest.Url = createRequest.DisplayName.ConvertToUrl();
                createRequest.Code = createRequest.DisplayName.ConvertToCode();

                var exists = _categoryRepository.Any(c => c.Url == createRequest.Url && c.Code == createRequest.Code);
                if (exists)
                {
                    return new Response {
                        Message = $"CategoryEntity titled {createRequest.DisplayName} already exists."
                    };
                }

                var category = new CategoryEntity
                {
                    Id = Guid.NewGuid(),
                    Url = createRequest.Url,
                    Code = createRequest.Code,
                    Note = createRequest.Note,
                    Position = createRequest.Position,
                    DisplayName = createRequest.DisplayName
                };

                Logger.LogInformation("Adding new categoryEntity to database.");
                _categoryRepository.Add(category);

                return new SuccessResponse();
            }));
        }
Пример #20
0
        public IActionResult Edit(CategoryEditViewModel model, IFormFile upload)
        {
            if (ModelState.IsValid)
            {
                var category = _categoryRepository.GetCategory(model.Id);
                category.Description = model.Description;
                category.Name        = model.Name;

                //File upload
                var dir = "/images/Categories/" + category.Name + "/";
                if (upload != null)
                {
                    if (category.Media == null || upload.FileName != category.Media?.Filename)
                    {
                        var media = _mediaService.InsertMedia(upload, dir);
                        //Delete old media.
                        if (category.Media != null)
                        {
                            _mediaService.Delete(category.Media);
                        }

                        //save new media.
                        category.Media   = media;
                        category.MediaId = media.Id;
                    }
                }
                _categoryRepository.Save(category);
                return(RedirectToAction("Index", "Category", new { Area = "Admin" }));
            }
            return(View(model));
        }
Пример #21
0
        public async Task DoesCategoryEditAsyncWorkCorrectlyWhenImageIsChanged()
        {
            var categoryList = new List <Category>
            {
                new Category
                {
                    Id       = TestCategoryId,
                    Name     = TestCategoryName,
                    ImageUrl = TestImageUrl,
                },
            };

            var service = this.CreateMockAndConfigureService(categoryList, new List <CategoryRecipe>());

            using FileStream stream = File.OpenRead(TestImageName);
            var file = new FormFile(stream, 0, stream.Length, null, stream.Name)
            {
                Headers     = new HeaderDictionary(),
                ContentType = TestImageContentType,
            };

            var categoryToEdit = new CategoryEditViewModel
            {
                Id    = TestCategoryId,
                Name  = "New name",
                Image = file,
            };

            await service.EditAsync(categoryToEdit, TestRootPath);

            var count = categoryList.Count();

            Assert.Equal("New name", categoryList.First().Name);
            Assert.Equal(1, count);
        }
Пример #22
0
        public async Task <ActionResult> AddOrEdit(CategoryEditViewModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(this.Error("数据非法!"));
                }

                var record = await _categoryService.Get(model.Id);

                var isAdd = record == null;

                if (record == null)
                {
                    record = PostCategoryRecord.Create(model.Id);
                }

                model.UpdateRecord(record);

                if (isAdd)
                {
                    await _categoryService.Add(record);
                }

                return(this.Success());
            }
            catch (ValidationException validationException)
            {
                return(this.Error(validationException.Message));
            }
        }
Пример #23
0
        public async Task DoesCategoryEditAsyncThrowsArgumentExceptionWhenCategoryWithThatNameAlreadyExists()
        {
            var categoryList = new List <Category>
            {
                new Category
                {
                    Id       = 1,
                    Name     = TestCategoryName,
                    ImageUrl = TestImageUrl,
                },
                new Category
                {
                    Id       = 2,
                    Name     = TestCategoryName2,
                    ImageUrl = TestImageUrl,
                },
            };

            var service = this.CreateMockAndConfigureService(categoryList, new List <CategoryRecipe>());

            var categoryToEdit = new CategoryEditViewModel
            {
                Id   = 2,
                Name = TestCategoryName,
            };

            await Assert.ThrowsAsync <ArgumentException>(async() => await service.EditAsync(categoryToEdit, string.Empty));
        }
        public async Task <ActionResult> CreateCategory(CategoryEditViewModel categoryViewModel)
        {
            if (ModelState.IsValid)
            {
                var category = categoryViewModel.ToCategory();

                var categoryResult = await _categoryService.Create(category, categoryViewModel.Files,
                                                                   categoryViewModel.ParentCategory, categoryViewModel.Section);

                if (!categoryResult.Successful)
                {
                    ModelState.AddModelError("", categoryResult.ProcessLog.FirstOrDefault());
                }
                else
                {
                    // We use temp data because we are doing a redirect
                    TempData[Constants.MessageViewBagName] = new GenericMessageViewModel
                    {
                        Message     = "Category Created",
                        MessageType =
                            GenericMessages.success
                    };
                    return(RedirectToAction("Index"));
                }
            }
            else
            {
                ModelState.AddModelError("", "There was an error creating the category");
            }

            categoryViewModel.AllCategories = _categoryService.GetBaseSelectListCategories(_categoryService.GetAll());
            categoryViewModel.AllSections   = _categoryService.GetAllSections().ToSelectList();

            return(View(categoryViewModel));
        }
Пример #25
0
        public async Task DoesCategoryEditAsyncWorkCorrectlyWhenImageIsNotChanged()
        {
            var categoryList = new List <Category>
            {
                new Category
                {
                    Id       = TestCategoryId,
                    Name     = TestCategoryName,
                    ImageUrl = TestImageUrl,
                },
            };

            var service = this.CreateMockAndConfigureService(categoryList, new List <CategoryRecipe>());

            var categoryToEdit = new CategoryEditViewModel
            {
                Id   = TestCategoryId,
                Name = "New name",
            };

            await service.EditAsync(categoryToEdit, string.Empty);

            var count = categoryList.Count();

            Assert.Equal("New name", categoryList.First().Name);
            Assert.Equal(1, count);
        }
Пример #26
0
        public async Task <IActionResult> Edit([Bind(include: "Category")]
                                               CategoryEditViewModel categoryBind)
        {
            if (ModelState.IsValid)
            {
                var categoryEntity = await _categoryService.GetCategoryById(categoryBind.Category.Id, true);

                if (categoryEntity == null)
                {
                    return(NotFound());
                }

                _mapper.Map(categoryBind.Category, categoryEntity);

                if (await _categoryService.SaveCategory(categoryEntity) < 1)
                {
                    ModelState.AddModelError("", "Unable to save changes. " +
                                             "Try again, and if the problem persists, " +
                                             "see your system administrator.");

                    _logger.LogError($"Unable to Update the category:  {StringHelper.PrintObjectProps(categoryBind.Category)}");

                    return(View(categoryBind));
                }
            }
            return(RedirectToAction(nameof(Index)));
        }
Пример #27
0
 public IActionResult Edit(CategoryEditViewModel model)
 {
     if (ModelState.IsValid)
     {
         var category = new Category()
         {
             Image        = model.ImagePath,
             CategoryName = model.CategoryName,
             CategoryId   = model.CategoryId,
         };
         var fileName = string.Empty;
         if (model.Image != null)
         {
             string uploadFolder = Path.Combine(webHostEnvironment.WebRootPath, "images/Category");
             fileName = $"{Guid.NewGuid()}_{model.Image.FileName}";
             var filePath = Path.Combine(uploadFolder, fileName);
             using (var fs = new FileStream(filePath, FileMode.Create))
             {
                 model.Image.CopyTo(fs);
             }
             category.Image = fileName;
             if (!string.IsNullOrEmpty(model.ImagePath))
             {
                 string delFile = Path.Combine(webHostEnvironment.WebRootPath, "images/Category", model.ImagePath);
                 System.IO.File.Delete(delFile);
             }
         }
         var editCtgr = CategoryRepository.Edit(category);
         if (editCtgr != null)
         {
             return(RedirectToAction("Dashboard", new { id = category.CategoryId }));
         }
     }
     return(View(model));
 }
Пример #28
0
        public ActionResult Create([Bind(Exclude = "Id")] CategoryEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                Category category = categoryService.AddOrUpdate(model);

                ActionResult action = RedirectToAction("Index");

                if (settingService.Get <bool>(SettingField.ShowCategoryTutorial))
                {
                    settingService.Set(SettingField.ShowCategoryTutorial, false);
                    action = RedirectToAction("Welcome", "Home");
                }

                if (model.OnCompleteAction == OnCompleteActionType.AddNew)
                {
                    loadParentId();
                    action = View(new CategoryEditViewModel {
                        OnCompleteAction = OnCompleteActionType.AddNew
                    });
                }
                if (model.OnCompleteAction == OnCompleteActionType.CloneNew)
                {
                    loadParentId();
                    action = View(model);
                }

                return(action
                       .WithSuccess(string.Format("Category \"{0}\" has been added".TA(), category.Name)));
            }

            loadParentId();
            return(View(model));
        }
Пример #29
0
        public IActionResult Create(CategoryEditViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var request = new CreateCategoryRequest
                    {
                        Title       = model.Name,
                        Note        = model.Note,
                        DisplayName = model.DisplayName
                    };

                    var response = _categoryService.CreateCategory(request);
                    if (response.IsSuccess)
                    {
                        DeleteOpmlFile();
                        return(RedirectToAction(nameof(Manage)));
                    }

                    Logger.LogError($"Create category failed: {response.Message}");
                    ModelState.AddModelError("", response.Message);
                    return(View("CreateOrEdit", model));
                }

                return(View("CreateOrEdit", model));
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error Create Category.");

                ModelState.AddModelError("", e.Message);
                return(View("CreateOrEdit", model));
            }
        }
Пример #30
0
        public ActionResult DoEdit(CategoryEditViewModel model)
        {
            JsonResult result = new JsonResult();

            if ((model != null) && (ModelState.IsValid))
            {
                CategoryDTO category = MapCategoryViewModelToCategoryDTO(model);
                try
                {
                    _bl.Categories.Update(category);
                    result.Data = new { Code = 0, Message = "OK" };
                }
                catch (NoteCustomException e)
                {
                    result.Data = new { Code = -1, Message = e.Message };
                }
                catch (Exception e)
                {
                    result.Data = new { Code = -2, Message = e.Message };
                }
            }
            else
            {
                result.Data = new { Code = -3, Message = "Ошибка проверки данных" };
            }
            return(result);
        }
Пример #31
0
        public IActionResult Edit(int CategoryId)
        {
            Category cat = _catService.Query(x => x.CategoryId == CategoryId).FirstOrDefault();

            TempData["categoryId"] = CategoryId.ToString();
            //_httpContextAccessor.HttpContext.Session.SetString("categoryId", CategoryId.ToString());

            CategoryEditViewModel VM = new CategoryEditViewModel
            {
                CategoryId   = cat.CategoryId,
                CategoryName = cat.CategoryName,
                Description  = cat.Description,
                ImageUrl     = cat.ImageUrl
            };

            // Creating a list of hampers attached to this category:
            bool HampersExist = false;

            if (_hamperService.Query(x => x.CategoryId == cat.CategoryId).Count() != 0)
            {
                HampersExist    = true;
                ViewBag.Hampers = _hamperService.Query(x => x.CategoryId == cat.CategoryId);
            }
            ViewBag.HampersExist = HampersExist;
            return(View(VM));
        }
 public ActionResult Create(CategoryEditViewModel category)
 {
     if (ModelState.IsValid)
     {
         var domainModel = Mapper.Map<Category>(category);
         _categoryService.Create(domainModel);
         return RedirectToAction("Index");
     }
     else
     {
         SetRelatedItemsInViewBag();
         return View(category);
     }
 }
Пример #33
0
        public Category AddOrUpdate(CategoryEditViewModel model)
        {
            Category category;
            if (model.Id == 0)
            {
                category = Mapper.Map<Category>(model);
                db.Categories.Add(category);
            }
            else
            {
                category = Find(model.Id);
                Mapper.Map(model, category);

                if (model.ParentId != null)
                {
                    // Check for recursion
                    var parentId = model.ParentId;
                    int counter = 0;
                    while (parentId.HasValue)
                    {
                        parentId = Find(parentId.Value).ParentId;
                        if (++counter >= 20)
                        {
                            model.ParentId = null;
                            break;
                        }
                    }
                }
            }

            db.SaveChanges();

            cacheService.Invalidate("categories");

            return category;
        }
Пример #34
0
 public ActionResult EditCategory(CategoryEditViewModel category)
 {
     Mapper.CreateMap<CategoryEditViewModel, CategoryEdit>();
     editorService.EditCategory(Mapper.Map<CategoryEditViewModel, CategoryEdit>(category));
     return RedirectToAction("Index");
 }
Пример #35
0
        public ActionResult Edit(CategoryEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                Category category = categoryService.AddOrUpdate(model);
                return RedirectToAction("Index")
                    .WithSuccess(string.Format("Category \"{0}\" has been updated".TA(), category.Name));
            }

            loadParentId();
            return View(model);
        }
Пример #36
0
        public ActionResult ProductsJson(HttpPostedFileBase file)
        {
            if (file.ContentLength <= 0) return View();

            var rootPath = Server.MapPath("~/Import");
            var guid = Guid.NewGuid().ToString();
            var path = Path.Combine(rootPath, guid);
            Directory.CreateDirectory(path);
            file.SaveAs(Path.Combine(rootPath, guid + ".zip"));
            using (var zip = new ZipFile(Path.Combine(rootPath, guid + ".zip")))
            {
                zip.FlattenFoldersOnExtract = true;
                zip.ExtractAll(path);
            }
            System.IO.File.Delete(Path.Combine(rootPath, guid + ".zip"));

            var imgIdMap = new Dictionary<Guid, Guid>();
            foreach (var imgFile in Directory.GetFiles(path, "*.jpg"))
            {
                var imgId = Guid.Parse(Path.GetFileNameWithoutExtension(imgFile));
                var dbUpl = db.Uploads.FirstOrDefault(u => u.Id == imgId);
                if (dbUpl == null)
                {
                    dbUpl = new Upload { Type = UploadType.ProductImage };
                    db.Uploads.Add(dbUpl);
                    db.SaveChanges();

                    System.IO.File.Copy(imgFile, Path.Combine(Server.MapPath("~/Storage"), dbUpl.Id.ToString()), true);
                }
                imgIdMap.Add(imgId, dbUpl.Id);
            }

            if (System.IO.File.Exists(Path.Combine(path, "export.json")))
            {
                // TODO: Use text reader for very large jsons
                // Import json
                /*
                using (var sr = new StreamReader(Path.Combine(path, "export.json")))
                using (var reader = new JsonTextReader(sr))
                {
                    while (reader.Read())
                    {
                        if ()
                    }
                }
                */

                dynamic json = JObject.Parse(System.IO.File.ReadAllText(Path.Combine(path, "export.json")));

                var categoryidMap = new Dictionary<int, int>();
                var optCategoryidMap = new Dictionary<int, int>();
                var optMap = new Dictionary<int, int>();
                var prodMap = new Dictionary<int, int>();

                foreach (var category in json.categories)
                {
                    int? parentId = category.parentId;
                    if (parentId != null) parentId = categoryidMap[(int)category.parentId];
                    string name = category.name;
                    var dbCategory = categoryService.FindAll()
                        .FirstOrDefault(c => c.Name == name && c.ParentId == parentId);
                    if (dbCategory == null)
                    {
                        var categoryModel = new CategoryEditViewModel
                                            {
                                                Name = category.name,
                                                Description = category.description,
                                                IsVisible = category.isVisible ?? true,
                                                SortOrder = category.sortOrder ?? 0
                                            };
                        if (category.parentId != null)
                            categoryModel.ParentId = categoryidMap[(int)category.parentId];
                        dbCategory = categoryService.AddOrUpdate(categoryModel);
                    }
                    categoryidMap.Add((int)category.id, dbCategory.Id);
                }

                foreach (var optCategory in json.optionCategories)
                {
                    string name = optCategory.name;
                    var dbOptCategory = db.OptionCategories.FirstOrDefault(c => c.Name == name);
                    if (dbOptCategory == null)
                    {
                        dbOptCategory = new OptionCategory
                                            {
                                                Name = optCategory.name,
                                                Description = optCategory.description,
                                                Type = optCategory.type,
                                                IncludeInFilters = optCategory.includeInFilters
                                            };
                        db.OptionCategories.Add(dbOptCategory);
                        db.SaveChanges();
                    }
                    optCategoryidMap.Add((int)optCategory.id, dbOptCategory.Id);
                }

                foreach (var option in json.options)
                {
                    string name = option.name;
                    int catId = optCategoryidMap[(int)option.optionCategoryId];
                    var dbOpt = db.Options.FirstOrDefault(o => o.Name == name && o.OptionCategoryId == catId);
                    if (dbOpt == null)
                    {
                        dbOpt = new Option
                                {
                                    Name = option.name,
                                    Description = option.description,
                                    OptionCategoryId = catId,
                                };
                        db.Options.Add(dbOpt);
                        db.SaveChanges();
                    }
                    optMap.Add((int)option.id, dbOpt.Id);
                }

                foreach (var product in json.products)
                {
                    string name = product.name;
                    var dbProd = productFinder.FindAll().FirstOrDefault(p => p.Name == name);
                    if (dbProd == null)
                    {
                        var prodModel = new ProductEditViewModel();
                        prodModel.Sku = product.sku;
                        prodModel.Name = product.name;
                        prodModel.Description = product.description;
                        prodModel.Price = product.price ?? 0;
                        prodModel.RetailPrice = product.retailPrice;
                        prodModel.CostPrice = product.costPrice;
                        prodModel.SalePrice = product.salePrice;
                        prodModel.IsFeatured = product.isFeatured;
                        prodModel.IsVisible = product.isVisible;
                        prodModel.CategoryIds = string.Join(",", ((JArray)product.categories).Select(
                            i => categoryidMap[(int)i].ToString()));
                        prodModel.Keywords = product.keywords;
                        prodModel.Quantity = product.quantity;
                        prodModel.TaxClassId = product.taxClassid;
                        prodModel.Weight = product.weight ?? 0;
                        prodModel.OptionIds = string.Join(",", ((JArray)product.options).Select(
                            i => optMap[(int)i].ToString()));
                        if (product.sections != null)
                        {
                            foreach (var sect in product.sections)
                            {
                                var sectModel = new ProductSectionEditViewModel
                                                {
                                                    Title = sect.title,
                                                    Type = sect.type,
                                                    Position = sect.position,
                                                    Settings = sect.settings,
                                                    Priority = sect.priority,
                                                    Text = sect.text
                                                };
                                prodModel.Sections.Add(sectModel);
                            }
                        }
                        if (product.uploads != null)
                        {
                            foreach (var upl in product.uploads)
                            {
                                if (prodModel.UploadIds == null)
                                    prodModel.UploadIds = "";
                                else
                                    prodModel.UploadIds += ",";
                                prodModel.UploadIds += imgIdMap[(Guid)upl.id];
                            }
                        }
                        if (product.skus != null)
                        {
                            foreach (var sku in product.skus)
                            {
                                var optIds = new List<int>();
                                if (sku.options != null)
                                {
                                    foreach (int optId in sku.options)
                                    {
                                        optIds.Add(optMap[optId]);
                                    }
                                }
                                var uploadIds = new List<Guid>();
                                if (sku.uploads != null)
                                {
                                    foreach (var uplId in sku.uploads)
                                    {
                                        uploadIds.Add(imgIdMap[(Guid)uplId]);
                                    }
                                }
                                prodModel.Skus.Skus.Add(
                                    new ProductSkuEditViewModel
                                    {
                                        Sku = sku.sku,
                                        Price = sku.price,
                                        Quantity = sku.quantity,
                                        UPC = sku.upc,
                                        Weight = sku.weight,
                                        OptionIds = JsonConvert.SerializeObject(optIds.ToArray()),
                                        UploadIds = JsonConvert.SerializeObject(uploadIds.ToArray())
                                    });
                            }
                        }
                        dbProd = productService.CreateOrUpdate(prodModel);
                    }
                    prodMap.Add((int)product.id, dbProd.Id);
                }
            }

            return View().WithInfo(
                "Data import has been initiated. You will receive notification as soon as the import is completed".TA());
        }
Пример #37
0
 public ActionResult DeleteCategory(CategoryEditViewModel category)
 {
     editorService.DeleteCategory(category.CategoryId);
     return RedirectToAction("Index");
 }
 public ActionResult Edit(int id, CategoryEditViewModel category)
 {
     if (ModelState.IsValid)
     {
         var categoryInDb = _categoryService.GetById(id);
         var updatedModel = Mapper.Map(category, categoryInDb);
         _categoryService.Update(updatedModel);
         return RedirectToAction("Index");
     }
     else
     {
         SetRelatedItemsInViewBag();
         return View(category);
     }
 }