public List<CategoryDTO> GetAllCategory()
        {
            List<CategoryDTO> list = new List<CategoryDTO>();

            try
            {
                SqlDataReader reader = ConnectionManager.GetCommand("SP0201ALL",
                                                                    new Dictionary<string, SqlDbType>() { },
                                                                    new List<object>() { }).ExecuteReader();

                while (reader.Read())
                {
                    CategoryDTO categoryDto = new CategoryDTO();
                    categoryDto.CategoryId = reader["CategoryID"].ToString();
                    categoryDto.CategoryName = reader["CategoryName"].ToString();
                    categoryDto.CreatedDate = (DateTime)reader["CreatedDate"];
                    categoryDto.UpdatedDate = (DateTime)reader["UpdatedDate"];
                    list.Add(categoryDto);
                }

                reader.Close();
            }
            catch (Exception e)
            {
                Log.Error("Error at AuthorDAO - GetAllCategory", e);
                return null;
            }

            return list;
        }
        public CategoryDTO GetCategoryById(String categoryId)
        {
            CategoryDTO categoryDto = null;

            try
            {
                SqlDataReader reader = ConnectionManager.GetCommand("SP0201CI",
                                                                    new Dictionary<string, SqlDbType>() { { "@Param1", SqlDbType.NVarChar } },
                                                                    new List<object>() { categoryId }).ExecuteReader();

                if (reader.Read())
                {
                    categoryDto = new CategoryDTO();
                    categoryDto.CategoryId = reader["CategoryID"].ToString();
                    categoryDto.CategoryName = reader["CategoryName"].ToString();
                    categoryDto.CreatedDate = (DateTime)reader["CreatedDate"];
                    categoryDto.UpdatedDate = (DateTime)reader["UpdatedDate"];
                }
            }
            catch (Exception e)
            {
                Log.Error("Error at CategoryDAO - GetCategoryByID", e);
                return null;
            }

            return categoryDto;
        }
 public static CategoryDTO CreateFromCategory(Category category)
 {
     CategoryDTO categoryDTO = new CategoryDTO();
     categoryDTO.CategoryID = category.CategoryID;
     categoryDTO.Name = category.CategoryName;
     categoryDTO.Description = category.Description;
     return categoryDTO;
 }
 public ActionResult Edit(int id)
 {
     CategoriesDAL c = new CategoriesDAL();
     CategoryDTO dto = new CategoryDTO();
     dto = c.GetCategoryByID(id);
     CategoryModel model = new CategoryModel();
     model.id_categ = dto.id_categ;
     model.categ_name = dto.categ_name;
     return View(model);
 }
        protected void Setup()
        {
            CategoryDTO category = new CategoryDTO();
            
            PropertyInfo propertyInfo = category.GetType().GetProperty("Name");
            if (propertyInfo == null) return;
            var attr = (ColumnAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(ColumnAttribute));
            if(attr == null) return;

            this._metaDataColumn =  new MetaDataColumn(propertyInfo,attr);
        }
        public CatalogueDTO GetCatalogueById(String isbn)
        {
            CatalogueDTO catalogueDto = null;

            try
            {
                SqlDataReader reader = ConnectionManager.GetCommand("SP0101ISBN",
                                                                    new Dictionary<string, SqlDbType>() { { "@Param1", SqlDbType.NVarChar } },
                                                                    new List<object>() { isbn }).ExecuteReader();

                if (reader.Read())
                {
                    catalogueDto = new CatalogueDTO();

                    PublisherDTO publisherDto = new PublisherDTO();
                    CategoryDTO categoryDto = new CategoryDTO();

                    catalogueDto.ISBN = reader["ISBN"].ToString();
                    catalogueDto.Title = reader["Title"].ToString();
                    // add code for get data
                    publisherDto.PublisherId = int.Parse(reader["PublisherID"].ToString());
                    catalogueDto.Publisher = publisherDto;
                    catalogueDto.ShortDescription = reader["ShortDescription"].ToString();
                    // add code for get data
                    categoryDto.CategoryId = reader["CategoryID"].ToString();
                    catalogueDto.Category = categoryDto;
                    catalogueDto.Language = reader["Language"].ToString();
                    catalogueDto.Year = int.Parse(reader["Year"].ToString());
                    catalogueDto.ExpandLimit = int.Parse(reader["ExpandLimit"].ToString());
                    catalogueDto.ExpandDateLimit = int.Parse(reader["ExpandDateLimit"].ToString());
                    catalogueDto.NumberOfCopies = int.Parse(reader["NumberOfCopies"].ToString());
                    catalogueDto.AvailableCopies = int.Parse(reader["AvailableCopies"].ToString());
                    catalogueDto.Price = float.Parse(reader["Price"].ToString());
                    catalogueDto.Image = reader["Image"].ToString();
                    catalogueDto.HitTime = int.Parse(reader["HitTime"].ToString());
                    catalogueDto.RentalTime = int.Parse(reader["RentalTime"].ToString());
                    catalogueDto.CreatedDate = (DateTime) reader["CreatedDate"];
                    catalogueDto.UpdatedDate = (DateTime) reader["UpdatedDate"];
                }

                reader.Close();
            }
            catch (Exception e)
            {
                Log.Error("Error at CatalogueDAO - GetCatalogueByID", e);
                return null;
            }

            return catalogueDto;
        }
