public ActionResult Create(LotViewModel lot)
 {
     if (ModelState.IsValid)
     {
         if (lot.EndDate < DateTime.Now)
         {
             ModelState.AddModelError(string.Empty, "End Date cannot come before Now");
             return(View(lot));
         }
         if (lot.MinimalBid < 0.01m)
         {
             ModelState.AddModelError(string.Empty, "Starting bid can't be less than 0.1");
             return(View(lot));
         }
         if ((lot.BuyOutBid != null) && (lot.BuyOutBid.Value <= lot.MinimalBid))
         {
             ModelState.AddModelError(string.Empty, "Buyout bid can't be less than or equal to starting bid!");
             return(View(lot));
         }
         lot.CreatedByUserId = UserViewModel.Id;
         WebImage wi = WebImage.GetImageFromRequest();
         if (wi != null)
         {
             wi.Resize(300, 300, true, true);
             lot.LotPicture = wi.GetBytes();
             wi.Resize(100, 100, true, true);
             lot.LotPicturePreview = wi.GetBytes();
         }
         _lotService.CreateLot(lot.ToLotEntity());
         return(RedirectToAction("Index"));
     }
     return(View(lot));
 }
        public ActionResult Create(ALMACEN3 a)
        {
            HttpPostedFileBase FileBase = Request.Files[0];

            if (FileBase.FileName != "")
            {
                WebImage image = new WebImage(FileBase.InputStream);
                a.FOTO_FRENTE = image.GetBytes();
                a.FOTO_LADO   = image.GetBytes();
            }
            if (!ModelState.IsValid)//ModelState es para validar que los datos sean los correctos.
            {
                LlenarViewDatas();
                return(View());
            }
            try
            {
                using (var db = new JEENContext())
                {
                    a.FECHA_MOD     = DateTime.Now;
                    a.USR_MOD       = 1;
                    a.GANANCIA      = CalcularPorcentajeGanancia(a.PRECIO_COSTO, a.PRECIO_COSTO2);
                    a.PRECIO_COSTO  = CalcularPrecioCompra(a.PRECIO_COSTO, a.GANANCIA, a.PRECIO_COSTO2);
                    a.PRECIO_COSTO2 = CalcularPrecioVenta(a.PRECIO_COSTO2, a.GANANCIA, a.PRECIO_COSTO);
                    db.ALMACEN3.Add(a);
                    db.SaveChanges();
                    return(RedirectToAction("ProductosLista"));
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "Error al registrar el producto - " + ex.Message);
                return(View());
            }
        }
