public ActionResult UploadFiles(HttpPostedFileBase[] files)
        {
            TempData["notice"] = "Files saved";
            bool fileIsTooLarge       = false;
            bool fileExtensionInvalid = false;

            //Ensure model state is valid
            if (ModelState.IsValid)
            {   //iterating through multiple file collection
                foreach (HttpPostedFileBase file in files)
                {
                    //Checking file is available to save.
                    if (file != null)
                    {
                        var checkextension = new[] { Path.GetExtension(file.FileName).ToLower() };

                        var allowedFileExtentions = new AllowedFileExtensionsHelper();
                        var maximumAttachmentSize = new AllowedFileSizeHelper();

                        // Todo one entrypoint into size check

                        if (!allowedFileExtentions.FileExtentionAllowed(checkextension))
                        {
                            fileExtensionInvalid = true;
                            TempData["notice"]   = "Only PDF documents and images (.jpg | .jpeg | .png) may be uploaded.";
                        }

                        if (maximumAttachmentSize.AllowedFileSize(files.Count(), file.ContentLength))
                        {
                            fileIsTooLarge     = true;
                            TempData["notice"] = "A single attachment cannot exceed than 3MB and the total attachment size cannot exceed 15MB.";
                        }

                        if ((!fileExtensionInvalid) && (!fileIsTooLarge))
                        {
                            try
                            {
                                var InputFileName  = Path.GetFileName(file.FileName);
                                var ServerSavePath = Path.Combine(Server.MapPath("~/UploadedFiles") + InputFileName);

                                //Save file to server folder
                                file.SaveAs(ServerSavePath);
                                //assigning file uploaded status to ViewBag for showing message to user.
                                ViewBag.UploadStatus = files.Count().ToString() + " files uploaded successfully.";
                            }
                            catch (FileLoadException fEx)
                            {
                                TempData["notice"] = "A single attachment cannot exceed than 3MB and the total attachment size cannot exceed 15MB.";
                            }
                            catch (Exception ex)
                            {
                                TempData["notice"] = ex.Message.ToString();
                            }
                        }
                    }
                }
            }

            return(View());
        }