Ejemplo n.º 7
0
        public void IntegraCategoria()
        {
            try
            {
                Console.WriteLine("Início do exemplo de integração de categoria");

                int nIdCategoria = 100; //Id da categoria que queremos inserir no exemplo

                //Primeiro buscamos a categoria para ver se esta já existe na VTEX. Esta busca é muito importante
                //para que seja mantido novos dados que venham a existir, fazendo com que seja necessária a alteração
                //apenas dos campos que realmente devem ser preenchidos
                CategoryDTO objCategory = this.vtexService.CategoryGet(nIdCategoria);

                if (objCategory == null)
                {
                    //Instanciamos um objeto do tipo CategoryDTO caso esta categoria não exista na VTEX
                    objCategory = new CategoryDTO();
                }

                objCategory.Id = nIdCategoria;
                objCategory.FatherCategoryId = null; //Nesse caso está sendo criado um departamento, que é uma categoria sem categoria pai
                objCategory.Name = "Nome da categoria";
                objCategory.Title = "Título da categoria";
                objCategory.Description = "Descrição da categoria";
                objCategory.IsActive = true;

                //Enviando os dados para serem inseridos ou atualizados. Note que o retorno padrão dos métodos InsertUpdate
                //é o próprio objeto enviado. Isto ocorre para que se possa recuperar ids auto-incrementos ou mesmo para verificação
                //dos dados por parte do integrador.
                objCategory = this.vtexService.CategoryInsertUpdate(objCategory);

                //Mensagem de sucesso
                Console.WriteLine("Categoria inserida com sucesso");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                Console.WriteLine("Fim do exemplo de integração de categoria");
                Console.ReadKey();
            }
        }
Ejemplo n.º 8
0
        public static List<CategoryDTO> GetAllCategory()
        {
            List<CategoryDTO> rs = new List<CategoryDTO>();

            string query = "select * from db3c04c35a9c6b45918ba3a551005e16ee.category";

            DataTable dt = DataProvider.ExecuteQuery(query);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                CategoryDTO sp = new CategoryDTO();

                    sp.ID = (string)dt.Rows[i]["ID"];
                    sp.Name = (string)dt.Rows[i]["Name"];

                rs.Add(sp);
            }

            return rs;
        }
 public ActionResult Add(CategoryModel model)
 {
     CategoriesDAL category = new CategoriesDAL();
     CategoryDTO dto = new CategoryDTO();
     dto.categ_name = model.categ_name;
     try
     {
         if (ModelState.IsValid)
         {
             category.insertCategory(dto);
             return RedirectToAction("Index");
         }
     }
     catch (DataException)
     {
         //Log the error (add a variable name after DataException) 
         ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
     }
     return View(model);
 }
        public int DeleteCategory(CategoryDTO category)
        {
            try
            {
                ConnectionManager.GetCommand("SP0204",
                                             new Dictionary<string, SqlDbType>()
                                                 {
                                                     {"@Param1", SqlDbType.NVarChar}
                                                 },
                                             new List<object>()
                                                 {
                                                     category.CategoryId
                                                 }).ExecuteNonQuery();

            }
            catch (Exception e)
            {
                Log.Error("Error at CategoryDAO - DeleteCategory", e);
                return 0;
            }

            return 1;
        }
Ejemplo n.º 11
0
 public CategoryOut(InventoryDBContext context, CategoryDTO categoryDTO) : base(categoryDTO)
 {
 }
Ejemplo n.º 12
0
 public async Task Update(CategoryDTO categoryDto)
 {
     var categoryEntity = _mapper.Map <Category>(categoryDto);
     await _categoryRepository.UpdateAsync(categoryEntity);
 }
Ejemplo n.º 13
0
 public Task UpdateAsync(CategoryDTO model)
 {
     throw new NotImplementedException();
 }
 public Int32 SaveCategory(CategoryDTO category)
 {
     using (DelightServiceClient service = new DelightServiceClient())
     {
         return service.SaveCategory(category);
     }
 }
 public IEnumerable <ProductDTO> GetByCategory(CategoryDTO category)
 {
     return(_productMapper.Map <IQueryable <Product>, IEnumerable <ProductDTO> >(_dbcontext.Products.GetByCondition(p => p.CategoryId == category.Id)));
 }
 public int InsertCategory(CategoryDTO category)
 {
     CategoryDAO dao = new CategoryDAO();
     return dao.InsertCategory(category);
 }
