コード例 #1
0
        public ActionResult Add([Bind] UserPostAddViewModel post)
        {
            if (!(User.IsInRole("Admin") || User.IsInRole("Moderator")))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }


            if (!ModelState.IsValid && !HttpPostedFileBaseExtensions.IsImage(post.ImageFile))
            {
                var categories = _categoryRepo.GetAll();
                var model      = new UserPostAddViewModel();
                model.Categories = categories;
                return(RedirectToAction("Add"));
            }

            var mapedPost = _mapper.Map <UserPostAddViewModel, Post>(post);

            try
            {
                mapedPost.UserId     = User.Identity.GetUserId();
                mapedPost.CategoryId = post.SelectedCategory;
                string imagePath = ResizerImage.UploadImage(post.ImageFile);
                mapedPost.ImagePath = imagePath;
                _postRepo.AddPost(mapedPost);
                _postRepo.SaveChanges();
            }
            catch (Exception e)
            {
                return(RedirectToAction("Add"));
            }
            TempData["addError"] = "false";
            return(RedirectToRoute("PostDetails", new { id = mapedPost.Id, name = post.GetTitleAsUrl() }));
        }
コード例 #2
0
        public ActionResult Index(HttpPostedFileBase file)
        {
            if (HttpPostedFileBaseExtensions.IsImage(file))
            {
                var person = db.People.First();

                string previousAvatarPath = Request.MapPath("~" + person.AvatarLink);

                if (System.IO.File.Exists(previousAvatarPath))
                {
                    System.IO.File.Delete(previousAvatarPath);
                }

                // extract only the filename
                var fileName = Path.GetFileName(file.FileName);
                // store the file inside ~/Content/uploads folder
                var path = Path.Combine(Server.MapPath("~/Content/uploads"), fileName);
                file.SaveAs(path);



                person.AvatarLink = "/Content/uploads/" + fileName;
                db.SaveChanges();
            }
            return(RedirectToAction("Index"));
        }
コード例 #3
0
 internal bool ImageGood(HttpPostedFileBase postFile, string shortName)
 {
     return(HttpPostedFileBaseExtensions.IsImage(postFile) &&
            postFile.ContentLength > 0 &&
            db.Boards
            .Where(b => b.shortName.Equals(shortName))
            .First().maxImageSize > postFile.ContentLength);
 }
コード例 #4
0
        public ActionResult SaveEditedProduct(EditProductViewModel model)
        {
            var proDB = _unitOfWork.Product.GetProductById(model.Id);

            List <ProductImages> images = new List <ProductImages>();
            var pathToSave = _unitOfWork.ProductImage.GetProductImageByProductId(model.Id).FilePath;
            var path       = "~/" + pathToSave;
            var imgPath    = "";

            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];

                if (file != null && file.ContentLength > 0 && HttpPostedFileBaseExtensions.IsImage(file))
                {
                    var           fileName   = Path.GetFileName(file.FileName);
                    ProductImages fileDetail = new ProductImages()
                    {
                        FileName      = fileName,
                        Extension     = Path.GetExtension(fileName),
                        FileNameNoExt = Path.GetFileNameWithoutExtension(fileName),
                        FilePath      = pathToSave
                    };
                    images.Add(fileDetail);

                    imgPath = Path.Combine(Server.MapPath(path), fileDetail.FileName);
                    file.SaveAs(imgPath);
                }
            }
            var newImages = proDB.Images.Concat(images).ToList();

            var PdfPathToSave = "";

            if (model.document != null && model.document.ContentLength > 0)
            {
                string folderDate = DateTime.Now.ToString("yyyyMMddHHmmss");
                Directory.CreateDirectory(Server.MapPath("~/DynamicContent/ProductPDFs/Product" + folderDate));
                var PdfPath = Path.Combine(Server.MapPath("~/DynamicContent/ProductPDFs/Product" + folderDate), model.document.FileName);
                PdfPathToSave = "DynamicContent/ProductPDFs/Product" + folderDate;
                model.document.SaveAs(PdfPath);

                proDB.DocumentPath = PdfPathToSave;
                proDB.DocumentName = model.document.FileName;
            }

            proDB.Images          = newImages;
            proDB.isActive        = model.isActive;
            proDB.Name            = model.Name;
            proDB.Subtitle        = model.Subtitle;
            proDB.Text            = model.Text;
            proDB.Price           = model.Price;
            proDB.MetaDescription = model.MetaDescription;
            proDB.MetaKeywords    = model.MetaKeywords;

            _unitOfWork.Complete();

            return(RedirectToAction("EditProduct", new { id = model.Id }));
        }
