Esempio n. 1
0
        private PictureViewModel BuildPictureViewModel(Pictures picture)
        {
            PictureViewModel pictureVM = new PictureViewModel()
            {
                Id          = picture.Id,
                Description = picture.Description,
                PictureUrl  = picture.PictureUrl
            };

            foreach (Posts post in picture.Posts)
            {
                pictureVM.Posts.Add(new PostsViewModel()
                {
                    Id            = post.Id,
                    DatePost      = post.DatePost,
                    TextPost      = post.TextPost,
                    ProfileAuthor = new ProfileViewModel()
                    {
                        Id        = post.ProfileAuthor.Id,
                        FirstName = post.ProfileAuthor.FirstName,
                        LastName  = post.ProfileAuthor.LastName
                    }
                });
            }
            return(pictureVM);
        }
Esempio n. 2
0
        public IActionResult SearchAnimatedGifs(string searchText, int searchLimit, string language)
        {
            PictureViewModel model = new PictureViewModel();

            try
            {
                var result = _giphyAService.GetGifsByCriteria(searchText, searchLimit, language);
                if (result != null)
                {
                    foreach (var item in result.Data)
                    {
                        if (item != null)
                        {
                            model.Pictures.Add(new Picture()
                            {
                                SourceUrl = item.Images?.OriginalStill?.Url,
                                FileName  = item.Images?.Downsized?.Url,
                                Height    = Convert.ToInt32(item.Images?.Downsized?.Height),
                                Width     = Convert.ToInt32(item.Images?.Downsized?.Width)
                            });
                        }
                    }
                }
                return(View(model));
            }
            catch (Exception)
            {
                model.IsError = true;
                model.Message = "Unexpected error ocurred while retrieving Animated Gifs from Giphy Website. Try again later!";
                return(View(model));
            }
        }
Esempio n. 3
0
        public static void printTags(PictureViewModel pvm)
        {
            Dictionary <string, int> exifCount = CountExifTags(pvm);
            Dictionary <string, int> iptcCount = CountIptcTags(pvm);

            Document  doc        = new Document();
            Section   section1   = doc.AddSection();
            Paragraph paragraph1 = section1.AddParagraph();

            paragraph1.AddFormattedText("EXIF Properties:\n", TextFormat.Bold);
            paragraph1.AddText(PrintableTags(exifCount));
            paragraph1.AddFormattedText("IPTC Properties:\n", TextFormat.Bold);
            paragraph1.AddText(PrintableTags(iptcCount));
            PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(false);

            pdfRenderer.Document = doc;
            pdfRenderer.RenderDocument();

            OpenFileDialog dialog = new OpenFileDialog();

            dialog.CheckFileExists = false;
            var result = dialog.ShowDialog();

            if (result == false)
            {
                return;
            }
            pdfRenderer.PdfDocument.Save(dialog.FileName);
        }
Esempio n. 4
0
        private static Dictionary <string, int> CountIptcTags(PictureViewModel pvm)
        {
            Dictionary <string, int> tags = new Dictionary <string, int>();

            foreach (Picture p in pvm.Images)
            {
                foreach (Property prop in p.IptcProperties)
                {
                    if (tags.IsNullOrEmpty())
                    {
                        tags.Add(prop.Name, 1);
                    }
                    else
                    {
                        if (tags.ContainsKey(prop.Name))
                        {
                            tags[prop.Name] += 1;
                        }
                        else
                        {
                            tags.Add(prop.Name, 1);
                        }
                    }
                }
            }
            return(tags);
        }
Esempio n. 5
0
        public ActionResult EditPicture(PictureViewModel model, HttpPostedFileBase imageData)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Index", "Error"));
            }
            var picture = Mapper.Map <Picture>(model);

            picture.Images = (List <Image>)TempData["Images"];
            if (imageData != null)
            {
                var tempImage = new Image {
                    ImageData = new byte[imageData.ContentLength]
                };
                imageData.InputStream.Read(tempImage.ImageData, 0, imageData.ContentLength);
                tempImage.ImageName = imageData.FileName;
                using (var image = System.Drawing.Image.FromStream(imageData.InputStream, true, true))
                {
                    tempImage.ImageHeight = image.Height;
                    tempImage.ImageWidth  = image.Width;
                }

                picture.Images.First().ImageData   = tempImage.ImageData;
                picture.Images.First().ImageName   = tempImage.ImageName;
                picture.Images.First().ImageWidth  = tempImage.ImageWidth;
                picture.Images.First().ImageHeight = tempImage.ImageHeight;
            }
            _pictureUtil.UpdatePicture(picture);
            return(RedirectToAction("Index"));
        }