Ejemplo n.º 17
0
        public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file)
        {
            //Check model state
            if (!ModelState.IsValid)
            {
                using (Db db = new Db())
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    return(View(model));
                }
            }

            //Make sure productName is unique
            using (Db db = new Db())
            {
                if (db.Products.Any(x => x.Name == model.Name))
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    ModelState.AddModelError("", "That model name is taken");

                    return(View(model));
                }
            }


            //Declare product id
            int id;

            //init and save ProductDTO
            using (Db db = new Db())
            {
                ProductDTO product = new ProductDTO();
                product.Name        = model.Name;
                product.Slug        = model.Name.Replace(" ", "-").ToLower();
                product.Description = model.Description;
                product.Price       = model.Price;
                product.CategoryId  = model.CategoryId;

                CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                model.CategoryName = catDTO.Name;

                db.Products.Add(product);
                db.SaveChanges();

                //Get the Id
                id = product.Id;
            }

            //Set tempData messsage
            TempData["SM"] = "You have added a product!";

            #region Upload Image
            //create necessary directories
            var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

            //check if a file was updated
            var pathString1 = Path.Combine(originalDirectory.ToString(), "Products");
            var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
            var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");
            var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery");
            var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs");

            if (!Directory.Exists(pathString1))
            {
                Directory.CreateDirectory(pathString1);
            }
            if (!Directory.Exists(pathString2))
            {
                Directory.CreateDirectory(pathString2);
            }
            if (!Directory.Exists(pathString3))
            {
                Directory.CreateDirectory(pathString3);
            }
            if (!Directory.Exists(pathString4))
            {
                Directory.CreateDirectory(pathString4);
            }
            if (!Directory.Exists(pathString5))
            {
                Directory.CreateDirectory(pathString5);
            }


            if (file != null && file.ContentLength > 0)
            {
                //Get file extension
                string ext = file.ContentType.ToLower();

                //Verify extension
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Db db = new Db())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "The image was not upload. Wrong image extension!");
                        return(View(model));
                    }
                }

                //Init image name
                string imageName = file.FileName;

                //Save image name to DTO
                using (Db db = new Db())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imageName;

                    db.SaveChanges();
                }


                //Set original and thumb image paths
                var path  = string.Format("{0}\\{1}", pathString2, imageName);
                var path2 = string.Format("{0}\\{1}", pathString3, imageName);

                //Save original
                file.SaveAs(path);

                //Create and save thumb
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }
            #endregion

            //Redirect
            return(RedirectToAction("AddProduct"));
        }
 private string BuildInsertCategoryQuery(Guid guid, CategoryDTO category)
 {
     return(string.Format(@"INSERT INTO Book_Category (category_id, title, description)
                             VALUES ('{0}', '{1}', '{2}')", guid, category.Title, category.Description));
 }
Ejemplo n.º 19
0
        public ActionResult EditProduct(ProductVM model, HttpPostedFileBase uploadPhoto, HttpPostedFileBase uploadPDF)
        {
            // Get product id
            int id = model.Id;

            // Populate categories select list and gallery images
            using (TicketAppDB db = new TicketAppDB())
            {
                model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
            }
            //model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs"))
            //                                    .Select(fn => Path.GetFileName(fn));

            // Check model state
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // Make sure product name is unique
            using (TicketAppDB db = new TicketAppDB())
            {
                if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name))
                {
                    ModelState.AddModelError("", "That product name is taken!");
                    return(View(model));
                }
            }

            using (TicketAppDB db = new TicketAppDB())
            {
                if (uploadPhoto != null && uploadPhoto.ContentLength > 0)
                {
                    var deleteCommand = "DELETE FROM tblPhoto WHERE ProductId = " + id + ";";
                    DbConnection();
                    using (SqlCommand cmd = new SqlCommand(deleteCommand, con))
                    {
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                    var photo = new PhotoDTO
                    {
                        Name        = System.IO.Path.GetFileName(uploadPhoto.FileName),
                        photoType   = photoType.Picture,
                        ContentType = uploadPhoto.ContentType,
                        ProductId   = id
                    };

                    string photoext = Path.GetExtension(photo.Name);
                    var    strings  = new List <string> {
                        ".png", ".jpeg", ".gif", ".jpg"
                    };
                    bool contains = strings.Contains(photoext, StringComparer.OrdinalIgnoreCase);
                    if (!contains)
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "That photo was not uploaded - wrong image extension.");
                        return(View(model));
                    }
                    using (var reader2 = new System.IO.BinaryReader(uploadPhoto.InputStream))
                    {
                        photo.Data = reader2.ReadBytes(uploadPhoto.ContentLength);
                    }

                    model.Photos = new List <PhotoDTO> {
                        photo
                    };
                    db.Photos.Add(photo);
                    db.SaveChanges();
                }
            }

            using (TicketAppDB db = new TicketAppDB())
            {
                if (uploadPDF != null && uploadPDF.ContentLength > 0)
                {
                    var deleteCommand = "DELETE FROM tblPdf WHERE ProductId = " + id + ";";
                    DbConnection();
                    using (SqlCommand cmd = new SqlCommand(deleteCommand, con))
                    {
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                    var invoice = new PdfDTO
                    {
                        Name        = System.IO.Path.GetFileName(uploadPDF.FileName),
                        PdfType     = PDFType.Invoice,
                        ContentType = uploadPDF.ContentType,
                        ProductId   = id
                    };
                    string pdfext = Path.GetExtension(invoice.Name);

                    if (!pdfext.Equals(".pdf", StringComparison.OrdinalIgnoreCase))
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "That pdf was not uploaded - wrong Pdf extension.");
                        return(View(model));
                    }
                    using (var reader = new System.IO.BinaryReader(uploadPDF.InputStream))
                    {
                        invoice.Data = reader.ReadBytes(uploadPDF.ContentLength);
                    }

                    model.Pdfs = new List <PdfDTO> {
                        invoice
                    };
                    db.Pdfs.Add(invoice);
                    db.SaveChanges();
                }
            }


            PdfDTO   pdfs   = new PdfDTO();
            PhotoDTO images = new PhotoDTO();
            string   pdfsName;
            string   imagesName;

            using (TicketAppDB db = new TicketAppDB())
            {
                pdfs       = db.Pdfs.Where(x => x.ProductId == id).FirstOrDefault();
                pdfsName   = pdfs.Name;
                images     = db.Photos.Where(x => x.ProductId == id).FirstOrDefault();
                imagesName = images.Name;
            }
            if (uploadPDF != null)
            {
                pdfsName = uploadPDF.FileName;
            }

            if (uploadPhoto != null)
            {
                imagesName = uploadPhoto.FileName;
            }
            // Update product
            string name = "";

            using (TicketAppDB db = new TicketAppDB())
            {
                ProductDTO dto = db.Products.Find(id);
                dto.Name            = model.Name;
                dto.Slug            = model.Name.Replace(" ", "-").ToLower();
                dto.Description     = model.Description;
                dto.ReservationDate = model.ReservationDate;
                dto.Verified        = model.Verified;
                dto.PdfName         = pdfsName;
                dto.ImageName       = imagesName;
                dto.Price           = model.Price;
                dto.CategoryId      = model.CategoryId;
                name = model.Name;
                CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                //dto.CategoryName = catDTO.Name;

                db.SaveChanges();
            }

            // Set TempData message
            TempData["SM"] = "You have edited '" + name + "'!";


            // Redirect
            return(RedirectToAction("Index", "Dashboard"));
        }