Beispiel #3
0
 public ActionResult EditarAlm2(ALMACEN2 a)
 {
     try
     {
         if (!ModelState.IsValid)//ModelState es para validar que los datos sean los correctos.
         {
             LlenarViewDatas();
             return(View());
         }
         else
         {
             using (var db = new JEENContext())
             {
                 HttpPostedFileBase FileBase = Request.Files[0];
                 if (FileBase.FileName != "")
                 {
                     WebImage image = new WebImage(FileBase.InputStream);
                     a.FOTO_FRENTE = image.GetBytes();
                     a.FOTO_LADO   = image.GetBytes();
                 }
                 ALMACEN2 alm2 = db.ALMACEN2.Find(a.ID);
                 a.FECHA_ALTA = alm2.FECHA_ALTA; //No se modifica la fecha de registro
                 a.USR_MOD    = 1;               //Se pone usuario por default
                 /*a.FECHA_MOD = DateTime.Now;*/ //Se pone la fecha del dia para el usuario actualizacion
                 ////////////////////////////////////////////////////////////////////////////////////
                 alm2.ID_PRODUCTO   = a.ID_PRODUCTO;
                 alm2.DESCRIPCION   = a.DESCRIPCION;
                 alm2.ID_DESCUENTO  = a.ID_DESCUENTO;
                 alm2.C_MINIMA      = a.C_MINIMA;
                 alm2.C_MAXIMA      = a.C_MAXIMA;
                 alm2.TIPO          = a.TIPO;
                 alm2.VENTA_WEB     = a.VENTA_WEB;
                 alm2.MARCA         = a.MARCA;
                 alm2.MATERIAL      = a.MATERIAL;
                 alm2.COLOR         = a.COLOR;
                 alm2.FOTO_FRENTE   = a.FOTO_FRENTE; //No se modifica la imagen
                 alm2.FOTO_LADO     = a.FOTO_LADO;   //No se modifica la imagen
                 alm2.GANANCIA      = CalcularPorcentajeGanancia(a.PRECIO_COSTO, a.PRECIO_COSTO2);
                 alm2.PRECIO_COSTO  = CalcularPrecioCompra(a.PRECIO_COSTO, alm2.GANANCIA, a.PRECIO_COSTO2);
                 alm2.PRECIO_COSTO2 = CalcularPrecioVenta(a.PRECIO_COSTO2, alm2.GANANCIA, a.PRECIO_COSTO);
                 alm2.PRECIO_VENTA  = 0;
                 alm2.LOCALIZACION  = a.LOCALIZACION;
                 alm2.PRECIO_EN     = a.PRECIO_EN;
                 alm2.USR_ALTA      = a.USR_ALTA;
                 alm2.FECHA_ALTA    = alm2.FECHA_ALTA; //No se modifica la fecha de registro
                 alm2.USR_MOD       = 1;               //Se pone usuario por default
                 alm2.FECHA_MOD     = DateTime.Now;    //Se pone la fecha del dia para el usuario actualizacion
                 alm2.ESPECIE       = a.ESPECIE;
                 db.SaveChanges();
                 return(RedirectToAction("Materia2Lista"));
             }
         }
     }
     catch (Exception ex)
     {
         ModelState.AddModelError("", "Error al registrar el producto - " + ex.Message);
         throw;
     }
 }
        public void Should_Transform_HobbyModel_To_Hobby()
        {
            var image = TestResources.TestsResources.test;

            var expectedStream = new MemoryStream();

            image.Save(expectedStream, ImageFormat.Jpeg);

            var expectedWebImage = new WebImage(expectedStream);

            expectedWebImage.Resize(350, 200, false);

            var expected = new Hobby()
            {
                Id      = 1,
                Content = expectedWebImage.GetBytes(),
                Texts   = new List <Text>()
                {
                    new Text()
                    {
                        Language = _languages[0], Value = "hb1.fr"
                    },
                    new Text()
                    {
                        Language = _languages[1], Value = "hb1.en"
                    }
                }
            };

            var imgFake = new Mock <HttpPostedFileBase>();

            imgFake.Setup(x => x.InputStream).Returns(new MemoryStream(expectedWebImage.GetBytes()));

            var act = new HobbyModel()
            {
                Picture = imgFake.Object,
                Texts   = new List <TextModel>()
                {
                    new TextModel()
                    {
                        Language = _languages[0], Value = "hb1.fr"
                    },
                    new TextModel()
                    {
                        Language = _languages[1], Value = "hb1.en"
                    }
                }
            };

            var result = act.ToDto(_languages);

            Assert.AreEqual(expected.Content, result.Content);
            AssertExtension.CompareIEnumerable(expected.Texts, result.Texts,
                                               (x, y) => x.Language == y.Language && x.Value == y.Value);
        }
        public string UploadLogo(System.Web.HttpPostedFileBase Filedata, string clienttype, string clientid)
        {
            try
            {
                WebImage img = WebImage.GetImageFromRequest();

                if (img != null)
                {
                    if (img.ImageFormat == "Bitmap")
                    {
                        Image bmp       = null;
                        Image converted = null;

                        using (MemoryStream stream = new MemoryStream())
                            using (MemoryStream ms = new MemoryStream())
                            {
                                ms.Write(img.GetBytes(), 0, img.GetBytes().Length);
                                Image.FromStream(ms).Save(stream, ImageFormat.Png);
                                converted = Image.FromStream(stream);
                            }

                        PictureManager.Instance.UploadRawImage(converted, clienttype + clientid, "resources", "employerlogos");
                    }
                    else
                    {
                        PictureManager.Instance.UploadRawImage(img, clienttype + clientid, "resources", "employerlogos");
                    }
                }
                else
                {
                    Image img2 = null;

                    if (String.IsNullOrEmpty(Request["qqfile"]))
                    {
                        //This works with IE
                        HttpPostedFileBase httpPostedFileBase = Request.Files[0] as HttpPostedFileBase;
                        img2 = Image.FromStream(httpPostedFileBase.InputStream);
                    }
                    else
                    {
                        img2 = Image.FromStream(Request.InputStream);
                    }

                    PictureManager.Instance.UploadRawImage(img2, clienttype + clientid, "resources", "employerlogos");
                }



                return("{\"success\":true}");
            }
            catch
            {
                return("{\"error\":\"error\"}");
            }
        }
