Пример #1
0
        public ActionResult Create([Bind(Include = "IdProduit,Nom,Couleur,Description,Prix,IdSousCategorie,DateMiseEnVente,Promotion,CodePays,Stock")] Produits produits, HttpPostedFileBase[] file)
        {
            if (ModelState.IsValid)
            {
                db.Produits.Add(produits);
                db.SaveChanges();
                if (!(file.Count() == 0))
                {
                    for (int i = 0; i < file.Count(); i++)
                    {
                        var fileName = Path.GetFileName(file[i].FileName);
                        var path = Path.Combine(Server.MapPath("~/Uploads/"), fileName);
                        file[i].SaveAs(path);
                        var photo = new DataLayer.Models.Photos();
                        photo.IdProduit = produits.IdProduit;
                        photo.PhotoName = fileName.ToString();
                        db.Photos.Add(photo);
                        db.SaveChanges();
                    }
                }
                return RedirectToAction("Index");
            }

            ViewBag.CodePays = new SelectList(db.Pays, "CodeIso3", "Name", produits.CodePays);
            ViewBag.IdSousCategorie = new SelectList(db.SousCategories, "IdSousCategorie", "Nom", produits.IdSousCategorie);
            return View(produits);
        }
        public ActionResult Create(HttpPostedFileBase[] files, string[] descriptions)
        {
            //Create Post
            Post post = new Post();
            post.title = Request["post.title"];
            post.slug = Request["post.slug"];
            post.type = PostType.Image;
            post.isFeature = bool.Parse(Request["post.isFeature"]);
            post.imageUrl = Request["post.imageUrl"];
            post.user = db.Users.Find(User.Identity.GetUserId());
            post.content = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
            post.createdDate = DateTime.Now;
            post.category = db.categories.Find(int.Parse(Request["post.category"]));

            db.posts.Add(post);
            db.SaveChanges();

            string id = post.id.ToString();

            if (files.Count() > 0)
            {

                //Create ImageGallery
                ImageGallery imageGallery = new ImageGallery();
                imageGallery.Id = Guid.NewGuid();
                imageGallery.Name = Request["imageGallery.Name"];
                imageGallery.ImagePath = "~/ImageGallery/";
                imageGallery.post = post;
                imageGallery = db.imageGallery.Add(imageGallery);
                db.SaveChanges();

                //Create List of Image for ImageGallery has been created
                for (int i = 0; i < files.Count(); i++)
                {
                    HttpPostedFileBase file = files[i];
                    string guid = Guid.NewGuid().ToString();
                    string fileName = imageGallery.Id + "_" + i + "_" + file.FileName;
                    file.SaveAs(Server.MapPath("~/ImageGallery/" + fileName));
                    Images image = new Images();
                    image.Description = descriptions[i] ?? "";
                    image.order = i;
                    image.gallery = imageGallery;
                    image.Name = i.ToString();
                    image.Path = imageGallery.ImagePath + fileName;
                    db.images.Add(image);

                    imageGallery.ImageList.Add(image);

                    //string path = "https://"+Request.Url.Host+":"+Request.Url.Port+ VirtualPathUtility.ToAbsolute(image.Path);
                }

                db.SaveChanges();
            }

            return View("index");
        }