Ejemplo n.º 20
0
        public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file)
        {
            //Получение id продукта
            int id = model.Id;

            //Заполнение списка ктегориями и изображениями
            using (Db db = new Db())
            {
                model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
            }

            model.GalleryImages = Directory
                                  .EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Small"))
                                  .Select(fn => Path.GetFileName(fn));

            //Проверка модели на валидность
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            //Проверка имени продукта на уникальность
            using (Db db = new Db())
            {
                if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name))
                {
                    ModelState.AddModelError("", "Это название рекламы занято");
                    return(View(model));
                }
            }

            //Обновление продукта
            using (Db db = new Db())
            {
                ProductDTO dto = db.Products.Find(id);

                dto.Name        = model.Name;
                dto.Slug        = model.Name.Replace(" ", "-").ToLower();
                dto.Description = model.Description;
                dto.Price       = model.Price;
                dto.CategoryId  = model.CategoryId;
                dto.ImageName   = model.ImageName;

                CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);  //Присваивание текущей категории модели
                dto.CategoryName = catDTO.Name;

                db.SaveChanges();
            }

            //Установка сообщения в TempData
            TempData["M"] = "Вы изменили рекламу";

            //Логика обработки изображений
            #region Image Upload

            //Проверка загрузки файла
            if (file != null && file.ContentLength > 0)
            {
                //Получение расширения файла
                string ext = file.ContentType.ToLower();

                //Проверка расширения
                if (ext != "image/jpg" &&
                    ext != "image/png" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png")
                {
                    using (Db db = new Db())
                    {
                        ModelState.AddModelError("", "Картинка не загружена. Недопустимое расширение.");
                        return(View(model));
                    }
                }

                //Установка путей загрузки
                var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads"));

                var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
                var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Small");

                //Удаление существующих путей и директорий
                DirectoryInfo di1 = new DirectoryInfo(pathString1);
                DirectoryInfo di2 = new DirectoryInfo(pathString2);

                //удаление в основной директории
                foreach (var file2 in di1.GetFiles())
                {
                    file2.Delete();
                }

                //Удаление цменьшенных изображений
                foreach (var file3 in di1.GetFiles())
                {
                    file3.Delete();
                }

                //Сохранение имени изображения
                string imageName = file.FileName;

                using (Db db = new Db())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imageName;

                    db.SaveChanges();
                }

                //Сохранение оригинала и уменьшенной версии
                var path  = string.Format($"{pathString1}\\{imageName}");  //к оригинальному изображению
                var path2 = string.Format($"{pathString2}\\{imageName}");  //к уменьшенному

                //Сохранение оригинального изображения
                file.SaveAs(path);

                //Создание и сохранение уменьшенной картинки
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200).Crop(1, 1);
                img.Save(path2);
            }
            #endregion

            //Переадресация пользователя
            return(RedirectToAction("EditProduct"));
        }