コード例 #5
0
        public ActionResult Index([Bind(Include = "tbUserId,Username,Fullname,Password,IsDisable")] tbUser tbUser, HttpPostedFileBase file)
        {
            string userid    = Auth.GetCookie("DUser");
            tbUser tbUserOld = db.tbUsers.Where(x => x.Username == userid).FirstOrDefault();

            if (tbUser == null)
            {
                return(HttpNotFound());
            }

            if (ModelState.IsValid)
            {
                tbUserOld.Fullname = tbUser.Fullname;
                tbUserOld.Password = DreamCMS.Encrypt.DHash.Encrypt(tbUser.Password);

                // AVATAR
                if (file != null)
                {
                    if (HttpPostedFileBaseExtensions.IsImage(file))
                    {
                        string ext = Path.GetExtension(file.FileName).ToLower();
                        //string pic = Path.GetFileName(file.FileName);
                        string path = Path.Combine(Server.MapPath("~/Areas/Admin/upload/avatar"), tbUserOld.Username + ext);
                        //delele old file
                        if (!string.IsNullOrEmpty(tbUserOld.AvatarUrl))
                        {
                            string fullPath = Path.Combine(Server.MapPath("~/Areas/Admin/upload/avatar"), tbUserOld.AvatarUrl);
                            if (System.IO.File.Exists(fullPath))
                            {
                                System.IO.File.Delete(fullPath);
                            }
                        }
                        // file is uploaded
                        file.SaveAs(path);

                        tbUserOld.AvatarUrl = tbUser.Username + ext;
                    }
                }

                db.SaveChanges();
                Auth.ReloadInfoUser();

                ViewBag.MsgResult = true;

                tbUserOld.Password = DreamCMS.Encrypt.DHash.Decrypt(tbUserOld.Password);
                return(View("__Cms/Account/Profile", tbUserOld));
            }

            ViewBag.MsgResult = false;
            ViewBag.MsgText   = "Cập nhật thông tin thất bại!!!";

            tbUserOld.Password = DreamCMS.Encrypt.DHash.Decrypt(tbUserOld.Password);
            return(View("__Cms/Account/Profile", tbUserOld));
        }
コード例 #6
0
        private bool CheckImage(ObjectTypeViewModel objectTypeViewModel)
        {
            objectTypeViewModel.ControlType = _context.ControlTypes.Where(x => x.ControlTypeId == objectTypeViewModel.ControlTypeId).SingleOrDefault();

            //If this is meant to be an image but another file type is used
            if (objectTypeViewModel.ControlType.Name == "Image" &&
                HttpPostedFileBaseExtensions.IsImage(objectTypeViewModel.Image) == false)
            {
                ModelState.AddModelError("", "Please select an image file");
                return(false);
            }
            else
            {
                return(true);
            }
        }
