コード例 #1
0
        public async Task <string> UploadPrivatePicture()
        {
            HttpFileCollection filecol = HttpContext.Current.Request.Files;

            PictureValidation.GetInstance().CompleteValidations(filecol);

            string username = User.Identity.Name;


            string uploadPath = PictureHandling.GetInstance().HandlingUpdatePrivateDirectories(username);

            //var uploadPath = HttpContext.Current.Server.MapPath("~/Uploads");

            // Generate a provider with a custom class, passing the path( later pass the path to base class).
            // This support a multipart upload.
            var multipartFormDataStreamProvider = new UploadMultipartFormProvider(uploadPath);

            // Read the MIME multipart asynchronously
            await Request.Content.ReadAsMultipartAsync(multipartFormDataStreamProvider);

            string _localFileName = multipartFormDataStreamProvider
                                    .FileData.Select(multiPartData => multiPartData.LocalFileName).FirstOrDefault();


            //_localFileName = Cryptography.Decrypt(_localFileName);
            //Encrypt
            //_localFileName = Cryptography.Encrypt(_localFileName);
            // Create response
            return(JsonConvert.SerializeObject(new FileResult
            {
                FileName = Path.GetFileName(_localFileName),
                FileLength = new FileInfo(_localFileName).Length,
                LocalFilePath = Cryptography.Encrypt(_localFileName),
            }));
        }
コード例 #2
0
        public async Task <string> UploadPublicPicture()
        {
            HttpFileCollection filecol = HttpContext.Current.Request.Files;

            PictureValidation.GetInstance().CompleteValidations(filecol);

            string uploadPath = PictureHandling.GetInstance().HandlingUpdatePublicDirectories();

            var multipartFormDataStreamProvider = new UploadMultipartFormProvider(uploadPath);

            await Request.Content.ReadAsMultipartAsync(multipartFormDataStreamProvider);

            string _localFileName = multipartFormDataStreamProvider
                                    .FileData.Select(multiPartData => multiPartData.LocalFileName).FirstOrDefault();

            //string a = uploadPath.Substring(uploadPath.LastIndexOf("PublicPictures"));
            //a = a.Substring(a.IndexOf("\\"));

            return(JsonConvert.SerializeObject(new FileResult
            {
                FileName = Path.GetFileName(_localFileName),
                FileLength = new FileInfo(_localFileName).Length,
                LocalFilePath = Cryptography.Encrypt(_localFileName),
            }));
        }
コード例 #3
0
        /// <summary>
        ///  Approve once more a previous picture or invalidate the current profile picture
        /// </summary>
        /// <param name="pictureValidation">id : picture id, valid : bool </param>
        /// <returns>student netname</returns>
        public string RevalidatePicture(PictureValidation pictureValidation, string netName)
        {
            //find selected picture
            var selectedPicture = _database.PICTUREs
                                  .Where(p => p.ID_PK == pictureValidation.Id)
                                  .FirstOrDefault();

            var studentNetname = selectedPicture.STUDENT_NETNAME;

            //find valid profile picture if user has one
            var approved = Status.Approved.ToString();
            var currentProfilePicture = _database.PICTUREs
                                        .Where(p => p.STUDENT_NETNAME == studentNetname && p.STATUS == approved)
                                        .FirstOrDefault();


            if (pictureValidation.Valid)
            {
                if (currentProfilePicture != null)
                {
                    //archived picture
                    currentProfilePicture.STATUS = Status.Archived.ToString();
                }

                //new profile
                selectedPicture.STATUS        = Status.Approved.ToString();
                selectedPicture.UPDATED       = DateTime.UtcNow;
                selectedPicture.ADMINISTRATOR = netName;

                //find his account and set it to valid
                var student = _database.STUDENTS
                              .Where(s => s.NETNAME == studentNetname)
                              .FirstOrDefault();

                student.VALID = true;
            }
            else
            {
                //invalidate current profile picture
                currentProfilePicture.STATUS = Status.Denied.ToString();

                //find his account and set it to invalid
                var student = _database.STUDENTS
                              .Where(s => s.NETNAME == currentProfilePicture.STUDENT_NETNAME)
                              .FirstOrDefault();

                student.VALID = false;
            }
            //log admin
            if (currentProfilePicture != null)
            {
                currentProfilePicture.UPDATED       = DateTime.UtcNow;
                currentProfilePicture.ADMINISTRATOR = netName;
            }


            _database.SaveChanges();

            return(studentNetname);
        }