Пример #3
0
 public ActionResult Create(PlaceCreator model, HttpPostedFileBase[] files)
 {
     int res = 0;
     if (ModelState.IsValid)
     {
         if (files.Count() > 5)
         {
             return Create("Не можна додавати більше 5 фото");
         }
         using (var db = new RazomContext())
         {
             Places p = new Places()
             {
                 CityID = model.SelectedCity,
                 Name = model.Place.Name,
                 PlaceTypeID = model.SelectedPlaceType,
                 Address = model.Place.Address,
             };
             db.Places.Add(p);
             db.SaveChanges();
             res = p.PlaceID;
             foreach (var file in files)
             {
                 byte[] image = new byte[file.ContentLength];
                 using (BinaryReader r = new BinaryReader(file.InputStream))
                 {
                     image = r.ReadBytes(file.ContentLength);
                 }
                 db.Database.ExecuteSqlCommand("INSERT INTO PhotosPlace(PlaceID,FileFoto) Values({0},{1})", p.PlaceID, image);
             }
         }
         return RedirectToAction("Show", "Place", new { id = res });
     }
     return Create("Не введена назва або адреса");
 }
        public ActionResult CreateProcess(FormCollection frm, HttpPostedFileBase[] ImagePath)
        {
            int kt = 0;
            try
            {
                foreach (HttpPostedFileBase file in ImagePath)
                {
                    /*Geting the file name*/
                    string filename = System.IO.Path.GetFileName(file.FileName);
                    /*Saving the file in server folder*/
                    file.SaveAs(Server.MapPath(@"~/Content/ImageUpload/" + filename));
                    string filepathtosave = "Content/ImageUpload/" + filename;

                    Nullable<int> isTopicImg = null;

                    Nullable<int> proId = null;
                    if (frm["ProgramId"] != "")
                    {
                        proId = int.Parse(frm["ProgramId"]);
                        List<ImageGallery> lsImg = ImageGalleryBusiness.GetImageTopic((int)proId);
                        if (lsImg.Count == 0)//if program doesn't has any image then set topic image =1
                        {
                            isTopicImg = 1;
                        }
                    }

                    Models.ImageGallery ad = new Models.ImageGallery()
                    {
                        ImagePath = filepathtosave,
                        ProgramId = proId,
                        IsTopicImage = isTopicImg,
                        Description = frm["Description"]
                    };

                    int check = ImageGalleryBusiness.AddImageGallery(ad);
                    if (check > 0)
                    {
                        kt++;
                    }
                }

            }
            catch
            {
                kt = 0;
            }

            if (kt == ImagePath.Count())
            {
                return RedirectToAction("Index", "ImageGallery", new { add = "success" });
            }
            else
            {
                return RedirectToAction("Index", "ImageGallery", new { add = "error" });
            }
        }