コード例 #7
0
        public ActionResult EditGalleryPanel(FormCollection collection, IEnumerable <HttpPostedFileBase> files)
        {
            if (System.Web.HttpContext.Current.Session["admin"] != null && System.Web.HttpContext.Current.Session["admin"].ToString() == "iamadmin" && files != null && collection != null)
            {
                var pm     = new PanelManagement();
                var thisId = Convert.ToInt32(collection["thisID"], CultureInfo.CurrentCulture);
                switch (collection["submit"])
                {
                case "save":
                    var styleSheet   = Convert.ToInt32(collection["panelDesign"], CultureInfo.CurrentCulture);
                    var header       = collection["hdr"];
                    var menuTag      = collection["menuTag"];
                    var underMenuTag = collection["underMenuTag"];

                    pm.EditGalleryPanel(thisId, styleSheet, header, menuTag, underMenuTag);
                    foreach (var item in files)
                    {
                        if (item != null)
                        {
                            if (HttpPostedFileBaseExtensions.IsImage(item))
                            {
                                pm.AddGalleryImage(thisId, item);
                            }
                        }
                    }

                    this.rc.ClearPanelCache();
                    return(this.Redirect(this.Request.UrlReferrer.ToString()));

                case "cancel":
                    return(this.RedirectToAction("AdminHome", "Admin"));

                case "delete":
                    pm.DeletePanel(thisId);

                    this.rc.ClearPanelCache();
                    return(this.RedirectToAction("AdminHome", "Admin"));

                default:
                    throw new ArgumentNullException("collection");
                }
            }
            else
            {
                return(this.RedirectToAction("AdminLogOn", "Admin"));
            }
        }
コード例 #8
0
        private bool PerformCameraImageUpload(CameraDetails cameraDetails)
        {
            IFormFile image = cameraDetails.UploadedImage;

            // If the user has uploaded a file.
            if (image != null)
            {
                // Verify file size, must be under 5 MB.
                if (image.Length > 5000000)
                {
                    return(false);
                }

                // Verify that the file is a valid image file (respects Minimum Size, File Extension and MIME Types).
                if (HttpPostedFileBaseExtensions.IsImage(image))
                {
                    // Proceed to process the request with the valid image.

                    // Obtain the file extension.
                    string fileExtension = Path.GetExtension(image.FileName).ToLower();

                    // Obtain the Database ID of the camera.
                    int cameraId = GetExistingCameraId(cameraDetails.CameraKey);

                    // Save the file to disk.

                    // 1. Ensure the output folder exists.
                    DirectoryInfo outputDirectory = Directory.CreateDirectory(DatabaseCamera.PATH_FOR_USER_UPLOADED_IMAGES);

                    // 2. Create the full file path (output path + filename).
                    string fullFilePath = Path.Combine(outputDirectory.FullName, cameraId + fileExtension);
                    cameraDetails.SavedImagePath = fullFilePath;

                    // 3. Save IFormFile as an image file in the output path.
                    using (var fileStream = new FileStream(fullFilePath, FileMode.Create))
                    {
                        // NOTE: If this was for the Edit page, we would have to delete the previous picture first.
                        Task task = image.CopyToAsync(fileStream);
                        task.GetAwaiter().GetResult();
                    }
                    return(true);
                }
            }

            return(false);
        }
コード例 #9
0
        public ActionResult AddGalleryPanel(FormCollection collection, IEnumerable <HttpPostedFileBase> files)
        {
            if (files != null && collection != null)
            {
                this.rc = new RetrieveContent();
                switch (collection["submit"])
                {
                case "save":
                    var menuTag    = collection["menuTag"];
                    var styleSheet = Convert.ToInt32(collection["panelDesign"], CultureInfo.CurrentCulture);

                    var header       = collection["hdr"];
                    var underMenuTag = collection["underMenuTag"];

                    this.pm = new PanelManagement();
                    this.pm.AddPanel(styleSheet, menuTag, underMenuTag);
                    this.rc.ClearPanelCache();
                    this.rc.GetContent();
                    var id = this.rc.Pan.Last().Panel_Id;
                    this.pm.AddGalleryPanel(id, header);

                    foreach (var item in files)
                    {
                        if (HttpPostedFileBaseExtensions.IsImage(item))
                        {
                            this.pm.AddGalleryImage(id, item);
                        }
                    }

                    this.rc.ClearPanelCache();
                    return(this.RedirectToAction("AdminHome", "Admin"));

                case "cancel":
                    return(this.RedirectToAction("AdminHome", "Admin"));

                default:
                    throw new ArgumentNullException("collection");
                }
            }

            return(this.RedirectToAction("AdminLogOn", "Admin"));
        }