Beispiel #6
0
        /// <summary>
        /// Upload one image to album and Storage
        /// </summary>
        /// <param name="file">The file to upload</param>
        /// <param name="albumid">The Album Identity</param>
        public void UploadFileToAlbum(HttpPostedFileBase file, int?albumid)
        {
            if ((file != null) && (file.ContentLength > 0))
            {
                string imagepath;
                string thumbnailpath;
                Guid   unique = Guid.NewGuid();
                Album  album  = null;
                if (file.FileName.ToUpper().Contains("JPG") || file.FileName.ToUpper().Contains("JPEG") || file.FileName.ToUpper().Contains("GIF") || file.FileName.ToUpper().Contains("PNG"))
                {
                    if (albumid == null)
                    {
                        album = AlbumRepository.Get(a => a.Name == Resources.AppMessages.Default_Album_Name).FirstOrDefault();
                        if (album == null)
                        {
                            album = new Album {
                                Name = Resources.AppMessages.Default_Album_Name, Description = Resources.AppMessages.Default_Album_Description, IsPublic = true, DateCreated = DateTime.Now
                            };
                            AlbumRepository.Insert(album);
                            AlbumRepository.UnitOfWork.Commit();;
                            AlbumRepository.Get(a => a.Name == album.Name);
                        }
                        albumid = album.AlbumId;
                    }
                    else
                    {
                        album = AlbumRepository.GetByID(albumid);
                    }
                    CloudBlobContainer container = GetContainerForAlbum(albumid);
                    WebImage           image     = new WebImage(file.InputStream);
                    image.Resize(1024, 768, preserveAspectRatio: true, preventEnlarge: true)
                    .Crop(1, 1);
                    CloudBlob blob = container.GetBlobReference(unique + "_" + file.FileName);
                    blob.UploadByteArray(image.GetBytes());
                    imagepath = blob.Uri.AbsoluteUri;

                    image.Resize(Int32.Parse(BgResources.Media_ThumbnailWidth), Int32.Parse(BgResources.Media_ThumbnailHeight), preserveAspectRatio: true, preventEnlarge: true)
                    .Crop(1, 1);
                    CloudBlob thblob = container.GetBlobReference(unique + "_th" + file.FileName);
                    thblob.UploadByteArray(image.GetBytes());
                    thumbnailpath = thblob.Uri.AbsoluteUri;

                    ImageRepository.Insert(new Image {
                        Name = file.FileName, Path = imagepath, ThumbnailPath = thumbnailpath, Album = album, DateCreated = DateTime.Now, FileName = file.FileName
                    });
                    ImageRepository.UnitOfWork.Commit();
                }
                else
                {
                    CloudBlobContainer container = GetContainerForAlbum(null);
                    CloudBlob          blobfile  = container.GetBlobReference(unique + "_" + file.FileName);
                    blobfile.UploadFromStream(file.InputStream);
                }
            }
        }
        public ActionResult Update(LotViewModel lot)
        {
            if (UserViewModel == null)
            {
                return(new HttpStatusCodeResult(401));
            }
            if ((UserViewModel.Id != lot.CreatedByUserId) &&
                (!_customAuthentication.CheckUserInRoles(UserViewModel.ToUserEntity(), "Admin,Moderator")))
            {
                return(new HttpStatusCodeResult(403));
            }
            var oldLot = _lotService.GetLotEntity(lot.Id);

            ViewBag.HasImage    = oldLot.LotPicture != null;
            lot.CreatedByUserId = oldLot.CreatedByUserId;
            if (ModelState.IsValid)
            {
                if (lot.EndDate < DateTime.Now)
                {
                    ModelState.AddModelError(string.Empty, "End Date cannot come before Now");
                    return(View(lot));
                }
                if (lot.MinimalBid < 0.01m)
                {
                    ModelState.AddModelError(string.Empty, "Starting bid can't be less than 0.1");
                    return(View(lot));
                }
                if ((lot.BuyOutBid != null) && (lot.BuyOutBid.Value <= lot.MinimalBid))
                {
                    ModelState.AddModelError(string.Empty, "Buyout bid can't be less than or equal to starting bid!");
                    return(View(lot));
                }
                WebImage wi = WebImage.GetImageFromRequest();
                var      r  = wi;
                if (wi != null)
                {
                    wi.Resize(300, 300, true, true);
                    lot.LotPicture = wi.GetBytes();
                    wi.Resize(100, 100, true, true);
                    lot.LotPicturePreview = wi.GetBytes();
                }
                if ((wi == null) && (!lot.DeletePicture))
                {
                    lot.LotPicture        = oldLot.LotPicture;
                    lot.LotPicturePreview = oldLot.LotPicturePreview;
                }

                _lotService.UpdateLot(lot.ToLotEntity());
                return(RedirectToAction("Details", new { id = lot.Id }));
            }
            return(View(lot));
        }
Beispiel #8
0
        public void AddImageWatermarkDoesNotChangeImageIfWatermarkIsTooBig()
        {
            WebImage watermark = new WebImage(_JpgImageBytes);
            WebImage image     = new WebImage(_BmpImageBytes);

            byte[] originalBytes = image.GetBytes("jpg");

            // This will use original watermark image dimensions which is bigger than the target image.
            image.AddImageWatermark(watermark);
            byte[] watermarkedBytes = image.GetBytes("jpg");

            Assert.Equal(originalBytes, watermarkedBytes);
        }
 public JavaScriptResult Create(ProductViewModel ProductVm)
 {
     try
     {
         if (ProductVm.Picturep != null)
         {
             var extension = Path.GetExtension(ProductVm.Picturep.FileName)?.Trim().ToLower();
             if (extension == ".jpg" || extension == ".png" || extension == ".gif")
             {
                 var reader    = new BinaryReader(ProductVm.Picturep.InputStream);
                 var byteArray = reader.ReadBytes(ProductVm.Picturep.ContentLength);
                 var img       = new WebImage(byteArray).Resize(300, 300, false, true);
                 ProductVm.Picture = img.GetBytes();
             }
             else
             {
                 throw new Exception("Please upload .jpg, PNG, gif file only.");
             }
         }
         _productService.Add(Mapper.Map <Product>(ProductVm));
         return(JavaScript($"ShowResult('{"Data saved successfully."}','{"success"}','{"redirect"}','{"/APanel/MedicineShopProduct/?ProductCategoryId=" + ProductVm.ProductCategoryId + "&&ProductSubCategoryId=" + ProductVm.ProductSubCategoryId}')"));
     }
     catch (Exception ex)
     {
         return(JavaScript($"ShowResult('{ex.Message}','failure')"));
     }
 }