Ejemplo n.º 21
0
        public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file)
        {
            //Проверка модели на валидность
            if (!ModelState.IsValid)
            {
                using (Db db = new Db())
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    return(View(model));
                }
            }

            //Проверка имени продуктa на уникальность
            using (Db db = new Db())
            {
                if (db.Products.Any(x => x.Name == model.Name))
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    ModelState.AddModelError("", "Такое название рекламы уже существует.");
                    return(View(model));
                }
            }

            //Объявление переменной ProductId
            int id;

            //Инициализация и сохранение модели на основе ProductDTO
            using (Db db = new Db())
            {
                ProductDTO product = new ProductDTO();

                product.Name        = model.Name;
                product.Slug        = model.Name.Replace(" ", "-").ToLower();;
                product.Description = model.Description;
                product.Price       = model.Price;
                product.CategoryId  = model.CategoryId;

                CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                product.CategoryName = catDTO.Name;

                db.Products.Add(product);
                db.SaveChanges();

                id = product.Id;
            }

            //Вывод сообщения в TempData
            TempData["M"] = "Вы добавили рекламу";

            #region Upload Image

            //Создание ссылок на директории
            var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads"));

            var pathString1 = Path.Combine(originalDirectory.ToString(), "Products");
            var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
            var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Small");
            var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery");
            var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Small");

            //Проверка на существование директорий, создание если нужно
            if (!Directory.Exists(pathString1))
            {
                Directory.CreateDirectory(pathString1);
            }

            if (!Directory.Exists(pathString2))
            {
                Directory.CreateDirectory(pathString2);
            }

            if (!Directory.Exists(pathString3))
            {
                Directory.CreateDirectory(pathString3);
            }

            if (!Directory.Exists(pathString4))
            {
                Directory.CreateDirectory(pathString4);
            }

            if (!Directory.Exists(pathString5))
            {
                Directory.CreateDirectory(pathString5);
            }

            //Проверка на загрузку файла
            if (file != null && file.ContentLength > 0)
            {
                //Получение расширения файла
                string ext = file.ContentType.ToLower();

                //Проверка расширения файла
                if (ext != "image/jpg" &&
                    ext != "image/png" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png")
                {
                    using (Db db = new Db())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "Картинка не загружена. Недопустимое расширение.");
                        return(View(model));
                    }
                }

                //Объявление переменной с именем изображения
                string imageName = file.FileName;

                //Сохранение имени в модель DTO
                using (Db db = new Db())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imageName;

                    db.SaveChanges();
                }

                //Назначение пути к оригинальному и уменьшенному изображению
                var path  = string.Format($"{pathString2}\\{imageName}");  //к оригинальному изображению
                var path2 = string.Format($"{pathString3}\\{imageName}");  //к уменьшенному

                //Сохранение оригинального изображения
                file.SaveAs(path);

                //Создание и сохранение уменьшенной картинки
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200).Crop(1, 1);
                img.Save(path2);
            }

            #endregion

            //Переадресовка пользователя
            return(RedirectToAction("AddProduct"));
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            CategoryBUS bus = new CategoryBUS();
            if (txtCategoryID.ReadOnly == true)
            {
                if (String.IsNullOrEmpty(txtCategoryName.Text))
                {
                    MessageBox.Show(Resources.ADD_NULL_CATEGORY_NAME);
                    txtCategoryName.Focus();
                }
                else
                {
                    CategoryDTO category = (CategoryDTO) grvCategory.GetFocusedRow();
                    category.CategoryName = txtCategoryName.Text;
                    if (bus.UpdateCategory(category) == 1)
                    {
                        MessageBox.Show(Resources.ADD_CATEGORY_SUCCESS);
                        grdCategory.RefreshDataSource();
                    }
                    else
                    {
                        MessageBox.Show(Resources.ADD_CATEGORY_FAIL);
                    }
                }
            }
            else
            {
                if (String.IsNullOrEmpty(txtCategoryID.Text))
                {
                    MessageBox.Show(Resources.ADD_NULL_CATEGORY_ID);
                    txtCategoryID.Focus();
                }
                else
                {
                    if(String.IsNullOrEmpty(txtCategoryName.Text))
                    {
                        MessageBox.Show(Resources.ADD_NULL_CATEGORY_NAME);
                        txtCategoryName.Focus();
                    }
                    else
                    {
                        if (bus.GetCategoryById(txtCategoryID.Text) != null)
                        {
                            MessageBox.Show(Resources.ADD_EXISTING_CATEGORY_ID);
                        }
                        else
                        {
                            bool Ok = false;
                            if (txtCategoryID.Text.IndexOf('.') == -1)
                            {
                                Ok = true;
                            }
                            else
                            {
                                if (bus.GetCategoryById(txtCategoryID.Text.Substring(0, txtCategoryID.Text.LastIndexOf('.'))) != null)
                                    Ok = true;
                                else Ok = false;
                            }

                            if (Ok)
                            {
                                CategoryDTO category = new CategoryDTO()
                                {
                                    CategoryId = txtCategoryID.Text,
                                    CategoryName = txtCategoryName.Text,
                                    CreatedDate = DateTime.Now,
                                    UpdatedDate = DateTime.Now
                                };
                                if (bus.InsertCategory(category) == 1)
                                {
                                    MessageBox.Show(Resources.ADD_CATEGORY_SUCCESS);
                                    txtCategoryID.ReadOnly = true;
                                    lst.Add(category);
                                    grdCategory.RefreshDataSource();
                                }
                                else
                                {
                                    MessageBox.Show(Resources.ADD_CATEGORY_FAIL);
                                }
                            }
                            else MessageBox.Show(Resources.ADD_ORPHANAGE_CATEGORY);
                        }
                    }

                }
            }
        }
Ejemplo n.º 23
0
        public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file)
        {
            if (!ModelState.IsValid)
            {
                using (Db db = new Db())
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                }
                return(View(model));
            }

            //Make sure productname is unique
            using (Db db = new Db())
            {
                if (db.Products.Any(x => x.Name == model.Name))
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    ModelState.AddModelError("", "That product name id taken!");
                    return(View(model));
                }
            }
            int id;

            using (Db db = new Db())
            {
                ProductDTO productdto = new ProductDTO();
                productdto.Name        = model.Name;
                productdto.Slug        = model.Name.Replace(" ", "-").ToLower();
                productdto.Description = model.Description;
                productdto.Price       = model.Price;
                productdto.CategoryId  = model.CategoryId;

                CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                productdto.CategoryName = catDTO.Name;

                db.Products.Add(productdto);
                db.SaveChanges();

                id = productdto.Id;
            }
            //set tempdata message
            TempData["SM"] = "You have added a product!";

            #region Upload image

            var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

            var pathString1 = Path.Combine(originalDirectory.ToString(), "Products");
            var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
            var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");
            var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery");
            var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs");

            if (!Directory.Exists(pathString1))
            {
                Directory.CreateDirectory(pathString1);
            }
            if (!Directory.Exists(pathString2))
            {
                Directory.CreateDirectory(pathString2);
            }
            if (!Directory.Exists(pathString3))
            {
                Directory.CreateDirectory(pathString3);
            }
            if (!Directory.Exists(pathString4))
            {
                Directory.CreateDirectory(pathString4);
            }
            if (!Directory.Exists(pathString5))
            {
                Directory.CreateDirectory(pathString5);
            }

            if (file != null && file.ContentLength > 0)
            {
                string ext = file.ContentType.ToLower();

                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Db db = new Db())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "The image was not uploaded or wrong image extension");
                    }
                }
                string imageName = file.FileName;
                using (Db db = new Db())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imageName;
                    db.SaveChanges();
                }

                var path  = string.Format("{0}\\{1}", pathString2, imageName);
                var path2 = string.Format("{0}\\{1}", pathString3, imageName);

                file.SaveAs(path);

                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }

            #endregion
            return(RedirectToAction("AddProduct"));
        }
 public int DeleteCategory(CategoryDTO category)
 {
     CategoryDAO dao = new CategoryDAO();
     return dao.DeleteCategory(category);
 }