コード例 #10
0
 public ActionResult UploadFile(HttpPostedFileBase file)
 {
     try
     {
         if (file.ContentLength > 0 && HttpPostedFileBaseExtensions.IsImage(file))
         {
             ResizerImage.UploadImage(file);
             ViewBag.Message = "File uploaded successfully!";
             return(View());
         }
         else
         {
             ViewBag.Message = "File upload failed!";
             return(View());
         }
     } catch (Exception e)
     {
         ViewBag.Message = "File upload failed!";
         return(View());
     }
 }
コード例 #11
0
        public ActionResult Create([Bind(Include = "tbUserId,Username,Fullname,Password,IsDisable")] tbUser tbUser, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                tbUser tbUserCheck = db.tbUsers.Where(p => p.Username == tbUser.Username).FirstOrDefault();
                if (tbUserCheck != null)
                {
                    ModelState.AddModelError("UserNameValid", "Tài khoản '" + tbUser.Username + "' đã tồn tại!!!");
                    return(View(tbUser));
                }

                tbUser.Password = DreamCMS.Encrypt.DHash.Encrypt(tbUser.Password);
                db.tbUsers.Add(tbUser);
                db.SaveChanges();

                // AVATAR
                if (file != null)
                {
                    if (HttpPostedFileBaseExtensions.IsImage(file))
                    {
                        string ext = Path.GetExtension(file.FileName).ToLower();
                        //string pic = Path.GetFileName(file.FileName);
                        string path = Path.Combine(Server.MapPath("~/Areas/Admin/upload/avatar"), tbUser.Username + ext);
                        // file is uploaded
                        file.SaveAs(path);

                        tbUser.AvatarUrl       = tbUser.Username + ext;
                        db.Entry(tbUser).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }

                return(RedirectToAction("Index"));
            }

            return(View("__Cms/Users/Create", tbUser));
        }
コード例 #12
0
        public ActionResult Edit([Bind(Include = "tbUserId,Username,Fullname,Password,IsDisable")] tbUser tbUser, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                tbUser.Password = DreamCMS.Encrypt.DHash.Encrypt(tbUser.Password);

                // AVATAR
                if (file != null)
                {
                    if (HttpPostedFileBaseExtensions.IsImage(file))
                    {
                        string ext = Path.GetExtension(file.FileName).ToLower();
                        //string pic = Path.GetFileName(file.FileName);
                        string path = Path.Combine(Server.MapPath("~/Areas/Admin/upload/avatar"), tbUser.Username + ext);
                        //delele old file
                        if (!string.IsNullOrEmpty(tbUser.AvatarUrl))
                        {
                            string fullPath = Path.Combine(Server.MapPath("~/Areas/Admin/upload/avatar"), tbUser.AvatarUrl);
                            if (System.IO.File.Exists(fullPath))
                            {
                                System.IO.File.Delete(fullPath);
                            }
                        }
                        // file is uploaded
                        file.SaveAs(path);

                        tbUser.AvatarUrl = tbUser.Username + ext;
                    }
                }

                db.Entry(tbUser).State = EntityState.Modified;
                db.SaveChanges();

                return(RedirectToAction("Index"));
            }
            return(View("__Cms/Users/Edit", tbUser));
        }