Beispiel #10
0
        public ActionResult Edit(ToevoegenViewmodel viewmodel, HttpPostedFileBase postedFile, bool Actie = false, bool Avontuur = false, bool Drama = false, bool Fantasie = false, bool Horror = false, bool Comedie = false, bool Misdaad = false, bool Oorlog = false, bool ScienceFiction = false, bool Sport = false, bool Thriller = false, bool Western = false, bool Romantiek = false)
        {
            viewmodel.Genres          = _genreRepository.GetAllGenres();
            viewmodel.Film.ListGenres = _filmRepository.CheckGenres(Actie, Avontuur, Drama, Fantasie, Horror, Comedie, Misdaad, Oorlog, ScienceFiction, Sport, Thriller, Western, Romantiek);
            if (postedFile == null)
            {
                ViewBag.image = "Upload astublieft een foto die bij de film hoort.";
                return(View(viewmodel));
            }
            if (viewmodel.Film.Naam == null || viewmodel.Film.Beschrijving == null || viewmodel.Film.Jaar == 0 || viewmodel.Film.Lengte == 0 || viewmodel.Film.Prijs == 0 || viewmodel.Film.ListGenres.Count == 0)
            {
                ViewBag.gegevens = "Vul astublieft alle gegevens van de film in.";
                return(View(viewmodel));
            }
            if (viewmodel.Film.Rating == 0)
            {
                ViewBag.rating = "Let op! Gebruik een punt en geen komma.";
                return(View(viewmodel));
            }
            WebImage img = new WebImage(postedFile.InputStream);

            img.Resize(124, 186, false);
            viewmodel.Film.Image = img.GetBytes();
            if (_filmRepository.GetAllFilms().Contains(viewmodel.Film))
            {
                return(View());
            }
            _filmRepository.EditFilm(viewmodel.Film);
            _genreRepository.DeleteFilmGenres(viewmodel.Film.Id);
            _genreRepository.InsertFilmGenres(viewmodel.Film);
            return(View("Toegevoegd"));
        }
        public ActionResult Edit([Bind(Include = "Id,nombre,procesador,graficos,ram,pantalla,almacenamiento,bateria,so,audio,puertos,conectividad,precio,existencias,img")] productos productos)
        {
            //byte[] imagenActual = null;
            productos _productos = new productos();

            HttpPostedFileBase FileBase = Request.Files[0];

            if (FileBase.ContentLength == 0)
            {
                _productos    = db.productos.Find(productos.Id);
                productos.img = _productos.img;
            }
            else
            {
                if (FileBase.FileName.EndsWith(".png") || FileBase.FileName.EndsWith(".PNG"))
                {
                    WebImage image = new WebImage(FileBase.InputStream);
                    productos.img = image.GetBytes();
                }
                else
                {
                    ModelState.AddModelError("Imagen", "Solo se admiten imagenes con formato .png");
                }
            }

            if (ModelState.IsValid)
            {
                db.Entry(_productos).State = EntityState.Detached;
                db.Entry(productos).State  = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(productos));
        }