Esempio n. 6
0
        public ActionResult UpdatePicture(PictureViewModel obj)
        {
            int userId = Convert.ToInt32(Session["UserId"]);

            if (userId == 0)
            {
                return(RedirectToAction("Login", "Account"));
            }
            var file = obj.Picture;

            User user = db.Users.Find(userId);

            if (file != null)
            {
                var    extension        = Path.GetExtension(file.FileName);
                string id_and_extension = userId + extension;
                string imageUrl         = "~/Profile Images/" + id_and_extension;
                user.ImageUrl        = imageUrl;
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                var path = Server.MapPath("~/Profile Images/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if ((System.IO.File.Exists(path + id_and_extension)))
                {
                    System.IO.File.Delete(path + id_and_extension);
                }
                file.SaveAs((path + id_and_extension));
            }
            return(RedirectToAction("UserProfile"));
        }
Esempio n. 7
0
        public async Task <ActionResult> AddFileAsync(PictureViewModel file)
        {
            try
            {
                byte[] imageData = null;
                using (var memoryStream = new MemoryStream())
                {
                    await file.FormImage.CopyToAsync(memoryStream);

                    imageData = memoryStream.ToArray();
                }
                Console.WriteLine(imageData.ToString());
                PictureModelEngine picture = new PictureModelEngine();
                picture.Id = file.FormImage.FileName;
                //  picture.ImageType = file.FormImage.ContentType;
                //  picture.Image = imageData;

                var result = await PictureEngineService.AddAsync(picture);

                return(Content($"<h1>{result.Succeeded}</h1>"));
            }
            catch (Exception ex)
            {
                return(View(ex.ToString()));
            }
        }
Esempio n. 8
0
        public ActionResult Create(GalleryViewModel model)
        {
            var pic = new PictureViewModel();

            pic.GalleryID = model.id;
            return(View(pic));
        }
Esempio n. 9
0
        // ViewModel -> ADO Model
        public static Picture FixBack(PictureViewModel from)
        {
            Mapper.Initialize(cfg => { cfg.CreateMap <PictureViewModel, Picture>(); });
            var to = Mapper.Map <PictureViewModel, Picture>(from);

            return(to);
        }
Esempio n. 10
0
        public ActionResult Index(String pictureInfoFrom, string currentFilter, int?page)
        {
            var sort     = db.Picture_Type.ToList();
            var pictures = from p in db.Picture.OrderByDescending(p => p.Pic_Time)

                           select p;

            if (pictureInfoFrom != null)
            {
                page = 1;
            }
            else
            {
                pictureInfoFrom = currentFilter;
            }
            ViewBag.CurrentFilter = pictureInfoFrom;

            if (!String.IsNullOrEmpty(pictureInfoFrom))
            {
                pictures = pictures.Where(x => x.Picture_Type.Name == pictureInfoFrom);
            }

            int pageSize    = 9;
            int pageNumber  = (page ?? 1);
            var picturetype = new PictureViewModel()
            {
                Type1    = sort,
                Pictures = pictures.ToPagedList(pageNumber, pageSize),
            };

            return(PartialView("Index", picturetype));
        }
Esempio n. 11
0
        public async Task <Guid> AddOrUpdatePictureAsync(PictureViewModel picture)
        {
            var existingPicture = StoredPictures.Where(p => p.Header.PictureId == picture.Header.PictureId).FirstOrDefault();

            if (existingPicture == null)
            {
                StoredPictures.Add(picture);
            }
            else
            {
                // HACK: It would be much better to use an object mapper such as the one available in the SWAN project
                existingPicture.Header.DateTakenUtc       = picture.Header.DateTakenUtc;
                existingPicture.Header.Location.Latitude  = picture.Header.Location.Longitude;
                existingPicture.Header.Location.Longitude = picture.Header.Location.Longitude;
                existingPicture.Header.Name              = picture.Header.Name;
                existingPicture.Header.PictureId         = picture.Header.PictureId;
                existingPicture.Pin.BoundingBox.H        = picture.Pin.BoundingBox.H;
                existingPicture.Pin.BoundingBox.W        = picture.Pin.BoundingBox.W;
                existingPicture.Pin.BoundingBox.X        = picture.Pin.BoundingBox.X;
                existingPicture.Pin.BoundingBox.Y        = picture.Pin.BoundingBox.Y;
                existingPicture.Pin.IsBoundingBoxVisible = picture.Pin.IsBoundingBoxVisible;
                existingPicture.Pin.IsBugIdentified      = picture.Pin.IsBugIdentified;
                existingPicture.Pin.X        = picture.Pin.X;
                existingPicture.Pin.Y        = picture.Pin.Y;
                existingPicture.Pin.IsActive = picture.Pin.IsActive;
                existingPicture.ImageWidth   = picture.ImageWidth;
                existingPicture.ImageHeight  = picture.ImageHeight;

                picture = existingPicture;
            }

            await Task.Delay(10);

            return(picture.Header.PictureId);
        }
Esempio n. 12
0
        public ActionResult Create(PictureViewModel pictureViewModel)
        {
            string fileName  = Path.GetFileNameWithoutExtension(pictureViewModel.ImageFile.FileName);
            string extention = Path.GetExtension(pictureViewModel.ImageFile.FileName);

            fileName = fileName + DateTime.Now.ToString("yymmssfff") + extention;
            pictureViewModel.ImagePath = "~/Image/" + fileName;
            fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
            pictureViewModel.ImageFile.SaveAs(fileName);
            //using (DBContext pc_db = new DBContext())
            //{
            //    var pictureModel = _mapper.Map<PictureModel>(pictureViewModel);
            //    var picModel = _mapper.Map<Picture>(pictureModel);
            //    pc_db.Pictures.Add(picModel);
            //    pc_db.SaveChanges();
            //}
            if (ModelState.IsValid)
            {
                var pictureModel = _mapper.Map <PictureModel>(pictureViewModel);
                _pictureService.Add(pictureModel);
                //ViewBag.ActiveUserRole = GetActiveUserRole();
                return(RedirectToAction("Index"));
            }

            ModelState.Clear();
            return(View());
        }
Esempio n. 13
0
        public async Task <bool> UpdateAsync(PictureViewModel viewModel)
        {
            var entity = await _pictures.FirstOrDefaultAsync(p => p.Id == viewModel.Id);

            if (entity != null)
            {
                entity.Path     = viewModel.Path;
                entity.FolderId = viewModel.FolderId;

                entity.Name         = viewModel.Name;
                entity.Size         = viewModel.Size;
                entity.Type         = viewModel.Type;
                entity.Url          = viewModel.Url;
                entity.DeleteUrl    = viewModel.DeleteUrl;
                entity.ThumbnailUrl = viewModel.ThumbnailUrl;
                entity.DeleteType   = viewModel.DeleteType;
                entity.Extension    = viewModel.Extension;

                var result = await _unitOfWork.SaveChangesAsync();

                return(result != 0);
            }

            return(await Task.FromResult(false));
        }
Esempio n. 14
0
        public MainWindowViewModel()
        {
            _businessLayer = new BusinessLayer();

            pictureInfoViewModel = new PictureInfoViewModel();

            pictureViewModel = new PictureViewModel();

            pictureListViewModel = new PictureListViewModel();

            photographerListViewModel = new PhotographerListViewModel();


            pictureListViewModel.PropertyChanged += (s, e) => {
                switch (e.PropertyName)
                {
                case nameof(PictureListViewModel.SelectedImage):
                    pictureViewModel.Picture   = pictureListViewModel.SelectedImage;
                    pictureViewModel.TagString = pictureViewModel.MakeTagString();
                    pictureViewModel.SelectedPhotographerName = pictureViewModel.Picture.Photographer.FullName;
                    OnPropertyChanged(nameof(pictureViewModel));

                    pictureInfoViewModel.IPTCModel = pictureListViewModel.SelectedImage.IPTC;
                    pictureInfoViewModel.EXIFModel = pictureListViewModel.SelectedImage.EXIF;
                    OnPropertyChanged(nameof(pictureInfoViewModel));
                    break;
                }
            };
        }
Esempio n. 15
0
        public ActionResult Picture(PictureViewModel model)
        {
            var user = UserManager.FindById(User.Identity.GetUserId());

            if (user != null)
            {
                // if newly posted file
                if (model.ProfilePicture != null)
                {
                    var url = _fileStorage.Write(FileHelpers.ConvertEmailToFileName(user.Email, model.ProfilePicture.FileName),
                                                 FileHelpers.GetPostedFileBytes(model.ProfilePicture));
                    if (string.IsNullOrEmpty(url))
                    {
                        // display error
                    }
                    user.ProfilePicture = url;
                }
                UserManager.Update(user);
                // add randomId parameter so that the css will pull the updated
                // profile picture rather than the cached. This is because the url
                // always remains the same for the user
                model.ProfilePictureUrl = user.ProfilePicture + $"?randomId={ Guid.NewGuid() }";
            }
            return(View(model));
        }
Esempio n. 16
0
        public ActionResult Edit(RoomModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            string[] pictureIds = "".Split(',');
            if (model.Room.PictureIds != null)
            {
                pictureIds = model.Room.PictureIds.Split(',');
            }

            var room = RoomBAL.Update(model.Room.Id, model.Room);

            model.Room = (RoomViewModel)room.ReturnObject;

            for (int i = 0; i < pictureIds.Length; i++)
            {
                if (pictureIds[i].Trim().Length == 0)
                {
                    continue;
                }
                PictureViewModel picture = new PictureViewModel();
                picture.Id       = Convert.ToInt64(pictureIds[i]);
                picture.Entity   = Entity.Room;
                picture.EntityId = model.Room.Id;
                ReturnResult returnResult = PictureBAL.Update(Convert.ToInt64(pictureIds[i]), picture);
                picture = (PictureViewModel)returnResult.ReturnObject;
                System.IO.File.Move(Server.MapPath("~/") + "uploadTemp/" + picture.Id + picture.FileExtension, Server.MapPath("~/") + "Images/" + picture.Id + picture.FileExtension);
            }
            return(RedirectToAction("Index"));
        }
Esempio n. 17
0
        public async Task <PictureViewModel> CreateAsync(PictureViewModel viewModel)
        {
            _context.Add(viewModel.Model);
            await _context.SaveChangesAsync();

            return(viewModel);
        }
Esempio n. 18
0
        public ActionResult Save(IEnumerable <HttpPostedFileBase> files)
        {
            var pictureViewModel = new PictureViewModel();

            // The Name of the Upload component is "files"
            if (files != null)
            {
                foreach (var file in files)
                {
                    // Some browsers send file names with full path.
                    // We are only interested in the file name.
                    var fileName     = Path.GetFileName(file.FileName);
                    var physicalPath = Path.Combine(Server.MapPath("~/Images"), fileName);

                    // The files are not actually saved in this demo
                    file.SaveAs(physicalPath);

                    string pictureUrl = @"../../Images/" + fileName;

                    pictureViewModel.PictureId   = 1;
                    pictureViewModel.PictureName = fileName;
                    pictureViewModel.PictureUrl  = pictureUrl;
                    pictureViewModel.Status      = true;
                }
            }

            // Return an empty string to signify success
            //return Content("");
            //return Content(Boolean.TrueString);
            //return Json(Boolean.TrueString, JsonRequestBehavior.AllowGet);
            //return Json(Boolean.TrueString, "text/plain");
            //return Json(pictureViewModel, "text/plain"); //ok
            return(Json(pictureViewModel, JsonRequestBehavior.AllowGet)); //ok
        }
Esempio n. 19
0
        public ActionResult Create(PictureViewModel vm)
        {
            try
            {
                //Smestanje slike na drajv
                string fileName = Guid.NewGuid().ToString() + "_" + vm.Picture.FileName;
                string putanja  = Path.Combine(Server.MapPath("~/Content/images"), fileName);

                vm.Picture.SaveAs(putanja);

                PictureDto dto = new PictureDto
                {
                    Alt = "slikaaaa",
                    Src = "Content/images/" + fileName
                };


                OpPictureInsert op = new OpPictureInsert();
                op.Slika = dto;
                OperationResult rez = _manager.executeOperation(op);
                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Esempio n. 20
0
        public ActionResult EditPicture(PictureViewModel model, HttpPostedFileBase file)
        {
            string pictureFolder = Server.MapPath("../../Images");

            var path     = string.Empty;
            var fileName = string.Empty;

            if (file != null && file.ContentLength > 0)
            {
                fileName = model.User + model.GalleryID.ToString() + Path.GetFileName(file.FileName);
                path     = Path.Combine(pictureFolder, fileName);

                file.SaveAs(path);

                model.Path = "~/Images/" + fileName;

                RemoveOldFileIfExists(model);
            }
            model.DateEdited = DateTime.Now;
            if (ModelState.IsValid)
            {
                var picToUpdate = ModelMapper.ModelToEntity(model);
                repo.AddOrUpdate(picToUpdate);
                return(RedirectToAction("Details", "Picture", model));
            }

            ModelState.AddModelError("", "Couldn't update information");
            return(View(model));
        }
Esempio n. 21
0
        public ActionResult View(int id)
        {
            var picture    = _pictureService.GetById(id);
            var download   = (Download)Session["download"];
            var isSelected = false;

            if (download != null)
            {
                if (download.Pictures.Any(p => p.Id == id))
                {
                    isSelected = true;
                }
            }

            var pictureViewModel = new PictureViewModel
            {
                Id        = picture.Id,
                FileName  = picture.FileName,
                AlbumId   = picture.Album.Id,
                AlbumName = picture.Album.Name,
                Tags      = picture.Tags.Select(t => new TagViewModel
                {
                    Id   = t.Id,
                    Name = t.Name
                }).ToList(),
                IsSelected = isSelected
            };

            return(View(pictureViewModel));
        }
Esempio n. 22
0
        public ActionResult AddPhoto(long id)
        {
            PictureViewModel picture = new PictureViewModel();

            picture.FlowerId = id;
            return(View(picture));
        }
        //Set tags of a picture
        private void SetPictureTags(Picture picture, PictureViewModel model, GalleryDbContext db)
        {
            //Split tags
            var tagsStrings = model.Tags
                              .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                              .Select(t => t.ToLower())
                              .Distinct();

            //Clear current picture tags
            picture.Tags.Clear();

            //Set new picture tags
            foreach (var tagString in tagsStrings)
            {
                //Get tag from db by its name
                var tag = db.Tags.FirstOrDefault(t => t.Name.Equals(tagString));

                //If the tag is null create new tag
                if (tag == null)
                {
                    tag = new Tag()
                    {
                        Name = tagString
                    };
                    db.Tags.Add(tag);
                }

                //Add tag to picture tags
                picture.Tags.Add(tag);
            }
        }
Esempio n. 24
0
        public override void Execute(object parameter)
        {
            if (m_path != null)
            {
                if (m_window == null)
                {
                    var window = new LargeImageView();

                    if (!File.Exists(m_path))
                    {
                        return;
                    }

                    var bi = new BitmapImage();
                    bi.BeginInit();
                    bi.CacheOption = BitmapCacheOption.OnLoad;
                    bi.UriSource   = new Uri(m_path);
                    bi.EndInit();

                    var viewModel = new PictureViewModel(bi, m_name);
                    window.DataContext           = viewModel;
                    window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    window.Show();

                    m_window         = window;
                    m_window.Closed += m_window_Closed;
                }
                m_window.BringIntoView();
            }
        }
Esempio n. 25
0
        public async Task <IHttpActionResult> PostPicture([FromBody] PictureViewModel viewModel)
        {
            PictureModel writeModel = Mapper.Map <PictureViewModel, PictureModel>(viewModel);

            writeModel.SearchKey = PicturePrefix + viewModel.UserHash;
            return(this.Json(await this.mPictureService.WritePicture(writeModel)));
        }
Esempio n. 26
0
        private async Task Reload()
        {
            _viewModel.IsBusy = true;
            _dataChanged      = false;
            await CheckAccount();

            _viewModel.PhotoItems.Clear();

            PictureViewModel pictureViewModel = await ProgenyService.GetPictureViewModel(
                _viewModel.CurrentPictureId, _viewModel.UserAccessLevel, _userInfo.Timezone, 1);

            _viewModel.PhotoItems.Add(pictureViewModel);
            _viewModel.CurrentPictureViewModel = pictureViewModel;

            var networkInfo = Connectivity.NetworkAccess;

            if (networkInfo == NetworkAccess.Internet)
            {
                // Connection to internet is available
                _online = true;
                OfflineStackLayout.IsVisible = false;
            }
            else
            {
                _online = false;
                OfflineStackLayout.IsVisible = true;
            }

            _viewModel.IsBusy = false;
        }
Esempio n. 27
0
        public IActionResult Picture([FromRoute] int touristSpotId, [FromBody] PictureViewModel body)
        {
            try
            {
                if (body != null)
                {
                    if (this.UserId.HasValue)
                    {
                        body.OwnerId = this.UserId.Value;
                    }

                    body.TouristSpotId = touristSpotId;
                }

                var _added = this.pictureAppService.Add(body);
                return(this.Response(_added, HttpStatusCode.Created, Messages.SaveSuccess));
            }
            catch (SnowmanLabsChallengeException slcex)
            {
                return(this.Response(slcex));
            }
            catch (Exception ex)
            {
                return(this.Response(ex));
            }
        }
        private async void GetImages(AppPreferences ap)
        {
            if (!String.IsNullOrEmpty(imageNames[0]))
            {
                Bitmap bit = ap.SetImageBitmap(ap.CreateDirectoryForPictures() + "/" + imageNames[0]);
                if (bit != null)
                {
                    pictureHolder.SetImageBitmap(bit);
                }
                else if (bit == null && !String.IsNullOrEmpty(imageNames[0]))
                {
                    PictureViewModel pictureViewModel = new PictureViewModel();
                    Models.Picture   picture          = await pictureViewModel.ExecuteGetPictureCommand(imageNames[0]);

                    if (picture != null)
                    {
                        var _bit = ap.StringToBitMap(picture.File);
                        if (_bit != null)
                        {
                            ap.SaveImage(_bit, imageNames[0]);
                        }
                        pictureHolder.SetImageBitmap(_bit);
                    }
                }
            }
        }
Esempio n. 29
0
        public ActionResult NewComment(PictureViewModel picture)
        {
            var newComment = new CommentViewModel();

            newComment.PictureID = picture.id;

            return(View(newComment));
        }
        public ActionResult Pictures_Destroy([DataSourceRequest]DataSourceRequest request, PictureViewModel picture)
        {
            var pic = this.pictures.AllWithDeleted().Where(x => x.Id == picture.PictureId).FirstOrDefault();

            this.pictures.HardDelete(pic);
            this.pictures.SaveChanges();

            return Json(new[] { picture }.ToDataSourceResult(request, ModelState));
        }
 public PictureBrowser()
 {
     this.InitializeComponent();
     TiltEffect.SetIsTiltEnabled(this, true);
     this.Pictures = new ObservableCollection<PictureInfo>();
     this.initAppBar();
     this.pictureViewModel = ViewModelLocator.PicturesViewModel;
     base.DataContext = this;
 }
Esempio n. 32
0
        public ActionResult Edit(PictureViewModel model)
        {
            var Model = Crud.GetPicture(model.Id).ToModel();

            Model.Public = model.Public;
            Model.Name   = model.Name;
            Crud.CreateOrUpdate(Model.ToEntity());
            return(PartialView(Model));
        }
        public JsonResult DeletePicture(PictureViewModel model)
        {
            var picture = this.Data.Pictures.Find(model.Id);

            if (picture != null)
            {
                this.DeletePicturetData(picture);
                this.Data.SaveChanges();
                this.AddNotification("Contest Edited", NotificationType.SUCCESS);
                return Json(new { Message = "home" }, JsonRequestBehavior.AllowGet);
            }

            this.AddNotification("Something is worng. Plase try again", NotificationType.ERROR);
            return this.Json(new { Message = "error" }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Delete(PictureViewModel model)
        {
            Picture picture = this.Data.Pictures.GetById(model.PictureId);

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

            if (picture.Owner != this.UserProfile)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "You cannot delete a picture which is not yours.");
            }

            this.Data.Pictures.Delete(picture);
            this.Data.SaveChanges();

            return RedirectToAction("Index", "AdminPictures", new { id = model.ContestId });
        }
Esempio n. 35
0
 public bool SaveToDatabase(int pictureId, PictureViewModel model, List<RuleViolation> rules)
 {
     return new PictureRepository().Save(pictureId, model, rules);
 }
        public ActionResult Update(PictureViewModel model)
        {
            var picture = this.Data.Pictures.GetById(model.PictureId);

            if (picture == null)
            {
                return this.HttpNotFound();
            }

            if (picture.OwnerId != this.UserProfile.Id)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "You cannot edit a picture which is not yours.");
            }

            picture.Title = model.Title;
            picture.Url = model.Url;

            this.Data.SaveChanges();

            return this.RedirectToAction("Index", new { id = picture.ContestId });
        }
 public void Setup()
 {
     mTarget = new PictureViewModel("c:\\file.jpg");
 }
 public ActionResult Update([DataSourceRequest]DataSourceRequest request, PictureViewModel model)
 {
     var updatedModel = base.Update(model, model.Id);
     return this.GridOperation(model, request);
 }
 public ActionResult Destroy([DataSourceRequest]DataSourceRequest request, PictureViewModel model)
 {
     this.Delete<Picture>(model);
     return this.GridOperation(model, request);
 }
        public ActionResult UploadPicture(AddPictureBindingModel model)
        {
            var contest = this.Data.Contests.Find(model.ContestId);
            var userId = this.User.Identity.GetUserId();
            var user = this.Data.Users.Find(userId);

            var url = Request.UrlReferrer.AbsolutePath;

            if (contest.ParticipationStrategy == ParticipationStrategy.Closed)
            {
                if (!contest.SelectedUsersForParticipation.Contains(user))
                {
                    //this.TempData["partisipation-message"] = "You don't have permission to participate in this contest!";
                    return this.Json("Not", JsonRequestBehavior.AllowGet);
                }
            }

            if (contest.DeadlineStrategy == DeadlineStrategy.ByNumberOfParticipants)
            {
                var pictures = this.Data.Pictures
                    .All()
                    .Where(p => p.ContestId == contest.Id)
                    .Select(p => new
                    {
                        OwnerId = p.OwnerId
                    })
                    .ToList();

                var participantsIds = new HashSet<string>();

                foreach (var picture in pictures)
                {
                    participantsIds.Add(picture.OwnerId);
                }

                if (participantsIds.Count >= contest.MaxParticipants && !participantsIds.Contains(userId))
                {
                    //this.TempData["partisipation-message"] = "You don't have permission to participate in this contest!";
                    return this.Json("Max", JsonRequestBehavior.AllowGet);
                }
            }

            if (model.Picture != null && model.Picture.ContentLength > 0)
            {
                Guid id = Guid.NewGuid();
                string fileName = id.ToString();
                string fileExtension = model.Picture.FileName.Split('.').Last();

                MemoryStream target = new MemoryStream();
                model.Picture.InputStream.CopyTo(target);
                byte[] data = target.ToArray();

                UserCredential credential;
                using (var filestream = new FileStream(Server.MapPath("~/client_secret.json"), FileMode.Open, FileAccess.Read))
                {
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(filestream).Secrets,
                        new[] { DriveService.Scope.Drive },
                        "yunay07abv.bg",
                        CancellationToken.None,
                        new FileDataStore(Server.MapPath("~/Contests"))).Result;
                }

                // Create the service.
                var service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "My Project",
                });

                File body = new File();
                body.Title = fileName;
                body.Shared = true;
                body.Shareable = true;
                body.Parents = new List<ParentReference>{ new ParentReference() {Id = "0B3FfQDv4R4vyMkZ0Z2ZkMC0tWjg"} };
                body.Description = "Image";
                body.MimeType = "image/jpeg";
                body.FileExtension = fileExtension;
                MemoryStream stream = new MemoryStream(data);
                FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");
                request.Upload();

                File file = request.ResponseBody;
                var newPic = new Picture();
             
                newPic.ContestId = model.ContestId;
                newPic.PictureUrl = "https://drive.google.com/uc?id=" + file.Id;
                newPic.VoteCount = 0;
                newPic.OwnerId = this.User.Identity.GetUserId();
                newPic.Description = model.Description;
                newPic.Title = model.Title;

                this.Data.Pictures.Add(newPic);
                this.Data.SaveChanges();

                PictureViewModel lastPicture = new PictureViewModel();

                lastPicture.CommentsCount = 0;
                lastPicture.Id = newPic.Id;
                lastPicture.PictureUrl = "https://drive.google.com/uc?id=" + file.Id;
                lastPicture.Comments = new List<CommentViewModel>();
                lastPicture.Owner = this.UserProfile.UserName;
                lastPicture.Title = model.Title;
                lastPicture.Description = model.Description;

                return PartialView("~/Views/Pictures/_ShowPicture.cshtml", lastPicture);
            }

            return View("/");
        }