コード例 #13
0
        public ActionResult Upload(HttpPostedFileBase upload)
        {
            if (upload == null)
            {
                return(View("Index"));
            }
            string fileName = Path.GetFileName(upload.FileName);

            bool isPdf = false;

            if (upload.ContentType.ToLower().Equals("application/pdf"))
            {
                Logger.Info("Вероятнее всего, загружаемый файл - PDF документ.");
                isPdf = true;
            }

            if (!HttpPostedFileBaseExtensions.IsImage(upload) || string.IsNullOrEmpty(fileName))
            {
                return(View("Index"));
            }

            if (isPdf)
            {
                //если есть подтверждение, что работаем с пдф, то перенаправляем действие на соответствующий сервис
                _scaleService = _container.Resolve <IScaleService>("PdfScaleService");
            }
            else
            {
                _scaleService = _container.Resolve <IScaleService>("ImageScaleService");
            }

            Logger.Info("Выполняется сохранение файла {0} на сервере ...", upload.FileName);
            var saveFile = Path.Combine(Server.MapPath("~/Files/"), fileName);

            try
            {
                upload.SaveAs(saveFile);
                if (_scaleService != null)
                {
                    _scaleService.Init(saveFile, _clientWidth);
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, "При сохранении файла на сервере произошла ошибка.");
                return(View("Index"));
            }
            Logger.Info("Файл успешно сохранен.");
            Plan plan;

            if (_scaleService != null)
            {
                plan = _scaleService.GetStartImage();
            }
            else
            {
                plan = new Plan(fileName);
            }

            return(View("Exam", plan));
        }
コード例 #14
0
        public ActionResult Registrar([Bind(Include = "IdProducto,Nombre,IdTipoProducto,Forma,Imagen,Estado,Usuario")] Producto producto, HttpPostedFileBase ImageFile)
        {
            if (!LoginController.validaUsuario(Session))
            {
                return(RedirectToAction("Index", "Home"));
            }
            if (!LoginController.validaRol(Session))
            {
                return(RedirectToAction("Index", "Home"));
            }

            try
            {
                ViewBag.IdTipoProducto = new SelectList((from s in db.TipoProducto
                                                         where s.Estado == 1
                                                         select new
                {
                    s.IdTipoProducto,
                    s.Nombre
                }
                                                         ), "IdTipoProducto", "Nombre");
                ViewBag.Categorias = new SelectList((from s in db.CategoriaMat
                                                     where s.Estado == 1
                                                     select new
                {
                    s.IdCategoria,
                    s.Nombre
                }
                                                     ), "IdCategoria", "Nombre");

                ModelState.Remove("Usuario");
                producto.Usuario = Session["UsuarioActual"].ToString();

                if (ModelState.IsValid)
                {
                    if (ImageFile != null)
                    {
                        byte[] array;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            ImageFile.InputStream.CopyTo(ms);
                            array = ms.GetBuffer();
                        }
                        if (HttpPostedFileBaseExtensions.GetImageFormat(array) != HttpPostedFileBaseExtensions.ImageFormat.Desconocido)
                        {
                            producto.Imagen = array;
                        }
                        else
                        {
                            ModelState.AddModelError("Imagen", "La imagen debe de ser de un formato correcto(jpg,png,gif,jpeg,tiff,bmp).");
                            return(View());
                        }
                    }



                    if (TempData["ListaMateriales"] != null)
                    {
                        db.Producto.Add(producto);
                        db.SaveChanges();
                        foreach (ListaMaterialesEsperProducto item in (List <ListaMaterialesEsperProducto>)TempData["ListaMateriales"])
                        {
                            ListaMatProducto LM = new ListaMatProducto();
                            LM.IdProducto = producto.IdProducto;
                            LM.IdMaterial = item.IdMaterial;
                            db.ListaMatProducto.Add(LM);
                        }
                        db.SaveChanges();
                        TempData["ListaMateriales"] = null;
                    }
                    else
                    {
                        db.Producto.Add(producto);
                        db.SaveChanges();
                    }

                    return(RedirectToAction("Index"));
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                ModelState.AddModelError("", "Imposible guardar cambios. Intentelo de nuevo, y si el problema persiste contacte el administrador del sistema.");
            }
            return(View(producto));
        }