Beispiel #12
0
        public ActionResult Create([Bind(Include = "Id,PlayerName,PlayerLastName,Nationality,BornDate,TeamID,Imagen,About")] Player player)
        {
            byte[]             imagenActual = null;
            HttpPostedFileBase FileBase     = Request.Files[0];

            if (FileBase == null)
            {
                imagenActual = db.Teams.SingleOrDefault(t => t.Id == player.Id).Imagen;
            }

            else
            {
                WebImage image = new WebImage(FileBase.InputStream);

                player.Imagen = image.GetBytes();
            }

            if (ModelState.IsValid)
            {
                db.Players.Add(player);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.TeamID = new SelectList(db.Teams, "Id", "TeamName", player.TeamID);
            return(View(player));
        }
Beispiel #13
0
        public ActionResult Create([Bind(Include = "ID,EmployeeName,I9,PictureID,I9Location,PictureIDLocation")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                bool first = false;
                foreach (var file in Request.Files)
                {
                    if (first == false)
                    {
                        if (employee.I9Location != null)
                        {
                            WebImage i9image = WebImage.GetImageFromRequest(file.ToString());
                            employee.I9 = i9image.GetBytes();
                        }
                        first = true;
                    }

                    else
                    {
                        if (employee.PictureIDLocation != null)
                        {
                            WebImage picimage = WebImage.GetImageFromRequest(file.ToString());
                            employee.PictureID = picimage.GetBytes();
                        }
                    }
                }
                db.Employees.Add(employee);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(employee));
        }
        public ActionResult Create([Bind(Include = "Id,nombre,procesador,graficos,ram,pantalla,almacenamiento,bateria,so,audio,puertos,conectividad,precio,existencias,img")] productos productos)
        {
            HttpPostedFileBase FileBase = Request.Files[0];

            if (FileBase.ContentLength == 0)
            {
                ModelState.AddModelError("Imagen", "Seleccione una imagen para el producto");
            }
            else
            {
                if (FileBase.FileName.EndsWith(".png") || FileBase.FileName.EndsWith(".PNG"))
                {
                    WebImage image = new WebImage(FileBase.InputStream);
                    productos.img = image.GetBytes();
                }
                else
                {
                    ModelState.AddModelError("Imagen", "Solo se admiten imagenes con formato .png");
                }
            }

            if (ModelState.IsValid)
            {
                db.productos.Add(productos);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(productos));
        }
Beispiel #15
0
        public ActionResult Edit([Bind(Include = "ID,Nombre,Descripcion,Precio,Tipo,Img")] Menu menu)
        {
            byte[] imagenActual = null;

            HttpPostedFileBase FileBase = Request.Files[0];

            if (FileBase == null)
            {
                imagenActual = db.Menus.SingleOrDefault(t => t.ID == menu.ID).Img;
            }
            else
            {
                WebImage image = new WebImage(FileBase.InputStream);

                menu.Img = image.GetBytes();
            }



            if (ModelState.IsValid)
            {
                db.Entry(menu).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(menu));
        }
        public ActionResult UpdateMovie(MovieViewModel model, HttpPostedFileBase upload)
        {
            if (ModelState.IsValid)
            {
                if (upload != null)
                {
                    var img = new WebImage(upload.InputStream);
                    if (img.Width > 700)
                    {
                        img.Resize(700, 300);
                    }

                    var movie = new MovieDto
                    {
                        MoviePoster   = img.GetBytes(),
                        MovieName     = model.MovieName,
                        UserMovieNote = model.UserMovieNote,
                        MovieID       = model.MovieID
                    };
                    movieService.Update(movie);
                }
                else
                {
                    var movie = new MovieDto
                    {
                        MovieName     = model.MovieName,
                        UserMovieNote = model.UserMovieNote,
                        MovieID       = model.MovieID
                    };
                    movieService.Update(movie);
                }
            }
            return(RedirectToAction("GetAllMovies", "Movie"));
        }
Beispiel #17
0
        public ActionResult Upload()
        {
            var db = new PhotoGalleryRepository();

            int id       = Request.Url.Segments[3].AsInt();
            var numFiles = Request.Files.Count;
            int imageId  = 0;

            for (int i = 0; i < numFiles; i++)
            {
                var file = Request.Files[i];
                if (file.ContentLength > 0)
                {
                    var fileUpload = new WebImage(file.InputStream);
                    var fileTitle  = Path.GetFileNameWithoutExtension(file.FileName).Trim();
                    if (fileTitle.IsEmpty())
                    {
                        fileTitle = "Untitled";
                    }
                    var fileExtension = Path.GetExtension(file.FileName).Trim();
                    var fileBytes     = fileUpload.GetBytes();

                    imageId = db.InsertImage(id, WebSecurity.CurrentUserId, fileTitle,
                                             fileExtension, fileUpload.ImageFormat, fileBytes.Length, fileBytes);
                }
            }

            return(RedirectToAction("View", "Photo", new { id = imageId }));
        }
Beispiel #18
0
        public ActionResult Create([Bind(Include = "ID,DIRECCION,TITULO,ID_SITIO")] FOTO_SITIO fOTO_SITIO)
        {
            HttpPostedFileBase FileBase = Request.Files[0];

            try
            {
                WebImage image = new WebImage(FileBase.InputStream);
                fOTO_SITIO.DIRECCION = image.GetBytes();
            }
            catch
            {
                ModelState.AddModelError("", "Es Obligatorio llenar el campo foto");
            }

            if (ModelState.IsValid)
            {
                db.FOTO_SITIO.Add(fOTO_SITIO);
                db.SaveChanges();
                ModelState.AddModelError("", "Se agrego la foto, puede subir mas si lo desea");
                return(RedirectToAction("Create/" + fOTO_SITIO.ID_SITIO.ToString()));
            }

            ViewBag.ID_SITIO = new SelectList(db.SITIO_TURISTICO, "ID", "NOMBRE", fOTO_SITIO.ID_SITIO);
            return(View(fOTO_SITIO));
        }
        public ActionResult Edit([Bind(Include = "Id,kindpruduct,productname,size,price,imagen")] Products products)
        {
            //byte[] imagenactual = null;

            Products _products = new Products();

            HttpPostedFileBase FileBase = Request.Files[0];

            if (FileBase.ContentLength == 0)
            {
                _products       = db.Products.Find(products.Id);
                products.imagen = _products.imagen;
            }
            else
            {
                if (FileBase.FileName.EndsWith(".jpg"))
                {
                    WebImage image1 = new WebImage(FileBase.InputStream);
                    products.imagen = image1.GetBytes();
                }
                else
                {
                    ModelState.AddModelError("imagen", "El sistema unicamente acepta imagenes con formato jpg");
                }
            }
            if (ModelState.IsValid)
            {
                db.Entry(_products).State = EntityState.Detached;
                db.Entry(products).State  = EntityState.Detached;
                db.Entry(products).State  = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(products));
        }
        public ActionResult Create([Bind(Include = "Id,kindpruduct,productname,size,price,imagen")] Products products)
        {
            HttpPostedFileBase FileBase = Request.Files[0];

            if (FileBase.ContentLength == 0)
            {
                ModelState.AddModelError("Imagen", "Es necesario seleccionar una imagen");
            }

            else
            {
                if (FileBase.FileName.EndsWith(".jpg"))
                {
                    WebImage image = new WebImage(FileBase.InputStream);
                    products.imagen = image.GetBytes();
                }
                else
                {
                    ModelState.AddModelError("imagen", "El sistema unicamente acepta imagenes con formato jpg");
                }
            }

            if (ModelState.IsValid)
            {
                db.Products.Add(products);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(products));
        }
Beispiel #21
0
        public static Images upload(WebImage webImage, string folder = "")
        {
            try
            {
                CloudinaryDotNet.Cloudinary cloudinary = new CloudinaryDotNet.Cloudinary(CloudAccount);
                byte[] fileData = webImage.GetBytes();

                using (MemoryStream memoryStream = new MemoryStream(fileData))
                {
                    ImageUploadParams uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription("advert images", memoryStream),
                        Transformation = new Transformation().Crop("limit").Width(750).Height(750),
                        Tags           = "advert_image",
                        Folder         = folder
                    };
                    Dictionary <string, object> dic = JsonHelper.JsonHelper.ConvertJsonToDictionary(cloudinary.Upload(uploadParams).JsonObj.ToString());
                    Images image = new Images()
                    {
                        url = getParam(dic, "public_id") + "." + getParam(dic, "format")
                    };
                    return(image);
                };
            }
            catch (System.Exception ex)
            {
                return(null);
            }
        }