Ejemplo n.º 25
0
        public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file)
        {
            int id = model.Id;

            using (Db db = new Db())
            {
                model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
            }
            model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs")).Select(fn => Path.GetFileName(fn));
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            using (Db db = new Db())
            {
                if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name))
                {
                    ModelState.AddModelError("", "Products name is taken!");
                    return(View(model));
                }
            }
            using (Db db = new Db())
            {
                ProductDTO dto = db.Products.Find(id);
                dto.Name        = model.Name;
                dto.Slug        = model.Name.Replace(" ", "-").ToLower();
                dto.Description = model.Description;
                dto.Price       = model.Price;
                dto.CategoryId  = model.CategoryId;
                dto.ImageName   = model.ImageName;

                CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                dto.CategoryName = catDTO.Name;
                db.SaveChanges();
            }
            #region ImageUpload
            if (file != null && file.ContentLength > 0)
            {
                string ext = file.ContentType.ToLower();

                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Db db = new Db())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "The image was not uploaded or wrong image extension");
                    }
                }
                var originalDirectory = new DirectoryInfo(String.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

                var pathString1 = Path.Combine(originalDirectory.ToString(), "Products");
                var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");

                DirectoryInfo di1 = new DirectoryInfo(pathString1);
                DirectoryInfo di2 = new DirectoryInfo(pathString2);

                foreach (FileInfo file2 in di1.GetFiles())
                {
                    file2.Delete();
                }
                foreach (FileInfo file3 in di2.GetFiles())
                {
                    file3.Delete();
                }
                string imgName = file.FileName;
                using (Db db = new Db())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imgName;
                    db.SaveChanges();
                }
                var path  = string.Format("{0}\\{1}", pathString1, imgName);
                var path2 = string.Format("{0}\\{1}", pathString2, imgName);

                file.SaveAs(path);

                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }
            #endregion

            TempData["SM"] = "You have edited the product!";

            return(RedirectToAction("EditProduct"));
        }
 public int UpdateCategory(CategoryDTO category)
 {
     CategoryDAO dao = new CategoryDAO();
     return dao.UpdateCategory(category);
 }
Ejemplo n.º 27
0
        public async Task <IActionResult> UpdateEntityAsync(CategoryDTO categoryDTO)
        {
            await _categoryService.UpdateEntityAsync(categoryDTO).ConfigureAwait(false);

            return(Ok("İşlem Başarılı"));
        }
 //----------------Delete-------------------
 
 public ActionResult Delete(int id)
 {
     CategoriesDAL c = new CategoriesDAL();
     CategoryDTO dto = new CategoryDTO();
     dto = c.GetCategoryByID(id);
     try
     {
         c.deleteCategory(dto);
         return RedirectToAction("Index");
     }
     catch (DataException)
     {
         //Log the error (add a variable name after DataException) 
         ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
     }
     return View();
 }
        public int UpdateCategory(CategoryDTO category)
        {
            category.UpdatedDate = DateTime.Now;
            try
            {
                ConnectionManager.GetCommand("SP0203",
                                             new Dictionary<string, SqlDbType>()
                                                 {
                                                     {"@Param1", SqlDbType.NVarChar},
                                                     {"@Param2", SqlDbType.NVarChar},
                                                     {"@Param3", SqlDbType.DateTime},
                                                     {"@Param4", SqlDbType.DateTime}
                                                 },
                                             new List<object>()
                                                 {
                                                     category.CategoryId,
                                                     category.CategoryName,
                                                     category.CreatedDate,
                                                     category.UpdatedDate
                                                 }).ExecuteNonQuery();

            }
            catch (Exception e)
            {
                Log.Error("Error at CategoryDAO - UpdateCategory", e);
                return 0;
            }

            return 1;
        }
        public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file)
        {
            //sprawdzamy model state
            if (!ModelState.IsValid)
            {
                //kontekst
                using (Database db = new Database())
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    return(View(model));
                }
            }


            // sprawdzenie czy nazwa produktu jest unikalna
            //kontekst
            using (Database db = new Database())
            {
                if (db.Products.Any(x => x.Name == model.Name))
                {
                    model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                    ModelState.AddModelError("", "Ta nazwa produktu jest zajęta");
                    return(View(model));
                }
            }

            //deklaracja prductId
            int id;

            // dodawanie produktu i zapis na bazie
            using (Database db = new Database())
            {
                ProductDTO product = new ProductDTO();
                product.Name        = model.Name;
                product.Slug        = model.Name.Replace(" ", "-").ToLower();
                product.Description = model.Description;
                product.Price       = model.Price;
                product.CategoryId  = model.CategoryId;

                CategoryDTO catDto = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                product.CategoryName = catDto.Name;

                db.Products.Add(product);
                db.SaveChanges();

                // pobranie id dodanego produktu
                id = product.Id;
            }

            //ustawiamy komunikat
            TempData["SM"] = "Dodałeś produkt";

            #region Upload Image

            //utworzenie potrzebnej struktury katalogów
            var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

            var pathString1 = Path.Combine(originalDirectory.ToString(), "Products");
            var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
            var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");
            var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery");
            var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs");

            if (!Directory.Exists(pathString1))
            {
                Directory.CreateDirectory(pathString1);
            }

            if (!Directory.Exists(pathString2))
            {
                Directory.CreateDirectory(pathString2);
            }

            if (!Directory.Exists(pathString3))
            {
                Directory.CreateDirectory(pathString3);
            }

            if (!Directory.Exists(pathString4))
            {
                Directory.CreateDirectory(pathString4);
            }

            if (!Directory.Exists(pathString5))
            {
                Directory.CreateDirectory(pathString5);
            }

            if (file != null && file.ContentLength > 0)
            {
                // sprawdzenie rozszerzenia pliku czy mamy do czynienia z obrazkiem
                string ext = file.ContentType.ToLower();
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Database db = new Database())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "Obraz nie został przesłany - nieprawidłowe rozszerzenie obrazu.");
                        return(View(model));
                    }
                }

                // inicjalizacja nazwy obrazka
                string imgName = file.FileName;

                // zapis nazwy obrazka do bazy
                using (Database db = new Database())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imgName;
                    db.SaveChanges();
                }

                var path  = string.Format("{0}\\{1}", pathString2, imgName);
                var path2 = string.Format("{0}\\{1}", pathString3, imgName);

                //zapisujemy oryginalny obrazek
                file.SaveAs(path);

                //zapisujemy miniaturkę
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }



            #endregion

            return(RedirectToAction("AddProduct"));
        }