コード例 #15
0
        public ActionResult Editar([Bind(Include = "IdProducto,Nombre,IdTipoProducto,Forma,Imagen,Estado,Usuario")] Producto producto, HttpPostedFileBase ImageFile)
        {
            if (!LoginController.validaUsuario(Session))
            {
                return(RedirectToAction("Index", "Home"));
            }
            if (!LoginController.validaRol(Session))
            {
                return(RedirectToAction("Index", "Home"));
            }

            ViewBag.IdTipoProducto = new SelectList((from s in db.TipoProducto
                                                     where s.Estado == 1
                                                     select new
            {
                s.IdTipoProducto,
                s.Nombre
            }
                                                     ), "IdTipoProducto", "Nombre");
            ViewBag.Categorias = new SelectList((from s in db.CategoriaMat
                                                 where s.Estado == 1
                                                 select new
            {
                s.IdCategoria,
                s.Nombre
            }
                                                 ), "IdCategoria", "Nombre");
            ModelState.Remove("Usuario");

            if (ModelState.IsValid)
            {
                Producto productoToUpdate = db.Producto.Find(producto.IdProducto);
                if (TryUpdateModel(productoToUpdate, "",
                                   new string[] { "Nombre", "IdTipoProducto", "Forma", "Imagen", "Estado", "Usuario" }))
                {
                    productoToUpdate.Usuario = Session["UsuarioActual"].ToString();

                    if (ImageFile != null)
                    {
                        byte[] array;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            ImageFile.InputStream.CopyTo(ms);
                            array = ms.GetBuffer();
                        }
                        if (HttpPostedFileBaseExtensions.GetImageFormat(array) != HttpPostedFileBaseExtensions.ImageFormat.Desconocido)
                        {
                            productoToUpdate.Imagen = array;
                        }
                        else
                        {
                            ModelState.AddModelError("Imagen", "La imagen debe de ser de un formato correcto(jpg,png,gif,jpeg,tiff,bmp).");
                            return(View(productoToUpdate));
                        }
                    }
                    db.Entry(productoToUpdate).State = EntityState.Modified;
                    db.SaveChanges();
                }
                if (TempData["ListaMateriales"] != null)
                {
                    var materiales = (from s in db.ListaMatProducto
                                      where s.IdProducto == producto.IdProducto
                                      select s).ToList();

                    foreach (ListaMatProducto item in materiales)
                    {
                        db.ListaMatProducto.Attach(item);
                        db.ListaMatProducto.Remove(item);
                        db.SaveChanges();
                    }
                    foreach (var item in (List <ListaMaterialesEsperProducto>)TempData["ListaMateriales"])
                    {
                        if (item.Estado == 1)
                        {
                            ListaMatProducto LM = new ListaMatProducto();
                            LM.IdProducto = producto.IdProducto;
                            LM.IdMaterial = item.IdMaterial;
                            db.ListaMatProducto.Add(LM);
                        }
                    }
                    db.SaveChanges();
                    TempData["ListaMateriales"] = null;
                }

                return(RedirectToAction("Index"));
            }
            return(View(producto));
        }