Beispiel #22
0
        public ActionResult Details(int id)
        {
            var model = new RepairDetailsViewModel();

            model.Repair = db.GetRepair(id);
            if (model.Repair == null)
            {
                return(View("NotFound"));
            }

            if (model.Repair.Image != null)
            {
                WebImage image = new WebImage(model.Repair.Image);
                image.Resize(250, image.Height, true, true);
                model.Repair.Image = image.GetBytes();
            }

            model.RepairParts = db.GetRepairParts(id);
            if (model.RepairParts.Count() > 1)
            {
                model.PartsTotalPrice = db.GetRepairPartsPriceSum(id);
            }

            return(View(model));
        }
Beispiel #23
0
        public ActionResult Edit([Bind(Include = "id,Name,Description,Gender,Price,Image,MarcaId")] Perfume perfume)
        {
            byte[] imagenActual = null;

            HttpPostedFileBase FileBase = Request.Files[0];

            if (FileBase == null)
            {
                imagenActual = db.Perfumes.SingleOrDefault(t => t.id == perfume.id).Image;
            }
            else
            {
                WebImage image = new WebImage(FileBase.InputStream);

                perfume.Image = image.GetBytes();
            }

            if (ModelState.IsValid)
            {
                db.Entry(perfume).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ViewBag.MarcaId = new SelectList(db.Marcas, "id", "Name", perfume.MarcaId);
            return(View(perfume));
        }
Beispiel #24
0
        public List <Error> UploadOneFile(string Source, string SourceId)
        {
            List <Error> errors    = new List <Error>();
            var          imageData = _hrUnitOfWork.MissionRepository.GetBytes(int.Parse(SourceId));

            if (imageData != null)
            {
                return(errors);
            }
            var      file     = HttpContext.Request.Files[0];
            int      sid      = Convert.ToInt32(SourceId);
            var      stream   = ImageProcesses.ReadFully(file.InputStream);
            WebImage fullsize = null;
            WebImage thumbs   = null;

            fullsize = new WebImage(stream).Resize(1240, 1754);
            thumbs   = new WebImage(stream).Resize(124, 175);

            CompanyDocsViews doc = new CompanyDocsViews()
            {
                CompanyId   = CompanyId,
                name        = file.FileName,
                CreatedUser = UserName,
                Source      = Source,
                SourceId    = sid,
                file_stream = fullsize != null?fullsize.GetBytes() : stream,
                                  thumbs = thumbs != null?thumbs.GetBytes() : null
            };

            _hrUnitOfWork.CompanyRepository.Add(doc);
            errors = Save(Language);
            return(errors);
        }
Beispiel #25
0
        public ActionResult Edit([Bind(Include = "InformacionPersonalID,NombresEgresado,PrimerApellidoEgresado,SegundoApellidoEgresado,FechaNacimientoEgresado,NumeroDocumentoEgresado,FechaExpedicionDocumento,SexoEgresado,correoEgresado,DireccionResidenciaEgresado,TelefonoMovilEgresado,TelefonoFijoEgresado,ExtencionTelefonoEgresado,NumeroActaGrado,FotoEgresado,UserName,Imagen,MunicipioID,TipoDocumentoID,DepartamentoID")] InformacionPersonal informacionPersonal)
        {
            InformacionPersonal _imagenAcutal = new InformacionPersonal();
            HttpPostedFileBase  fileBase      = Request.Files[0];

            if (fileBase.ContentLength == 0)
            {
                _imagenAcutal = db.InformacionPersonals.Find(informacionPersonal.InformacionPersonalID);
            }
            else
            {
                if (fileBase.FileName.EndsWith(".jpg"))
                {
                    WebImage Imagen = new WebImage(fileBase.InputStream);

                    informacionPersonal.Imagen = Imagen.GetBytes();
                }
                else
                {
                    ModelState.AddModelError("Imagen", "El sistema unicamente acepta imagenes con formato JPG.");
                }
            }

            if (ModelState.IsValid)
            {
                db.Entry(_imagenAcutal).State       = EntityState.Detached;
                db.Entry(informacionPersonal).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Ver"));
            }
            ViewBag.TipoDocumentoID = new SelectList(db.TipoDocumentoes, "TipoDocumentoID", "NombreTipoDocumento", informacionPersonal.TipoDocumentoID);
            ViewBag.DepartamentoID  = new SelectList(db.Departamentoes, "DepartamentoID", "NombreDepartamento");
            ViewBag.MunicipioID     = new SelectList(db.Municipios.Where(m => m.DepartamentoID == db.Departamentoes.FirstOrDefault().DepartamentoID), "MunicipioID", "NombreMunicipio");
            return(View(informacionPersonal));
        }
Beispiel #26
0
        private ActionResult GetFileInternal(string type, string url, int width = 0, int height = 0)
        {
            url = url.Replace("&#47;", "/");

            if (!this._fileService.CheckAccessFile(url))
            {
                this.Response.StatusCode = 401;
                return(new HttpUnauthorizedResult());
            }

            string path = null;

            if (width > 0 && height > 0)
            {
                path = this._imageConverter.GetThumbPath(url, width, height);
                var pathParts = path.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
                url  = pathParts.Last();
                path = string.Format("/{0}/", Web.Helpers.GetVirtualPath(string.Join("\\", pathParts.Take(pathParts.Length - 1))));
            }
            else
            {
                path = this.Request.Url.Segments.Contains(string.Format("{0}/", CmsConstants.SECURE)) ? string.Format("~/Content/{0}/{1}/", type, CmsConstants.SECURE) : string.Format("~/Content/{0}/", type);
            }

            // Todo: logic te determine which images should be watermarked. Use an event?
            if (false)
            {
                var    webImage      = new WebImage(path);
                string waterMarkPath = string.Format("{0}{1}", Server.MapPath("~"), StrixCms.Config.Files.WaterMarkPath.Replace('/', '\\'));
                webImage.AddImageWatermark(waterMarkPath);
                return(this.File(webImage.GetBytes(), MimeMapping.GetMimeMapping(url)));
            }

            return(this.File(this.Server.MapPath(path) + url, MimeMapping.GetMimeMapping(url)));
        }
Beispiel #27
0
        public ActionResult GetImage(ImageAction imageaction)
        {
            WebImage image = new WebImage(Server.MapPath("~/images/twmvclogo.png"));


            switch (imageaction)
            {
            case ImageAction.Resize:
                image = image.Resize(100, 100);
                break;

            case ImageAction.Flip:
                image = image.FlipVertical();
                break;

            case ImageAction.Watermark:
                image = image.AddTextWatermark("TW MVC");
                break;

            case ImageAction.Crop:
                image = image.Crop(50, 50, 50, 50);
                break;

            default:
                throw new ArgumentException("尚未實作");
            }

            return(File(image.GetBytes(), "image/png"));
        }
        public ActionResult Create([Bind(Include = "DiseñoID,TipoID,Descripcion,PrecioUnitario,Imagen")] Diseño diseño)
        {
            HttpPostedFileBase FileBase = Request.Files[0];

            if (FileBase.ContentLength == 0)
            {
                ModelState.AddModelError("Imagen", "Es necesario seleccionar una imagen.");
            }
            else
            {
                if (FileBase.FileName.EndsWith(".png"))
                {
                    WebImage img = new WebImage(FileBase.InputStream);

                    diseño.Imagen = img.GetBytes();
                }
                else
                {
                    ModelState.AddModelError("Imagen", "Sólo se permiten imágenes *.png");
                }
            }


            if (ModelState.IsValid)
            {
                db.Diseño.Add(diseño);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.TipoID = new SelectList(db.Tipos, "TipoID", "NombreTipo", diseño.TipoID);
            return(View(diseño));
        }
        public ActionResult GongYePianQuImageThumbs(string id, int width, int height)
        {
            string   fileName = _gongYePianQuService.GetGongYePianQuZhaoPianById(ConvertToInt(id)).FilePath;
            WebImage img      = new WebImage(fileName).Resize(width, height);

            return(File(img.GetBytes("image/jpeg"), "image/jpeg"));
        }
        public ActionResult Edit([Bind(Include = "ID,Name,Price,Category,Image,ImageMimeType")] Product product)
        {
            //byte[] imagenActual = null;
            Product _product = new Product();

            HttpPostedFileBase filebase = Request.Files[0];

            if (filebase.ContentLength == 0)
            {
                _product      = db.Products.Find(product.ID);
                product.Image = _product.Image;
            }
            else
            {
                if (filebase.FileName.EndsWith(".jpg"))
                {
                    WebImage imagen = new WebImage(filebase.InputStream);
                    product.Image = imagen.GetBytes();
                }
                else
                {
                    ModelState.AddModelError("Image", "Invalid value");
                }
            }

            if (ModelState.IsValid)
            {
                db.Entry(_product).State = EntityState.Detached;
                db.Entry(product).State  = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ViewBag.Category = new SelectList(db.Categories, "ID", "Name", product.Category);
            return(View(product));
        }
        public void SimpleGetBytesClonesArray()
        {
            WebImage image = new WebImage(_PngImageBytes);

            byte[] returnedContent = image.GetBytes();

            Assert.False(ReferenceEquals(_PngImageBytes, returnedContent), "GetBytes should clone array.");
            Assert.Equal(_PngImageBytes, returnedContent);
        }
        public void WebImagePreservesOriginalFormatFromFile()
        {
            WebImage image = new WebImage(_PngImageBytes);

            byte[] returnedContent = image.GetBytes();

            // If format was changed; content would be different
            Assert.Equal(_PngImageBytes, returnedContent);
        }
        public void GetBytesWithNullReturnsClonesArray()
        {
            byte[] originalContent = _BmpImageBytes;
            WebImage image = new WebImage(originalContent);

            byte[] returnedContent = image.GetBytes();

            Assert.False(ReferenceEquals(originalContent, returnedContent), "GetBytes with string null should clone array.");
            Assert.Equal(originalContent, returnedContent);
        }
        public void WebImagePreservesOriginalFormatFromStream()
        {
            WebImage image = null;
            byte[] originalContent = _PngImageBytes;
            using (MemoryStream stream = new MemoryStream(originalContent))
            {
                image = new WebImage(stream);
            } // dispose stream; WebImage should have no dependency on it

            byte[] returnedContent = image.GetBytes();

            // If format was changed; content would be different
            Assert.Equal(originalContent, returnedContent);
        }
 public void GetBytesThrowsOnIncorrectFormat()
 {
     WebImage image = new WebImage(_JpgImageBytes);
     Assert.ThrowsArgument(
         () => image.GetBytes("bmpx"),
         "format",
         "\"bmpx\" is invalid image format. Valid values are image format names like: \"JPEG\", \"BMP\", \"GIF\", \"PNG\", etc.");
 }
        public void AddImageWatermarkDoesNotChangeImageIfWatermarkIsTooBig()
        {
            WebImage watermark = new WebImage(_JpgImageBytes);
            WebImage image = new WebImage(_BmpImageBytes);
            byte[] originalBytes = image.GetBytes("jpg");

            // This will use original watermark image dimensions which is bigger than the target image.
            image.AddImageWatermark(watermark);
            byte[] watermarkedBytes = image.GetBytes("jpg");

            Assert.Equal(originalBytes, watermarkedBytes);
        }
        public void GetBytesWithSameFormatReturnsSameFormat()
        {
            byte[] originalContent = _JpgImageBytes;
            WebImage image = new WebImage(originalContent);

            byte[] returnedContent = image.GetBytes("jpeg");

            Assert.False(ReferenceEquals(originalContent, returnedContent), "GetBytes with string null should clone array.");
            Assert.Equal(originalContent, returnedContent);
        }
        public void GetBytesWithDifferentFormatReturnsExpectedFormatWhenCreatedFromFile()
        {
            // Format is not set during construction.
            WebImage image = new WebImage(_PngImageBytes);

            // Request different format
            byte[] returnedContent = image.GetBytes("jpg");

            WebImage newImage = new WebImage(returnedContent);

            Assert.Equal("jpeg", newImage.ImageFormat);
        }
        public void GetBytesWithSameFormatReturnsSameFormatWhenCreatedFromFile()
        {
            byte[] originalContent = _BmpImageBytes;
            // Format is not set during construction.
            WebImage image = new WebImage(_BmpImageBytes);

            byte[] returnedContent = image.GetBytes("bmp");

            Assert.False(ReferenceEquals(originalContent, returnedContent), "GetBytes with string format should clone array.");
            Assert.Equal(originalContent, returnedContent);
        }
        public void GetBytesWithNoFormatReturnsInitialFormatEvenAfterTransformations()
        {
            byte[] originalContent = _BmpImageBytes;
            // Format is not set during construction.
            WebImage image = new WebImage(_BmpImageBytes);
            image.Crop(top: 10, bottom: 10);

            byte[] returnedContent = image.GetBytes();

            Assert.NotEqual(originalContent, returnedContent);
            using (MemoryStream stream = new MemoryStream(returnedContent))
            {
                using (Image tempImage = Image.FromStream(stream))
                {
                    Assert.Equal(ImageFormat.Bmp, tempImage.RawFormat);
                }
            }
        }
        public void WebImageCorrectlyReadsFromNoSeekStream()
        {
            WebImage image = null;

            byte[] originalContent = _PngImageBytes;
            using (MemoryStream stream = new MemoryStream(originalContent))
            {
                TestStream ts = new TestStream(stream);
                image = new WebImage(ts);
            } // dispose stream; WebImage should have no dependency on it

            byte[] returnedContent = image.GetBytes();

            // If chunks are not assembled correctly; content would be different and image would be corrupted.
            Assert.Equal(originalContent, returnedContent);
            Assert.Equal("png", image.ImageFormat);
        }
        public void GetBytesWithDifferentFormatReturnsExpectedFormat()
        {
            byte[] originalContent = _BmpImageBytes;
            WebImage image = new WebImage(originalContent);

            // Request different format
            byte[] returnedContent = image.GetBytes("jpg");

            Assert.False(ReferenceEquals(originalContent, returnedContent), "GetBytes with string format should clone array.");
            using (MemoryStream stream = new MemoryStream(returnedContent))
            {
                using (Image tempImage = Image.FromStream(stream))
                {
                    Assert.Equal(ImageFormat.Jpeg, tempImage.RawFormat);
                }
            }
        }