Ejemplo n.º 31
0
        public async Task UploadFileAsync(IFormFile uploadeDoc, CategoryDTO category)
        {
            bool isNew = false;

            await _context.Docs.Include(x => x.Versions).LoadAsync();

            var same    = _context.Docs.FirstOrDefault(x => x.Name == uploadeDoc.FileName && x.Category == (Category)category);
            int release = 1;

            if (same != null)
            {
                release = same.Versions.OrderBy(x => x.Release).Last().Release + 1;
            }
            else
            {
                isNew = true;
                same  = new Doc
                {
                    Category = (Category)category,
                    Name     = uploadeDoc.FileName,
                };
                _context.Docs.Add(same);
            }
            //string path = $"{_appEnvironment.ContentRootPath}/Files/{category}_{release}_{uploadeDoc.FileName}";
            string path = $"{_configuration.GetValue<string>("FilesPath")}/{category}_{release}_{uploadeDoc.FileName}";

            var version = new Models.Version
            {
                Doc            = same,
                Path           = path,
                Release        = release,
                Size           = uploadeDoc.Length,
                UploadDateTime = DateTime.Now,
            };

            _context.Versions.Add(version);
            try
            {
                await _context.SaveChangesAsync();


                if (!Directory.Exists(_configuration.GetValue <string>("FilesPath")))
                {
                    Directory.CreateDirectory(_configuration.GetValue <string>("FilesPath"));
                }

                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    await uploadeDoc.CopyToAsync(fileStream);
                }
            }
            catch (DbUpdateException db)
            {
                throw db;
                //
            }
            catch (Exception fileStriem)
            {
                // + откат изменений в БД

                if (isNew)
                {
                    _context.Remove(same);
                }

                _context.Versions.Remove(version);

                throw fileStriem;
            }
        }
        public List<CategoryDTO> SearchCategory(string info)
        {
            List<CategoryDTO> list = new List<CategoryDTO>();
            CategoryDTO categoryDTO;
            try
            {
                SqlDataReader reader = ConnectionManager.GetCommand("sp0005category",
                                                                    new Dictionary<string, SqlDbType>() { { "@cate", SqlDbType.NVarChar } },
                                                                    new List<object>() { info }).ExecuteReader();

                while (reader.Read())
                {
                    categoryDTO = new CategoryDTO();
                    categoryDTO.CategoryId = reader["categoryID"].ToString();
                    categoryDTO.CategoryName = reader["categoryName"].ToString();
                    categoryDTO.CreatedDate = (DateTime)reader["CreatedDate"];
                    categoryDTO.UpdatedDate = (DateTime)reader["UpdatedDate"];
                    list.Add(categoryDTO);
                }

                reader.Close();
            }
            catch (Exception e)
            {
                Log.Logger.Error("Error at AuthorDAO - GetAuthorByID", e);
                return null;
            }
            return list;
        }
        public static string GetOperationLog(this CategoryDTO entity, CategoryDTO oldDTO = null)
        {
            var sb = new StringBuilder();

            var parentNames = new List <string>();
            var parent      = entity.Parent;

            while (parent != null)
            {
                parentNames.Add(parent.Name);
                parent = parent.Parent;
            }
            parentNames.Reverse();
            var parentNameString = string.Join(" > ", parentNames.ToArray());

            if (oldDTO == null)
            {
                sb.AppendLine(string.Format("{0}: {1}", CommonMessageResources.Sn, entity.Sn));
                sb.AppendLine(string.Format("{0}: {1}", CommonMessageResources.Name, entity.Name));
                sb.AppendLine(string.Format("{0}: {1}", BaseMessagesResources.Parent_Category, parentNameString));
                sb.AppendLine(string.Format("{0}: {1}", CommonMessageResources.SortOrder, entity.SortOrder));
                sb.AppendLine(string.Format("{0}: {1}", BaseMessagesResources.Child_SerialNumberRule_Prefix, entity.ChildSnRulePrefix));
                sb.AppendLine(string.Format("{0}: {1}", BaseMessagesResources.Child_SerialNumberRule_NumberLength, entity.ChildSnRuleNumberLength));
            }
            else
            {
                var oldParentNames = new List <string>();
                var oldParent      = oldDTO.Parent;
                while (oldParent != null)
                {
                    oldParentNames.Add(oldParent.Name);
                    oldParent = oldParent.Parent;
                }
                oldParentNames.Reverse();
                var oldParentNameString = string.Join(" > ", oldParentNames.ToArray());

                if (entity.Sn != oldDTO.Sn)
                {
                    sb.AppendLine(string.Format("{0}: {1} => {2}",
                                                CommonMessageResources.Sn, oldDTO.Sn, entity.Sn));
                }
                if (entity.Name != oldDTO.Name)
                {
                    sb.AppendLine(string.Format("{0}: {1} => {2}",
                                                CommonMessageResources.Name, oldDTO.Name, entity.Name));
                }
                if (parentNameString != oldParentNameString)
                {
                    sb.AppendLine(string.Format("{0}: {1} => {2}",
                                                BaseMessagesResources.Parent_Category, parentNameString, oldParentNameString));
                }
                if (entity.SortOrder != oldDTO.SortOrder)
                {
                    sb.AppendLine(string.Format("{0}: {1} => {2}",
                                                CommonMessageResources.SortOrder, oldDTO.SortOrder, entity.SortOrder));
                }
                if (entity.ChildSnRulePrefix != oldDTO.ChildSnRulePrefix)
                {
                    sb.AppendLine(string.Format("{0}: {1} => {2}",
                                                BaseMessagesResources.Child_SerialNumberRule_Prefix, oldDTO.ChildSnRulePrefix, entity.ChildSnRulePrefix));
                }
                if (entity.ChildSnRuleNumberLength != oldDTO.ChildSnRuleNumberLength)
                {
                    sb.AppendLine(string.Format("{0}: {1} => {2}",
                                                BaseMessagesResources.Child_SerialNumberRule_NumberLength, oldDTO.ChildSnRuleNumberLength, entity.ChildSnRuleNumberLength));
                }
            }

            return(sb.ToString().TrimEnd('\r', '\n'));
        }