コード例 #16
0
        public ActionResult GuardarProducto(Producto p)
        {
            Retorno retorno = new Retorno()
            {
                Success = true, Message = "Producto añadido correctamente"
            };
            var    user           = db.Users.Find(User.Identity.GetUserId());
            var    usuarioHayny   = db.Usuarios.Find(user.Usuario.IdUsuario);
            Imagen imagenProducto = null;

            using (var dbTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    if (Request.Files.Count > 0)
                    {
                        HttpPostedFileBase file          = Request.Files[0];
                        string             fileName      = Path.GetFileName(file.FileName);
                        string             fileExtension = Path.GetExtension(file.FileName);

                        if (HttpPostedFileBaseExtensions.IsImage(file))
                        {
                            try
                            {
                                Stream stream = file.InputStream;
                                System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
                                imagenProducto = new Imagen()
                                {
                                    Usuario     = usuarioHayny,
                                    FechaSubida = DateTime.Now,
                                    Height      = image.Height,
                                    Width       = image.Width,
                                    Formato     = fileExtension,
                                    Title       = fileName
                                };
                                db.Imagenes.Add(imagenProducto);
                                db.SaveChanges();
                                string path = Path.Combine(Server.MapPath("~/ImagenesSubidas/"), imagenProducto.IdImagen + fileExtension);
                                file.SaveAs(path);
                            }
                            catch (Exception e)
                            {
                                LogFileCreator LogError = new LogFileCreator();
                                LogError.ErrorLog(Server.MapPath("/Logs"), e.Message);
                                retorno = new Retorno()
                                {
                                    Success = false, Message = "Ocurrió un error al subir el archivo"
                                };
                                return(Json(retorno, JsonRequestBehavior.AllowGet));
                            }
                        }
                        else
                        {
                            retorno = new Retorno()
                            {
                                Success = false, Message = "El archivo subido no es una imagen válida"
                            };
                            return(Json(retorno, JsonRequestBehavior.AllowGet));
                        }
                    }
                    else
                    {
                        retorno.Success = false;
                        retorno.Message = "Debe incluir una imagen para agregar el producto";
                    }

                    p.Imagen        = imagenProducto;
                    p.FechaCreacion = DateTime.Now;
                    db.Productos.Add(p);
                    db.SaveChanges();
                    dbTransaction.Commit();
                }
                catch (DbEntityValidationException e)
                {
                    foreach (var eve in e.EntityValidationErrors)
                    {
                        LogFileCreator LogError = new LogFileCreator();

                        foreach (var ve in eve.ValidationErrors)
                        {
                            var mensaje = String.Format("  \"{0}\"  , {1} , {2}", eve.Entry.Entity.GetType().Name, ve.PropertyName, ve.ErrorMessage);
                            LogError.ErrorLog(Server.MapPath("/Logs"), mensaje);
                        }
                    }
                }
                catch (Exception e)
                {
                    LogFileCreator LogError = new LogFileCreator();
                    LogError.ErrorLog(Server.MapPath("/Logs"), e.Message);
                    dbTransaction.Rollback();
                }
            }

            return(Json(retorno, JsonRequestBehavior.AllowGet));
        }
コード例 #17
0
        public ActionResult GuardarArticulo(GuardarArticuloViewModel model)
        {
            Retorno retorno = new Retorno()
            {
                Success = true, Message = "Articulo añadido correctamente"
            };
            var             user           = db.Users.Find(User.Identity.GetUserId());
            var             usuarioHayny   = db.Usuarios.Find(user.Usuario.IdUsuario);
            List <Etiqueta> etiquetas      = JsonConvert.DeserializeObject <List <Etiqueta> >(model.Etiquetas);
            Imagen          imagenArticulo = null;

            using (var dbTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    if (Request.Files.Count > 0)
                    {
                        var file          = Request.Files[0];
                        var fileName      = Path.GetFileName(file.FileName);
                        var fileExtension = Path.GetExtension(file.FileName);
                        if (HttpPostedFileBaseExtensions.IsImage(file))
                        {
                            try
                            {
                                Stream stream = file.InputStream;
                                System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
                                imagenArticulo = new Imagen()
                                {
                                    Usuario     = usuarioHayny,
                                    FechaSubida = DateTime.Now,
                                    Height      = image.Height,
                                    Width       = image.Width,
                                    Formato     = fileExtension,
                                    Title       = fileName
                                };
                                db.Imagenes.Add(imagenArticulo);
                                db.SaveChanges();
                                string path = Path.Combine(Server.MapPath("~/ImagenesSubidas/"), imagenArticulo.IdImagen + fileExtension);
                                file.SaveAs(path);
                            }
                            catch (Exception e)
                            {
                                LogFileCreator LogError = new LogFileCreator();
                                LogError.ErrorLog(Server.MapPath("/Logs"), e.Message);
                                retorno = new Retorno()
                                {
                                    Success = false, Message = "Ocurrió un error al subir el archivo"
                                };
                                return(Json(retorno, JsonRequestBehavior.AllowGet));
                            }
                        }
                        else
                        {
                            retorno = new Retorno()
                            {
                                Success = false, Message = "El archivo subido no es una imagen válida"
                            };
                            return(Json(retorno, JsonRequestBehavior.AllowGet));
                        }
                    }


                    Articulo articulo = new Articulo()
                    {
                        Titulo      = model.Titulo,
                        Contenido   = model.Contenido,
                        FechaSubida = DateTime.Now,
                        Usuario     = usuarioHayny,
                        Imagen      = imagenArticulo
                    };
                    db.Articulos.Add(articulo);
                    foreach (Etiqueta etiq in etiquetas)
                    {
                        etiq.Nombre = etiq.Nombre.ToLowerInvariant();
                        db.Etiquetas.Add(etiq);
                        EtiquetaArticulo etar = new EtiquetaArticulo()
                        {
                            Articulo = articulo, Etiqueta = etiq
                        };
                        db.EtiquetaArticulo.Add(etar);
                    }
                    db.SaveChanges();
                    dbTransaction.Commit();
                }
                catch (DbEntityValidationException e)
                {
                    foreach (var eve in e.EntityValidationErrors)
                    {
                        LogFileCreator LogError = new LogFileCreator();

                        foreach (var ve in eve.ValidationErrors)
                        {
                            var mensaje = String.Format("  \"{0}\"  , {1} , {2}", eve.Entry.Entity.GetType().Name, ve.PropertyName, ve.ErrorMessage);
                            LogError.ErrorLog(Server.MapPath("/Logs"), mensaje);
                        }
                    }
                }
                catch (Exception e)
                {
                    LogFileCreator LogError = new LogFileCreator();
                    LogError.ErrorLog(Server.MapPath("/Logs"), e.Message);
                    dbTransaction.Rollback();
                }
            }


            return(Json(retorno, JsonRequestBehavior.AllowGet));
        }