コード例 #4
0
        public HttpResponseMessage DownloadPublicPicture(FileResult file)
        {
            HttpResponseMessage result = null;
            //string filename = "hh.jpg";
            string filename = Cryptography.Decrypt(file.LocalFilePath);
            //filename = Path.GetFileName(filename);
            //filename = Path.GetFileName(filename);
            string path = PictureHandling.GetInstance().HandlingDownloadPublicDirectories(filename);

            PictureValidation.GetInstance().ValidateFileExist(path);
            //if (!File.Exists(path))
            //{
            //    throw new ApiException(7779, "La imagen no existe",
            //    System.Net.HttpStatusCode.Gone, "NoLink");
            //}
            //else
            //{
            // Serve the file to the client
            result         = Request.CreateResponse(HttpStatusCode.OK);
            result.Content = new StreamContent(PictureHandling.GetInstance().Resize(path, file.Qualitier));
            result.Content.Headers.ContentDisposition          = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = filename.Substring(filename.LastIndexOf("\\") + 1, filename.Length - filename.LastIndexOf("\\") - 1);
            //result.Content.Headers.ContentDisposition.FileName = filename;

            //}

            return(result);
        }
コード例 #5
0
        public IActionResult PostRevalidatePicture([FromBody] PictureValidation picture)
        {
            var authenticatedUser = GetAuthenticatedUserNetname();

            var netName = _studentsRepo.RevalidatePicture(picture, authenticatedUser);

            _logRepo.LoggerAsync(authenticatedUser, picture.Valid ? Log.Action.ReApprovedPicture : Log.Action.DeniedPicture,
                                 netName);


            return(Ok());
        }
