// GET: Ideas/Edit/5
        public ActionResult Edit(int?id)
        {
            var model = new FileSelectionViewModel();

            model.idea = db.Ideas.Find(id);

            foreach (var attachment in db.Attachments)
            {
                if (attachment.ideaID == model.idea.ID)
                {
                    var editorViewModel = new SelectFileEditorViewModel()
                    {
                        ID       = attachment.ID,
                        Name     = attachment.name,
                        Selected = false
                    };
                    model.Attachs.Add(editorViewModel);
                }
            }
            return(View(model));
        }
 public FileSelectionPage(FileSelectionViewModel fileSelectionViewModel)
 {
     InitializeComponent();
     DataContext = fileSelectionViewModel;
 }
        public ActionResult Edit(FileSelectionViewModel model, IEnumerable <HttpPostedFileBase> files)
        {
            if (ModelState.IsValid)
            {
                db.Entry(model.idea).State = EntityState.Modified;

                var currentIdea = db.Ideas.FirstOrDefault(p => p.ID == model.idea.ID);

                var ideas = db.Ideas.Where(IDEA => IDEA.title == model.idea.title && IDEA.ID != model.idea.ID).ToList();

                if (ideas.Count > 0)
                {
                    return(View(model));
                }

                // If the Idea is already in the "Submitted" state, another email will not be sent.
                bool alreadySubmitted = false;
                if (currentIdea.statusCode == "Submitted")
                {
                    alreadySubmitted = true;
                }
                currentIdea.title        = model.idea.title;
                currentIdea.body         = model.idea.body;
                currentIdea.statusCode   = "Submitted";
                currentIdea.denialReason = model.idea.denialReason;
                currentIdea.mod_date     = DateTime.Now;
                currentIdea.email        = model.idea.email;

                if (files != null)
                {
                    var appSettings = ConfigurationManager.AppSettings;

                    // store path to server location of the attachment storage
                    var connectionInfo = appSettings["serverPath"];

                    // combine the server location and the name of the new folder to be created
                    var storagePath = string.Format(@"{0}{1}_{2}", connectionInfo, model.idea.ID, model.idea.title);
                    if (!Directory.Exists(storagePath))
                    {
                        DirectoryInfo di = Directory.CreateDirectory(storagePath);
                    }

                    //run each file through MetaScan and check for forbidden extensions
                    for (int i = 0; i < files.Count(); ++i)
                    {
                        if (files.ElementAt(i) != null && files.ElementAt(i).ContentLength > 0)
                        {
                            var file = files.ElementAt(i);
                            // store the name of the attachment

                            // place the file into a bytearray for MetaScan use
                            FileStream stream    = System.IO.File.OpenRead(Path.GetFullPath(file.FileName));
                            byte[]     fileBytes = new byte[stream.Length];

                            stream.Read(fileBytes, 0, fileBytes.Length);
                            stream.Close();

                            // make the file a bytearray and send to MetaScan here?
                            FileService.FileService sf = new FileService.FileService();

                            string ext = Path.GetExtension(file.FileName);

                            bool valrtn = sf.ScanByFileWithNameAndExtension(fileBytes, file.FileName, ext);

                            // If any file fails to load, reload the creation screen and inform the submitter of the need to scan the files.
                            if (!valrtn)
                            {
                                TempData["ScanFailure"] = "\n\nThe files failed to upload. " +
                                                          "Please scan them locally using McAffee before uploading them again." +
                                                          " Selected files have not been deleted.";

                                return(View(model));
                            }
                        }
                    }

                    // save the files to the specified folder and link them to the idea
                    for (int i = 0; i < files.Count(); ++i)
                    {
                        if (files.ElementAt(i) != null && files.ElementAt(i).ContentLength > 0)
                        {
                            var file           = files.ElementAt(i);
                            var attachmentName = Path.GetFileName(file.FileName);
                            var namepath       = string.Format("{0}\\{1}", storagePath, attachmentName);

                            // save the new Attachments to the Idea
                            var attachment = new Models.Attachment
                            {
                                storageLocation = string.Format("{0}\\", storagePath),
                                name            = attachmentName,
                                cre_date        = DateTime.Now,
                                deleteObj       = "false"
                            };

                            try
                            {
                                file.SaveAs(string.Format("{0}\\{1}", storagePath, attachmentName));
                            }
                            catch (Exception ex)
                            {
                                TempData["Message"] += String.Format("An error was caught: Error number: {0}, Message: {1}", ex.HResult, ex.Message);
                                return(View(model));
                            }

                            if (model.idea.attachments == null)
                            {
                                model.idea.attachments = new List <Models.Attachment>();
                            }

                            model.idea.attachments.Add(attachment);
                            db.Attachments.Add(attachment);
                        }
                    }
                }
                // save the new Attachments to the Idea
                try
                {
                    db.SaveChanges();
                }
                catch (SqlException ex)
                {
                    log.Error("An error has occured while accessing the database.", ex);
                    return(RedirectToAction("AnError", "Error"));
                }

                // get the ids of the items selected:
                var selectedIds = model.getSelectedIds();

                // Use the ids to retrieve the records for the selected people
                // from the database:
                var selectedAttachments = from x in db.Attachments
                                          where selectedIds.Contains(x.ID)
                                          select x;

                // Process according to your requirements:
                foreach (var attachment in selectedAttachments)
                {
                    // in here is where I will delete the attachments based on what was selected.
                    attachment.DeleteFile();
                    db.Attachments.Remove(attachment);
                }

                try
                {
                    db.SaveChanges();
                }
                catch (SqlException ex)
                {
                    log.Error("An error has occured while accessing the database.", ex);
                    return(RedirectToAction("AnError", "Error"));
                }

                if (!alreadySubmitted)
                {
                    // Compose an email to send to PPMO Group and return to index
                    List <string> emailInfo = new List <string> {
                        "2", model.idea.email, model.idea.title, model.idea.body, model.idea.cre_user, model.idea.ID.ToString()
                    };
                    TempData["EmailInfo"] = emailInfo;

                    return(RedirectToAction("AutoEmail", "Mails"));
                    // This is only for Josh and Alex since they don't have access to AD
                    //return RedirectToAction("Index", "Ideas");
                }
                TempData["Message"] = "Your idea has been successfully submitted.";
                return(RedirectToAction("Index", "Ideas"));
            }
            return(View(model));
        }