コード例 #18
0
        public ActionResult SaveNewProduct(AddProductViewModel model)
        {
            List <ProductImages> images = new List <ProductImages>();
            string folderDate           = DateTime.Now.ToString("yyyyMMddHHmmss");

            Directory.CreateDirectory(Server.MapPath("~/DynamicContent/ProductImages/Product" + folderDate));
            var path       = "~/DynamicContent/ProductImages/Product" + folderDate;
            var pathToSave = "DynamicContent/ProductImages/Product" + folderDate;
            var imgPath    = "";

            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];

                if (file != null && file.ContentLength > 0 && HttpPostedFileBaseExtensions.IsImage(file))
                {
                    var           fileName   = Path.GetFileName(file.FileName);
                    ProductImages fileDetail = new ProductImages()
                    {
                        FileName      = fileName,
                        Extension     = Path.GetExtension(fileName),
                        FileNameNoExt = Path.GetFileNameWithoutExtension(fileName),
                        FilePath      = pathToSave
                    };
                    images.Add(fileDetail);

                    imgPath = Path.Combine(Server.MapPath(path), fileDetail.FileName);
                    file.SaveAs(imgPath);
                }
            }

            var PdfPathToSave = "";

            if (model.document != null && model.document.ContentLength > 0)
            {
                Directory.CreateDirectory(Server.MapPath("~/DynamicContent/ProductPDFs/Product" + folderDate));
                var PdfPath = Path.Combine(Server.MapPath("~/DynamicContent/ProductPDFs/Product" + folderDate), model.document.FileName);
                PdfPathToSave = "DynamicContent/ProductPDFs/Product" + folderDate;
                model.document.SaveAs(PdfPath);
            }

            var dbProduct = new Product
            {
                DatePublished     = DateTime.Now,
                Images            = images,
                isActive          = model.isActive,
                Name              = model.Name,
                Subtitle          = model.Subtitle,
                Text              = model.Text,
                Price             = model.Price,
                MetaDescription   = model.MetaDescription,
                MetaKeywords      = model.MetaKeywords,
                DocumentPath      = PdfPathToSave,
                DocumentName      = model.document.FileName,
                NumberOfDownloads = 0
            };

            _unitOfWork.Product.AddProduct(dbProduct);
            _unitOfWork.Complete();

            return(RedirectToAction("Index"));
        }