Ejemplo n.º 34
0
        public async Task <IActionResult> UpdateCategory(string id, [FromBody] CategoryDTO category)
        {
            await _categoryManager.UpdateCategory(id, _mapper.Map <Category>(category));

            return(Ok());
        }
Ejemplo n.º 35
0
 public void UpdateCategory(CategoryDTO category)
 {
     uow.Categories.Update(mapper.Map <CategoryDTO, Category>(category));
 }
 protected void Setup()
 {
     CategoryDTO category = new CategoryDTO();
     this._metaDataTable = new MetaDataTable(category.GetType(), CategoryDTO.ENTITYNAME);
 }
Ejemplo n.º 37
0
 public void Edit(CategoryDTO DTO)
 {
     DAL.Edit(DTO);
 }
        public IActionResult Update(CategoryDTO categoryDTO)
        {
            _categoryService.Update(_mapper.Map <Category>(categoryDTO));

            return(RedirectToAction("Index"));
        }
        public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file)
        {
            // pobranie id produktu
            int id = model.Id;

            // pobranie kategorii dla listy rozwijanej
            using (Database db = new Database())
            {
                model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
            }

            // ustawiamy zdjecia
            model.GalleryImages = Directory
                                  .EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs"))
                                  .Select(fn => Path.GetFileName(fn));

            // sprawdzamy model state (czy nasz formularz jest poprawnie wypełniony)
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // sprawdzenie unikalności nazwy produktu
            using (Database db = new Database())
            {
                if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name))
                {
                    ModelState.AddModelError("", "Ta nazwa produktu jest zajęta");
                    return(View(model));
                }
            }

            // Edycja produktu i zapis na bazie
            using (Database db = new Database())
            {
                ProductDTO dto = db.Products.Find(id);
                dto.Name        = model.Name;
                dto.Slug        = model.Name.Replace(" ", "-").ToLower();
                dto.Description = model.Description;
                dto.Price       = model.Price;
                dto.CategoryId  = model.CategoryId;
                dto.ImageName   = model.ImageName;

                //sprawdzenie nazwy po idku
                CategoryDTO catDto = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                dto.CategoryName = catDto.Name;

                db.SaveChanges();
            }

            // ustawienie TempData
            TempData["SM"] = "Edytowałeś produkt";

            #region Image Upload

            // sprawdzamy czy jest plik
            if (file != null && file.ContentLength > 0)
            {
                // sprawdzamy rozszerzenie pliku czy to jest obrazek
                string ext = file.ContentType.ToLower();

                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Database db = new Database())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "Obraz nie został przesłany - nieprawidłowe rozszerzenie obrazu.");
                        return(View(model));
                    }
                }

                //utworzenie potrzebnej struktury katalogów
                var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

                var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
                var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");

                // usuwamy stare pliki z katalogów
                DirectoryInfo di1 = new DirectoryInfo(pathString1);
                DirectoryInfo di2 = new DirectoryInfo(pathString2);

                foreach (var file2 in di1.GetFiles())
                {
                    file2.Delete();
                }

                foreach (var file3 in di2.GetFiles())
                {
                    file3.Delete();
                }

                // zapisujemy nazwę obrazkę na bazie
                string imageName = file.FileName;

                using (Database db = new Database())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imageName;
                    db.SaveChanges();
                }

                // Zapis nowych pliku
                var path  = string.Format("{0}\\{1}", pathString1, imageName);
                var path2 = string.Format("{0}\\{1}", pathString2, imageName);

                //zapisujemy plik obrazka
                file.SaveAs(path);

                //zapisujemy plik miniaturki i zmniejszamy wielkość obrazka głównego
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }

            #endregion



            return(RedirectToAction("EditProduct"));
        }
 public CategoryDTO RenameCategory(CategoryDTO category)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 41
0
 public CategoryResponse(CategoryDTO category) : base(string.Empty, true)
 {
     this.category = category;
 }
Ejemplo n.º 42
0
 public void Add(CategoryDTO DTO)
 {
     DAL.Add(DTO);
 }
Ejemplo n.º 43
0
 public void AddCategory(CategoryDTO category)
 {
     uow.Categories.Create(mapper.Map <CategoryDTO, Category>(category));
 }