コード例 #6
0
ファイル: ShopsController.cs プロジェクト: Mikk182/GPOrder
        public ActionResult AddPictures(ShopPicture shopPicture, HttpPostedFileBase upload)
        {
            try
            {
                var dbShop = db.Shops.Single(s => s.Id == shopPicture.ShopId);

                var userId = User.Identity.GetUserId();

                var shopPic = new ShopPicture
                {
                    CreationDate = DateTime.UtcNow,
                    CreateUser   = db.Users.Single(u => u.Id == userId),
                    Name         = System.IO.Path.GetFileName(upload.FileName),

                    LinkedFile = new File
                    {
                        FileType    = FileType.ShopPicture,
                        ContentType = upload.ContentType,
                    },

                    ShopId = dbShop.Id
                };

                // Parametre 'LeaveOpen = true' car la validation a peut etre besoin de relire la stream (sinon le Dispose() du BinaryReader efface le contenu)
                using (var reader = new System.IO.BinaryReader(upload.InputStream, Encoding.Default, true))
                {
                    shopPic.LinkedFile.Content = reader.ReadBytes(upload.ContentLength);
                }

                var spv = new PictureValidation <ShopPicture>();
                spv.Validate(shopPicture, ModelState);
                spv.Validate(upload, ModelState);

                if (!ModelState.IsValid)
                {
                    return(View(shopPicture));
                }

                db.ShopPictures.Add(shopPic);
                db.SaveChanges();
            }
            catch (DbUpdateException e)
            {
                ModelState.AddModelError("", e.Message);
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return(RedirectToAction("Details", new { Id = shopPicture.ShopId }));
        }
コード例 #7
0
        /// <summary>
        ///  Validate a pending picture
        ///  If approved, the student pending picture become their valid profile picture
        ///  if denied, the pending picture is send to the picture archive
        /// </summary>
        /// <param name="pictureValidation">id : student id,valid : bool</param>
        /// <returns>student netname</returns>
        public string ValidatePicture(PictureValidation pictureValidation, string netName)
        {
            var student = _database.STUDENTS
                          .Where(s => s.ID == pictureValidation.Id)
                          .FirstOrDefault();

            var studentNetname = student.NETNAME;


            var pending        = Status.Pending.ToString();
            var pendingPicture = _database.PICTUREs.
                                 Where(p => p.STATUS == pending && p.STUDENT_NETNAME == studentNetname)
                                 .FirstOrDefault();

            if (pictureValidation.Valid)
            {
                pendingPicture.STATUS = Status.Approved.ToString();

                //if user has already a profile picture, set to archive
                var aprouved       = Status.Approved.ToString();
                var profilePicture = _database.PICTUREs.
                                     Where(p => p.STATUS == aprouved && p.STUDENT_NETNAME == studentNetname)
                                     .FirstOrDefault();

                if (profilePicture != null)
                {
                    profilePicture.STATUS        = Status.Archived.ToString();
                    profilePicture.UPDATED       = DateTime.UtcNow;
                    profilePicture.ADMINISTRATOR = netName;
                }

                //account is now valid
                student.VALID = true;
            }
            else
            {
                pendingPicture.STATUS = Status.Denied.ToString();
            }


            student.PENDING = false;
            //log the admin doing the validation
            pendingPicture.ADMINISTRATOR = netName;
            pendingPicture.UPDATED       = DateTime.UtcNow;
            _database.SaveChanges();

            return(studentNetname);
        }
コード例 #8
0
        public HttpResponseMessage DownloadPrivatePicture(FileResult file)
        {
            HttpResponseMessage result = null;
            string username            = User.Identity.Name;
            string filename            = Cryptography.Decrypt(file.LocalFilePath);

            filename = Path.GetFileName(filename);
            string path = PictureHandling.GetInstance().HandlingDownloadPrivateDirectories(username, filename);

            PictureValidation.GetInstance().ValidateFileExist(path);
            result         = Request.CreateResponse(HttpStatusCode.OK);
            result.Content = new StreamContent(PictureHandling.GetInstance().Resize(path, file.Qualitier));
            result.Content.Headers.ContentDisposition          = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = filename;

            return(result);
        }
コード例 #9
0
        public async Task <string> UploadPublicPictureWithGUID()
        {
            HttpFileCollection filecol = HttpContext.Current.Request.Files;
            HttpPostedFile     a       = filecol.Get("FileUpload");

            PictureValidation.GetInstance().CompleteValidations(filecol);

            string uploadPath = PictureHandling.GetInstance().HandlingUpdatePublicDirectories();

            Guid Guided = Guid.NewGuid();

            uploadPath += "\\" + Guided.ToString("N") + ".jpg";

            //a.SaveAs(uploadPath);
            MemoryStream mss = new MemoryStream();

            a.InputStream.CopyTo(mss);



            using (mss)
            {
                ////with no compress;
                //Image img = System.Drawing.Image.FromStream(ms);

                //img.Save(withoutextension + "-th" + ".jpg");

                //with compress;
                Image             img = System.Drawing.Image.FromStream(mss);
                EncoderParameters eps = new EncoderParameters(1);
                eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);
                string         mimetype = GetMimeType(new System.IO.FileInfo(uploadPath).Extension);
                ImageCodecInfo ici      = GetEncoderInfo(mimetype);
                img.Save(uploadPath, ici, eps);
            }


            return(JsonConvert.SerializeObject(new FileResult
            {
                FileName = Path.GetFileName(uploadPath),
                FileLength = new FileInfo(uploadPath).Length,
                LocalFilePath = Cryptography.Encrypt(uploadPath),
            }));
        }
コード例 #10
0
        public async Task <string> UploadPublicPictureCompresser()
        {
            HttpFileCollection filecol = HttpContext.Current.Request.Files;

            PictureValidation.GetInstance().CompleteValidations(filecol);
            string uploadPath = PictureHandling.GetInstance().HandlingUpdatePublicDirectories();

            var multipartFormDataStreamProvider = new UploadMultipartFormProvider(uploadPath);

            await Request.Content.ReadAsMultipartAsync(multipartFormDataStreamProvider);

            string _localFileName = multipartFormDataStreamProvider
                                    .FileData.Select(multiPartData => multiPartData.LocalFileName).FirstOrDefault();

            string withoutextension = _localFileName.Split('.')[0];

            #region Qualitier
            var        qualitiesparam = HttpContext.Current.Request.Params["qualitier"];
            Qualitiers q = JsonConvert.DeserializeObject <Qualitiers>(qualitiesparam);
            #endregion

            using (System.IO.MemoryStream ms = PictureHandling.GetInstance().Resize(_localFileName, q))
            {
                ////with no compress;
                //Image img = System.Drawing.Image.FromStream(ms);

                //img.Save(withoutextension + "-th" + ".jpg");

                //with compress;
                Image             img = System.Drawing.Image.FromStream(ms);
                EncoderParameters eps = new EncoderParameters(1);
                eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);
                string         mimetype = GetMimeType(new System.IO.FileInfo(_localFileName).Extension);
                ImageCodecInfo ici      = GetEncoderInfo(mimetype);
                img.Save(withoutextension + "-th" + ".jpg", ici, eps);
            }

            return(JsonConvert.SerializeObject(new FileResult
            {
                FileName = Path.GetFileName(_localFileName),
                FileLength = new FileInfo(_localFileName).Length,
                LocalFilePath = Cryptography.Encrypt(_localFileName),
            }));
        }