Пример #5
0
        public ActionResult ImagesUpload(HttpPostedFileBase[] files, string sessionKey, int? defaultImageIndex)
        {
            ProductSessionObject sObject = (ProductSessionObject)Session[sessionKey];
            string thumbsPath = ProductImage.DefaultThumbDirectory,
                imagesPath = ProductImage.DefaultImageDirectory;
            //If images were uploaded and there were no default image selected,
            //then the first one is our default.
            if (files.Count() > 0 && !defaultImageIndex.HasValue)
            {
                defaultImageIndex = 0;
            }
            //Defines the image resizing and format settings for thumbnails
            Instructions thumbResizeSettings = new Instructions() { Width = 300, Height = 400, Mode = FitMode.Pad };

            foreach (var item in files)
            {
                string extension = Path.GetExtension(item.FileName).ToLower();
                if (extension == ".png" || extension == ".jpg" || extension == ".jpeg")
                {
                    ProductImage image = new ProductImage();
                    //First we resize/save the thmbnail.
                    //ImageResizer can generate the filename using variables like these <guid> and <ext> below.
                    //I guess their working is obvious, so I won't explain.
                    ImageResizer.ImageJob thumbImageJob = new ImageResizer.ImageJob(item,
                        string.Format("{0}<guid>.<ext>", thumbsPath),
                        thumbResizeSettings);
                    thumbImageJob.Build();

                    //Setting the filename for the full image and for its thumbnail
                    image.Filename = Path.GetFileName(thumbImageJob.FinalPath);
                    image.ThumbFilename = image.Filename;

                    //Finally, save the full image with the same name as the thumbnail
                    item.SaveAs(Server.MapPath(imagesPath + image.Filename));

                    //Adds the newly uploaded image object do the Session Object. NOT to database.
                    sObject.Images.Add(image);
                }
            }

            ViewBag.defaultImageIndex = defaultImageIndex;

            return PartialView(sObject.Images);
        }
        public ActionResult SlideCreateProcess(FormCollection frm, HttpPostedFileBase[] ImagePath)
        {
            int kt = 0;
            try
            {
                foreach (HttpPostedFileBase file in ImagePath)
                {
                    /*Geting the file name*/
                    string filename = System.IO.Path.GetFileName(file.FileName);
                    /*Saving the file in server folder*/
                    file.SaveAs(Server.MapPath(@"~/Content/ImageUpload/Slider/" + filename));
                    string filepathtosave = "Content/ImageUpload/Slider/" + filename;

                    Models.ImageGallery ad = new Models.ImageGallery()
                    {
                        ImagePath = filepathtosave,
                        IsSildeImage = 1,
                        Description = frm["Description"]
                    };

                    int check = ImageGalleryBusiness.AddSlideImage(ad);
                    if (check > 0)
                    {
                        kt++;
                    }
                }

            }
            catch
            {
                kt = 0;
            }

            if (kt == ImagePath.Count())
            {
                return RedirectToAction("ListSlide", "ImageGallery", new { add = "success" });
            }
            else
            {
                return RedirectToAction("ListSlide", "ImageGallery", new { add = "error" });
            }
        }
        public ActionResult Edit(HttpPostedFileBase[] files, string[] updateImages)
        {
            List<UpdateImageModel> updateImageModels = new List<UpdateImageModel>();
            List<int> oldOrders = new List<int>();
            if (updateImages != null)
            {
                foreach (var s in updateImages)
                {
                    UpdateImageModel updateImageModel = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<UpdateImageModel>(s);
                    updateImageModels.Add(updateImageModel);
                }
            }

            string imageGallery_id = Request["imageGallery.Id"];
            ImageGallery imageGallery = db.imageGallery.Where(i => i.Id.ToString() == imageGallery_id).FirstOrDefault();
            IEnumerable<UpdateImageModel> oldImages = updateImageModels.Where(i => i.isOld == true);
            int post_id = int.Parse(Request["post.id"]);
            Post post = db.posts.Where(p => p.id == post_id).FirstOrDefault();
            if (imageGallery != null)
            {

                //Update Old Image and Remove Old Image
                if (oldImages.Count() > 0)
                {
                    //update oldImages (description and order)
                    foreach (var item in oldImages)
                    {
                        Images image = imageGallery.ImageList.Where(j => j.order == item.oldOrder).FirstOrDefault();
                        if (image != null)
                        {
                            image.order = item.newOrder;
                            image.Description = item.description;
                            db.SaveChanges();
                        }

                    }
                }

                //remove image
                IEnumerable<int> removeOrders = imageGallery.ImageList.Select(i => i.order).Except(oldImages.Select(o => o.oldOrder)).ToArray();
                foreach (var i in removeOrders)
                {

                    Images image = imageGallery.ImageList.Where(j => j.order == i).FirstOrDefault();
                    if (image != null)
                    {
                        string path = Server.MapPath(image.Path);
                        if (System.IO.File.Exists(path))
                        {
                            System.IO.File.Delete(path);
                        }

                        imageGallery.ImageList.Remove(image);
                        db.images.Remove(image);
                    }

                }
                db.SaveChanges();

                //Update Post

                if (post != null)
                {
                    post.title = Request["post.title"];
                    post.slug = Request["post.slug"];
                    post.type = PostType.Image;
                    post.isFeature = bool.Parse(Request["post.isFeature"]);
                    post.imageUrl = Request["post.imageUrl"];
                    post.user = db.Users.Find(User.Identity.GetUserId());
                    post.content = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
                    post.createdDate = DateTime.Now;
                    post.category = db.categories.Find(int.Parse(Request["post.category"]));

                    db.SaveChanges();
                }

                if (files != null)
                {
                    IEnumerable<UpdateImageModel> newImages = updateImageModels.Where(i => i.isOld == false);
                    if (files.Count() > 0)
                    {
                        //update Image Gallery and Add Image to  ImageGallery
                        imageGallery.Name = Request["imageGallery.Name"];
                        //imageGallery.ImagePath = "~/ImageGallery/";

                        //Create List of Image for ImageGallery has been created
                        int i = 0;
                        foreach (var item in newImages)
                        {
                            HttpPostedFileBase file = files[i];
                            string guid = Guid.NewGuid().ToString();
                            string fileName = imageGallery.Id + "_" + item.newOrder + "_" + file.FileName;
                            file.SaveAs(Server.MapPath("~/ImageGallery/" + fileName));
                            Images image = new Images();
                            image.Description = item.description;
                            image.gallery = imageGallery;
                            image.order = item.newOrder;
                            image.Name = item.newOrder.ToString();
                            image.Path = imageGallery.ImagePath + fileName;
                            db.images.Add(image);

                            imageGallery.ImageList.Add(image);

                            db.SaveChanges();
                            i++;
                            //string path = "https://"+Request.Url.Host+":"+Request.Url.Port+ VirtualPathUtility.ToAbsolute(image.Path);
                        }
                    }
                }

                db.SaveChanges();
                //return RedirectToAction("Index");
            }

            return View(new ImageGalleryPostViewModel() { imageGallery = imageGallery, post = post });
        }