Пример #2
0
        public ActionResult Edit(int id, [Bind(Include = "Id")] FormCollection requestForm, HttpPostedFileBase[] upload)
        {
            bool   uploadedFileFailure = false;
            string uploadedFileMessage = string.Empty;

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var authUser = User.Identity.GetUserId();


            if (ModelState.IsValid)
            {
                var request    = db.Request.Find(id);
                var attachment = db.Attachment.SingleOrDefault(c => c.Id == id);

                request.Title       = requestForm["Request.Title"];
                request.Description = requestForm["Request.Description"];
                request.ModifyDate  = DateTime.Today;
                request.Amount      = Convert.ToDecimal(requestForm["Request.Amount"]);
                request.StatusId    = requestForm["Request.StatusId"] != null?Int32.Parse(requestForm["Request.StatusId"]) : 1;

                db.Entry(request).State = EntityState.Modified;

                var addFile = false;

                if (attachment == null)
                {
                    addFile = true;
                }

                bool fileIsTooLarge       = false;
                bool fileExtensionInvalid = false;

                foreach (HttpPostedFileBase file in upload)
                {
                    //Checking file is available to save.
                    if (file != null)
                    {
                        var checkextension = new[] { Path.GetExtension(file.FileName).ToLower() };

                        var allowedFileExtentions = new AllowedFileExtensionsHelper();
                        var maximumAttachmentSize = new AllowedFileSizeHelper();

                        if (!allowedFileExtentions.FileExtentionAllowed(checkextension))
                        {
                            fileExtensionInvalid = true;
                            uploadedFileMessage  = "Only PDF documents and images (.jpg | .jpeg | .png) may be uploaded.";
                            uploadedFileFailure  = true;
                        }

                        if (maximumAttachmentSize.AllowedFileSize(upload.Count(), file.ContentLength))
                        {
                            fileIsTooLarge      = true;
                            uploadedFileMessage = "A single attachment cannot exceed than 3MB and the total attachment size cannot exceed 15MB.";
                            uploadedFileFailure = true;
                        }

                        if ((!fileExtensionInvalid) && (!fileIsTooLarge))
                        {
                            try
                            {
                                attachment.RequestId   = id;
                                attachment.File        = Path.GetFileName(file.FileName);
                                attachment.ContentType = file.ContentType;

                                using (var reader = new BinaryReader(file.InputStream))
                                {
                                    attachment.Content = reader.ReadBytes(file.ContentLength);

                                    db.Attachment.Add(attachment);
                                }
                            }
                            catch (Exception ex)
                            {
                                uploadedFileMessage = ex.Message.ToString();
                                uploadedFileFailure = true;
                            }
                        }
                    }
                }

                try
                {
                    db.SaveChanges();
                    return(RedirectToAction(nameof(EditConfirmation), new { message = uploadedFileMessage, uploadedFile = uploadedFileFailure }));
                }
                catch (DbEntityValidationException ex)
                {
                    foreach (var entityValidationErrors in ex.EntityValidationErrors)
                    {
                        foreach (var validationError in entityValidationErrors.ValidationErrors)
                        {
                            ViewBag.Message("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                        }
                    }
                }
                catch (OptimisticConcurrencyException)
                {
                    db.SaveChanges();
                }
            }

            return(View());
        }
Пример #3
0
        public ActionResult Index([Bind(Include = "Id")] FormCollection requestForm, HttpPostedFileBase[] upload)
        {
            var    authUser            = User.Identity.GetUserId();
            bool   uploadedFileFailure = false;
            string uploadedFileMessage = string.Empty;

            if (ModelState.IsValid)
            {
                RequestModel request = new RequestModel();
                request.Title            = requestForm["Title"];
                request.Description      = requestForm["Description"];
                request.Charity          = requestForm["Charity"];
                request.PlayItForward    = requestForm["PlayItForward"] != null ? true : false;
                request.Amount           = Convert.ToDecimal(requestForm["Amount"].Replace(".", ","));
                request.SubmissionDate   = DateTime.Today;
                request.ModifyDate       = DateTime.Today;
                request.User             = authUser;
                request.StatusId         = 1;
                request.ConfirmationCode = Guid.NewGuid().ToString().Substring(0, 9);

                db.Request.Add(request);

                try
                {
                    db.SaveChanges();

                    int requestId = GetRequestId(request.ConfirmationCode.ToString());

                    if (requestId != 0)
                    {
                        AttachmentModel requestAttachment = new AttachmentModel();

                        bool fileIsTooLarge       = false;
                        bool fileExtensionInvalid = false;

                        foreach (HttpPostedFileBase file in upload)
                        {
                            //Checking file is available to save.
                            if (file != null)
                            {
                                var checkextension = new[] { Path.GetExtension(file.FileName).ToLower() };

                                var allowedFileExtentions = new AllowedFileExtensionsHelper();
                                var maximumAttachmentSize = new AllowedFileSizeHelper();

                                if (!allowedFileExtentions.FileExtentionAllowed(checkextension))
                                {
                                    fileExtensionInvalid = true;
                                    uploadedFileMessage  = "Only PDF documents and images (.jpg | .jpeg | .png) may be uploaded.";
                                    uploadedFileFailure  = true;
                                }

                                if (maximumAttachmentSize.AllowedFileSize(upload.Count(), file.ContentLength))
                                {
                                    fileIsTooLarge      = true;
                                    uploadedFileMessage = "A single attachment cannot exceed than 3MB and the total attachment size cannot exceed 15MB.";
                                    uploadedFileFailure = true;
                                }

                                if ((!fileExtensionInvalid) && (!fileIsTooLarge))
                                {
                                    try
                                    {
                                        requestAttachment.RequestId   = requestId;
                                        requestAttachment.File        = Path.GetFileName(file.FileName);
                                        requestAttachment.ContentType = file.ContentType;

                                        using (var reader = new BinaryReader(file.InputStream))
                                        {
                                            requestAttachment.Content = reader.ReadBytes(file.ContentLength);

                                            db.Attachment.Add(requestAttachment);
                                        }

                                        uploadedFileMessage = upload.Count().ToString() + " file(s) uploaded.";
                                    }
                                    catch (Exception ex)
                                    {
                                        uploadedFileMessage = ex.Message.ToString();
                                        uploadedFileFailure = true;
                                    }
                                }
                            }

                            db.SaveChanges();
                        }

                        //string callbackUrl = SendEmailConfirmationTokenAsync(authUser, requestId, "Confirm your request.");

                        return(RedirectToAction(nameof(CreateConfirmation), new { message = uploadedFileMessage, uploadedFile = uploadedFileFailure }));
                    }
                }
                catch (DbEntityValidationException ex)
                {
                    foreach (var entityValidationErrors in ex.EntityValidationErrors)
                    {
                        foreach (var validationError in entityValidationErrors.ValidationErrors)
                        {
                            // Sent to error page
                            // TempData["notice"] = "Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage;
                        }
                    }
                }
            }

            return(RedirectToAction(nameof(Index)));
        }