コード例 #11
0
        public string DownloadPublicPicture64(FileResult file)
        {
            HttpResponseMessage result = null;
            string filename            = Cryptography.Decrypt(file.LocalFilePath);

            if (!File.Exists(filename))
            {
                return("");
            }
            string path = PictureHandling.GetInstance().HandlingDownloadPublicDirectories(filename);

            PictureValidation.GetInstance().ValidateFileExist(path);
            //result = Request.CreateResponse(HttpStatusCode.OK);
            //result.Content = new StreamContent(PictureHandling.GetInstance().Resize(path, file.Qualitier));
            //result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            //result.Content.Headers.ContentDisposition.FileName = filename.Substring(filename.LastIndexOf("\\") + 1, filename.Length - filename.LastIndexOf("\\") - 1);
            string src = Convert.ToBase64String(PictureHandling.GetInstance().Resize(path, file.Qualitier).ToArray());

            return(src);
        }
コード例 #12
0
        public void ValidatePicture()
        {
            const string name     = "testFirst";
            const string lastName = "testLast";
            var          netname  = StudentHelper.GenerateNetName(name, lastName);

            var users = new List <STUDENT>()
            {
                new STUDENT
                {
                    NETNAME     = netname,
                    ID          = 21941097,
                    FIRSTNAME   = name,
                    LASTNAME    = lastName,
                    DOB         = DateTime.UtcNow,
                    UGRADSTATUS = "U"
                },

                new STUDENT
                {
                    NETNAME     = "test",
                    ID          = 11941097,
                    FIRSTNAME   = name,
                    LASTNAME    = lastName,
                    DOB         = DateTime.UtcNow,
                    UGRADSTATUS = "U"
                },
            };

            _mySetStudent.Object.AddRange(users);
            ConnectMocksToDataStore(users);

            var pictures = new List <PICTURE>()
            {
                new PICTURE
                {
                    PICTURE_DATA    = null,
                    STUDENT_NETNAME = netname,
                    STATUS          = Status.Pending.ToString(),
                    CREATED         = new DateTime(1989, 11, 06)
                }, new PICTURE
                {
                    PICTURE_DATA    = null,
                    STUDENT_NETNAME = "test",
                    STATUS          = Status.Approved.ToString(),
                    CREATED         = new DateTime(1989, 11, 06)
                },
            };

            _mySetPicture.Object.AddRange(pictures);
            ConnectPictureMocksToDataStore(pictures);


            // Admin deny the picture
            var validationMessage = new PictureValidation
            {
                Id    = 21941097,
                Valid = false
            };

            var picturePending = _picture.FindPendingPicture(21941097);
            var pictureId      = picturePending.ID_PK;

            _repo.ValidatePicture(validationMessage, "test");

            var studentPictures = _picture.FindStudentPicturesAsync(21941097).Result;

            decimal id     = -1;
            var     status = "";

            // in our unit test our student has only 1 picture
            foreach (dynamic d in studentPictures.ArchivedPictures)
            {
                UnitTestHelper.PrintPropertiesOfDynamicObject(d);
                id     = UnitTestHelper.ReflectPropertyValue(d, "ID_PK");
                status = UnitTestHelper.ReflectPropertyValue(d, "STATUS");
            }

            Assert.Equal(Status.Denied.ToString(), status);
            Assert.Equal(pictureId, id);
        }
コード例 #13
0
 public override FileValidation ChargeMyValidator()
 {
     return(PictureValidation.GetInstance());
 }