Пример #8
0
        public ActionResult ArticleEdit(ArticleForEdit articleForEdit,
                                        HttpPostedFileBase introimgChang,
                                        HttpPostedFileBase[] image,
                                        int category = 0)
        {
            if (articleForEdit.ArticleID != 0)
            {
                Article article = repository.Articles_allImages
                                            .Where(x => x.ArticleID == articleForEdit.ArticleID)
                                            .FirstOrDefault();
                articleForEdit.IntroImg = article.IntroImg;
                articleForEdit.Images = article.Images;
            }
            else
            {
                articleForEdit.IntroImg = new Image();
                articleForEdit.Images = new List<Image>();
            }
            articleForEdit.Category_CategoryID = category;
            bool isImageNull = false;
            int OldImagesCount = articleForEdit.Images.Count;
            bool TextIsValid = true;
            if (image != null)
            {
                for (int i = 0; i < image.Count(); i++)
                {
                    if (image[i] == null && OldImagesCount < i)
                        isImageNull = true;
                }

                try { string.Format(articleForEdit.Text, image); }
                catch (Exception) { TextIsValid = false; }
            }
            bool isValid = ModelState.IsValid;
            if (isValid)
                if (TextIsValid)
                    if (!isImageNull)
                        if (articleForEdit.IntroImg != null || introimgChang != null)
                        {

                            if (introimgChang != null)
                            {
                                int introimgLength = introimgChang.ContentLength;
                                Image imageTmp = new Image()
                                {
                                    ImageType = introimgChang.ContentType,
                                    ImageData = new byte[introimgLength],
                                };
                                introimgChang.InputStream.Read(imageTmp.ImageData, 0, introimgLength);

                                articleForEdit.IntroImg = imageTmp;
                            }
                            if (articleForEdit.Images == null)
                                articleForEdit.Images = new List<Image>();

                            if (image!=null && OldImagesCount <= image.Count())
                            {
                                for (int i = 0; i < image.Count(); i++)
                                    if (image[i] != null)
                                    {
                                        Image imageTmp = new Image()
                                        {
                                            ImageType = image[i].ContentType,
                                            ImageData = new byte[image[i].ContentLength],
                                        };
                                        image[i].InputStream.Read(imageTmp.ImageData, 0, image[i].ContentLength);

                                        if (OldImagesCount <= i)
                                            articleForEdit.Images.Add(imageTmp);
                                        else
                                            articleForEdit.Images[i] = imageTmp;
                                    }
                            }
                            else
                            {
                                //articleForEdit.Images.RemoveRange(articleForEdit.Images.Count - 1,
                                //    articleForEdit.Images.Count - image.Count());
                                //for (int i = 0; i < articleForEdit.Images.Count; i++)
                                //    if (image[i] != null)
                                //    {
                                //        Image imageTmp = new Image()
                                //        {
                                //            ImageType = image[i].ContentType,
                                //            ImageData = new byte[image[i].ContentLength],
                                //        };
                                //        image[i].InputStream.Read(imageTmp.ImageData, 0, image[i].ContentLength);

                                //        articleForEdit.Images[i] = imageTmp;
                                //    }
                            }
                            repository.SaveArticle(articleForEdit, "123123");// User.Identity.Name);
                            int i;
                            i = 8;
                            return RedirectToRoute(new
                            {
                                controller = "Article",
                                action = "TheArticle",
                                ArticleId = articleForEdit.ArticleID
                            });
                        }

            //**Создание выпадающего списка
            EFCategoryRepository categoryRepo = new EFCategoryRepository();
            SelectList DropDownList = new SelectList(categoryRepo.Categorys,
                                                    "CategoryID", "Name",
                                                    articleForEdit.Category_CategoryID.ToString());
            ViewData["Category"] = DropDownList;
            return View(articleForEdit);
        }
        public List<string> uploadImages(HttpPostedFileBase[] images, string title)
        {
            var cloudinary = getCloudinary();

            var urls = new List<string>();

            int numPhotos = Globals.Shirts.Exists(x => x.Title == title && x.Photos.Length > 0) ?
                int.Parse(Globals.Shirts.FirstOrDefault(x => x.Title == title).Photos.Last().Split('_').Last().Replace(".png", "")) + 1 : 0;

            for (int i = numPhotos; i < images.Count() + numPhotos; i++)
            {
                var image = images[i - numPhotos];

                //var memoryStream = new MemoryStream();
                //image.InputStream.CopyTo(memoryStream);

                var safetitle = title.ToLower().Replace(' ', '_').Replace("'", "_").Replace('"', '_').Replace("/","_") + "_" + i;

                var uploadParams = new ImageUploadParams()
                {
                    File = new FileDescription(safetitle, image.InputStream),
                    PublicId = safetitle
                };

                var upload = cloudinary.Upload(uploadParams);

                urls.Add(upload.Uri.ToString());
            }
            return urls;
        }
Пример #10
0
        public ActionResult Files(string SiteID, HttpPostedFileBase[] files)
        {
            String thisPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
            //verificar si el id es de una agencia existente
            if (!string.IsNullOrEmpty(SiteID))
            {
                try
                {
                    int id = int.Parse(SiteID);
                    Sites siteUpload = db.Sites.Find(id);
                    if (siteUpload != null)
                    {
                        if (files.Count() > 0)
                        {
                            //buscar tipo Entidad
                            var t = from x in db.TipoEntidad where x.tipoEntidad == "Site" select x;
                            int tipo = 0;
                            if(t.Count() > 0)
                            {
                                tipo = t.First().idTipoEntidad;
                            }

                            //uploading file(s)
                            foreach (var f in files)
                            {
                                var filename = Path.GetFileName(f.FileName);
                                var path = Path.Combine(Server.MapPath("~/App_Data/files/site"), filename);
                                f.SaveAs(path);

                                //creando archivo en bd
                                Archivos archivo = new Archivos();
                                archivo.idEntidad = id;
                                archivo.TipoEntidad = tipo;
                                archivo.rutaArchivo = path;

                                //guardando cambios
                                db.Archivos.Add(archivo);
                            }

                            //saving database
                            db.SaveChanges();
                            TempData["message"] = "File upload successful.";
                            TempData["previous"] = thisPageUrl;
                            return View("~/Views/Shared/Success.cshtml");
                        }
                        else
                        {
                            TempData["message"] = "You must upload at least one file.";
                            TempData["previous"] = thisPageUrl;
                            return View("~/Views/Shared/Error.cshtml");
                        }
                    }
                    else
                    {
                        TempData["message"] = "The site you selected doesn't exist. Try again with another site.";
                        TempData["previous"] = thisPageUrl;
                        return View("~/Views/Shared/Error.cshtml");
                    }

                }
                catch (Exception e)
                {
                    TempData["message"] = "There was a problem uploading file.";
                    TempData["previous"] = thisPageUrl;
                    return View("~/Views/Shared/Error.cshtml");
                }

            }
            else
            {
                TempData["message"] = "You must select and existing site.";
                TempData["previous"] = thisPageUrl;
                return View("~/Views/Shared/Error.cshtml");
            }
        }
Пример #11
0
        private void ValidatePostedFiles(HttpPostedFileBase[] files)
        {
            if (files != null && files.Count() > 0)
            {
                int maxFileSize = SiteConfig.MaxFileSize.ToInt();
                List<string> invalidFileTypes = new List<string>();
                bool uploadLimitExceeded = false;

                foreach (var file in files.Where(item => item != null))
                {
                    if (file.ContentLength > 0)
                    {
                        if (!_fileServices.ValidFileType(file.FileName))
                            invalidFileTypes.Add(System.IO.Path.GetExtension(file.FileName));
                        else if (file.ContentLength > maxFileSize * 1024)
                            uploadLimitExceeded = true;
                    }
                }

                string error = "";

                if (uploadLimitExceeded)
                    error += "Max file size is " + maxFileSize + " kb.";
                if (invalidFileTypes.Count > 0)
                {
                    error += string.Format("File type not accepted ({0}).", string.Join(", ",invalidFileTypes));
                }

                if(!string.IsNullOrWhiteSpace(error))
                    ModelState.AddModelError("PostEditor.Files", error);

            }
        }
        private void GetPictureForTour(Tour tour, HttpPostedFileBase[] Pictures)
        {
            if (Pictures.Count() > 0 && Pictures[0] != null)
            {
                for (int i = 0; i < Pictures.Count(); i++)
                {
                    var picture = new Tour_PictureOfTour();
                    picture.FileName = Pictures[i].FileName;
                    picture.ContentType = Pictures[i].ContentType;

                    using (var reader = new BinaryReader(Pictures[i].InputStream))
                    {
                        //picture.Picture = reader.ReadBytes(Pictures[i].ContentLength);
                        picture.Picture = PictureController.GetCroppedImage(reader.ReadBytes(Pictures[i].ContentLength), PictureController.GetFormatImage(Pictures[i].ContentType));
                    }

                    tour.Tour_PictureOfTour.Add(picture);
                }
            }
        }