//
 // GET: /Editor/Editor/
 public ActionResult Index()
 {
     try
     {
         using (PaperSubmissionsContext db = new PaperSubmissionsContext())
         {
             List<PaperSubmissionModel> backwards = db.PaperSubmissions.ToList();
             backwards.Reverse();
             return View(backwards);
         }
     }
     catch (Exception ex)
     {
         logger.Error(ex.Message);
     }
     return View();
 }
 public ActionResult Delete(int paperId)
 {
     WebMatrix.WebData.WebSecurity.RequireRoles(new string[] { "admin" });
     try
     {
         using (PaperSubmissionsContext db = new PaperSubmissionsContext())
         {
             PaperSubmissionModel submission = db.PaperSubmissions.First(x => x.Id == paperId);
             var authorsToRemove = submission.Authors.ToList();
             foreach (var a in authorsToRemove)
                 db.Entry(a).State = System.Data.Entity.EntityState.Deleted;
             submission.Authors.Clear();
             db.Entry(submission).State = System.Data.Entity.EntityState.Deleted;
             db.SaveChanges();
         }
         Tools.UploadsManager.DeleteFiles(paperId);
     }
     catch (Exception ex)
     {
         logger.Error(ex.Message);
     }
     return RedirectToAction("Index");
 }
        public ActionResult Create(PaperSubmissionModel paper)
        {
            try
            {
                // TODO: Add insert logic here
                paper.submissionDate = DateTime.Now.ToString("yyyy.MM.dd HH:mm");
                paper.lastStatusChangeDate = DateTime.Now.ToString("yyyy.MM.dd HH:mm");
                paper.Owner = WebMatrix.WebData.WebSecurity.CurrentUserName;
                //file upload logic below
                string subId = (string)TempData["UniqueSubmissionId"];
                logger.Info("subid: " + subId);
                if (subId == null)
                {
                    subId = Guid.NewGuid().ToString();
                    logger.Info("subid is null. new subid: " + subId);
                }

                TempData["UniqueSubmissionId"] = subId;//kepeing in tempdata
                paper.Attachment = Tools.UploadsManager.GetUpload(subId);
                logger.Info("IsAttachmentNull:" + (paper.Attachment == null));

                if (paper.Attachment != null)
                {
                    ModelState.Remove("Attachment");
                    ViewBag.UploadedInfo = paper.Attachment.ContentLength;
                }

                if (!ModelState.IsValid)
                {
                    return View("Create", paper);
                }

                paper.submissionState = 0;//0-submission just added
                using (PaperSubmissionsContext db = new PaperSubmissionsContext())
                {
                    db.PaperSubmissions.Add(paper);
                    db.Authors.AddRange(paper.Authors);
                    db.SaveChanges();
                }
                Tools.UploadsManager.SaveFile(paper.Id, subId);
                return RedirectToAction("Success", new { id = paper.Id });
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                // return View();
                return File(System.Text.ASCIIEncoding.Default.GetBytes(ex.Message), "text");
            }
        }
        //get
        public ActionResult Success(int id)
        {
            try
            {
                int[] legitStates = { 0 };
                ViewBag.paperId = id;
                using (PaperSubmissionsContext db = new PaperSubmissionsContext())
                {
                    var paper = db.PaperSubmissions.First(x => x.Id == id);
                    if (!legitStates.Contains(paper.submissionState))
                        return new HttpStatusCodeResult(HttpStatusCode.Forbidden);

                    if (paper.submissionState == 0)
                    {
                        paper.lastStatusChangeDate = DateTime.Now.ToString("yyyy.MM.dd HH:mm");
                        paper.submissionState = 1;
                        if (paper.Authors.Count == 0)
                            foreach (Author a in db.Authors.ToList())
                            {
                                if (a.PaperSubmissionModelId == id)
                                    paper.Authors.Add(a);
                            }
                        paper.Attachment = new FakePreprintAttachment("bogus.pdf");
                        if (paper.Reviewer == null)
                            paper.Reviewer = db.Reviewers.FirstOrDefault(x => x.PaperSubmissionModelId == id);
                        db.Entry(paper).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();
                        Tools.PanelHelper.CreateContext(paper);//creating context for panel

                        foreach (Author author in paper.Authors)
                            Tools.MailSender.SendMail(Tools.ConfigurationResourcesHelper.GetResource("messages", "EmailSubmissionNotificationTitle"), Tools.ConfigurationResourcesHelper.GetResourceVal("messages", "EmailSubmissionNotification", author), Tools.ConfigurationResourcesHelper.GetResource("options", "EmailNotificationAddress"), author.Email);
                        Tools.SMSSender.SendSms(Tools.ConfigurationResourcesHelper.GetResourceVal("messages", "SMSSubmissionNotification", paper), "7" + paper.ContactPhone);
                        //clean previous scheduled mails
                        Tools.ScheduleHelper.CleanRecurringJobs(id);
                        //new sendings
                        Tools.PanelHelper.SendSmsForCurrentState(paper, 1);
                        Tools.PanelHelper.SendMailForCurrentState(paper, 1, "");
                        Tools.PanelHelper.LogMessage(Tools.EditorHelper.GetStatusDescription(1) + " (статус: 1)", id, 0, Tools.AccountHelper.GetRoleTranslation(Tools.AccountHelper.GetUserRole(WebMatrix.WebData.WebSecurity.CurrentUserId)));
                    }
                }
                return View();
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                // return View();
                return File(System.Text.ASCIIEncoding.Default.GetBytes(ex.Message), "text");
            }
        }
 public ActionResult Download(int id, string type = "docx", bool forcorrector = false)
 {
     try
     {
         using (PaperSubmissionsContext db = new PaperSubmissionsContext())
         {
             var document = Tools.PaperSubmissionControllerHelper.CreateOrGetExistingDocument(db.PaperSubmissions.First(x => x.Id == id), forcorrector, false);
             if (type == "docx")
             {
                 var cd = new System.Net.Mime.ContentDisposition
                 {
                     // for example foo.bak
                     FileName = forcorrector ? "request_corrector.docx" : "request.docx",
                     // always prompt the user for downloading, set to true if you want
                     // the browser to try to show the file inline
                     Inline = false,
                 };
                 Response.AppendHeader("Content-Disposition", cd.ToString());
                 return File(System.IO.File.ReadAllBytes(document), "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
             }
             else
                 if (type == "pdf")
                 {
                     string pdfFile = Tools.PaperSubmissionControllerHelper.ConvertDocxToPDF(document);
                     var cd = new System.Net.Mime.ContentDisposition
                     {
                         // for example foo.bak
                         FileName = "request.pdf",
                         // always prompt the user for downloading, set to true if you want
                         // the browser to try to show the file inline
                         Inline = false,
                     };
                     Response.AppendHeader("Content-Disposition", cd.ToString());
                     return File(pdfFile, "application/pdf");
                 }
                 else
                     return File(System.Text.ASCIIEncoding.Default.GetBytes("Указан неизвестный формат выходного файла."), "text");
         }
     }
     catch (Exception ex)
     {
         logger.Error(ex.Message);
         return File(System.Text.ASCIIEncoding.Default.GetBytes(ex.Message), "text");
         //RedirectToAction("Index", db.PaperSubmissions.ToList());
     }
 }
 public ActionResult Submission(int id = 0)
 {
     if (id > 0)
     {
         try
         {
             using (PaperSubmissionsContext db = new PaperSubmissionsContext())
             {
                 PaperSubmissionModel submission = db.PaperSubmissions.First(x => x.Id == id);
                 if (Tools.AccountHelper.GetUserRole(WebSecurity.CurrentUserId) == "user")
                     WebSecurity.RequireUser(submission.Owner);
                 if (submission.Authors.Count == 0)
                     foreach (Author a in db.Authors.ToList())
                     {
                         if (a.PaperSubmissionModelId == id)
                             submission.Authors.Add(a);
                     }
                 if (submission.Reviewer == null)
                     submission.Reviewer = db.Reviewers.FirstOrDefault(x => x.PaperSubmissionModelId == id);
                 //submission.Attachment = new PreprintAttachment(Server.MapPath("~/App_Data/uploads/" + id + "/latest.pdf"));
                 //.Server.MapPath("~/App_Data/uploads/" + paper.Id)
                 return View(submission);
             }
         }
         catch (Exception ex)
         {
             logger.Error(ex.Message);
             return RedirectToAction("Index", "Edit");
         }
     }
     else
         return RedirectToAction("Index", "Edit");
 }
        public ActionResult Submission(PaperSubmissionModel paper)
        {
            try
            {
                //paper.Attachment = new PreprintAttachment(Server.MapPath("~/App_Data/uploads/" + paper.Id + "/latest.pdf"));
                //if (ModelState.Values.Count == 1 && ModelState.IsValidField("Attachment"))
                if (paper == null)
                    throw new ArgumentNullException("paper");
                if (paper.Attachment == null)
                    ModelState.Remove("Attachment");
                // TODO: Add insert logic here
                if (!ModelState.IsValid)
                {
                    return View("Submission", paper);
                }

                using (PaperSubmissionsContext db = new PaperSubmissionsContext())
                {
                    PaperSubmissionModel submission = db.PaperSubmissions.Find(paper.Id);
                    foreach (Author a in submission.Authors.ToList())
                    {
                        db.Entry(a).State = System.Data.Entity.EntityState.Deleted;
                    }
                    //dealing with attachments
                    if (paper.Attachment != null)
                    {
                        Tools.UploadsManager.SaveFile(paper.Id, paper.Attachment);
                        submission.Attachment = paper.Attachment;
                    }
                    else
                    {
                        submission.Attachment = new FakePreprintAttachment("bogus.pdf");
                    }

                    submission.Reviewer = db.Reviewers.Find(paper.Reviewer.Id);
                    db.SaveChanges();
                }

                using (PaperSubmissionsContext db = new PaperSubmissionsContext())
                {
                    PaperSubmissionModel submission = db.PaperSubmissions.Find(paper.Id);
                    Reviewer reviewer = db.Reviewers.Find(submission.Reviewer.Id);
                    reviewer.PaperSubmissionModelId = submission.Id;
                    reviewer.PaperSubmissionModel = submission;
                    db.Entry(reviewer).State = System.Data.Entity.EntityState.Modified;
                    submission.Reviewer = reviewer;
                    submission.Authors = paper.Authors;
                    foreach (Author a in submission.Authors)
                    {
                        a.PaperSubmissionModelId = submission.Id;
                        a.PaperSubmissionModel = submission;
                        db.Authors.Add(a);
                    }

                    submission.TitleEnglish = paper.TitleEnglish;
                    submission.TitleRussian = paper.TitleRussian;
                    submission.AbstractEnglish = paper.AbstractEnglish;
                    submission.AbstractRussian = paper.AbstractRussian;
                    submission.Bibliography = paper.Bibliography;
                    submission.ContactName = paper.ContactName;
                    submission.ContactPhone = paper.ContactPhone;
                    submission.FieldOfResearch = paper.FieldOfResearch;
                    submission.FinancialSupport = paper.FinancialSupport;
                    submission.KeywordsEnglish = paper.KeywordsEnglish;
                    submission.KeywordsRussian = paper.KeywordsRussian;
                    submission.Languages = paper.Languages;
                    submission.NumberOfAuthorsCopies = paper.NumberOfAuthorsCopies;
                    submission.NumberOfPages = paper.NumberOfPages;
                    submission.Review = paper.Review;
                    submission.UDK = paper.UDK;
                    if (paper.Attachment != null)
                        submission.Attachment = paper.Attachment;
                    else
                        submission.Attachment = new FakePreprintAttachment("bogus.pdf");
                    db.Entry(submission).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                    TempData["IsDataSaved"] = "True";
                    if (submission.submissionState > 0)
                        Tools.PanelHelper.LogMessage("Заявка отредактирована.", paper.Id, 0, Tools.AccountHelper.GetRoleTranslation(Tools.AccountHelper.GetUserRole(WebMatrix.WebData.WebSecurity.CurrentUserId)));
                    //updating submission files
                    //making 2 conversions at a time might be not good
                    //Tools.PaperSubmissionControllerHelper.CreateOrGetExistingDocument(paper, false, true);
                    //Tools.PaperSubmissionControllerHelper.CreateOrGetExistingDocument(paper, true, true);
                    //instead just deleting necessary files
                    string path = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads/" + paper.Id + "/");
                    if (System.IO.File.Exists(path + "submission.docx"))
                        System.IO.File.Delete(path + "submission.docx");
                    if (System.IO.File.Exists(path + "submission_for_corrector.docx"))
                        System.IO.File.Delete(path + "submission_for_corrector.docx");
                    return View("Submission", paper);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                TempData["IsDataSaved"] = "False";
                return View("Submission", paper);
                //return File(System.Text.ASCIIEncoding.Default.GetBytes(ex.Message), "text");
            }
        }
 public static bool GotAnySubmissions(string username)
 {
     lock (locker)
     {
         using (PaperSubmissionsContext db = new PaperSubmissionsContext())
         {
             List<PaperSubmissionModel> papers = db.PaperSubmissions.ToList();
             foreach (var paper in papers)
                 if (paper.Owner == username)
                     return true;
         }
         return false;
     }
 }
 public static bool GotAnySubmissions(int userId)
 {
     lock (locker)
     {
         using (PaperSubmissionsContext db = new PaperSubmissionsContext())
         {
             List<PaperSubmissionModel> papers = db.PaperSubmissions.ToList();
             foreach (var paper in papers)
                 if (WebMatrix.WebData.WebSecurity.GetUserId(paper.Owner) == userId)
                     return true;
         }
         return false;
     }
 }
 public static PaperSubmissionModel GetModel(int id)
 {
     lock (locker)
     {
         using (PaperSubmissionsContext db = new PaperSubmissionsContext())
         {
             var paper = db.PaperSubmissions.First(x => x.Id == id);
             if (paper.Authors.Count == 0)
                 foreach (Author a in db.Authors.ToList())
                 {
                     if (a.PaperSubmissionModelId == id)
                         paper.Authors.Add(a);
                 }
             paper.Attachment = new FakePreprintAttachment("bogus.pdf");
             if (paper.Reviewer == null)
                 paper.Reviewer = db.Reviewers.FirstOrDefault(x => x.PaperSubmissionModelId == id);
             return paper;
         }
     }
 }
 //public ActionResult GetLog(int paperId, int subLogId, int lastLogId)
 //{
 //    try
 //    {
 //        //logger.Info("lastLogLogId: " + lastLogId);
 //        //DateTime d = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
 //        //d = d.AddMilliseconds(Convert.ToInt64(lastUpdateTime));
 //        //DateTime lastUpdate = d.ToLocalTime();
 //        //return Json(System.Text.UnicodeEncoding.Default.GetBytes(Tools.PanelHelper.GetLogAfterId(paperId, lastLogId)), "text");
 //        string contentstring = Tools.PanelHelper.GetWholeSubLogAfterId(paperId, subLogId, lastLogId);
 //        //logger.Info("content: " + contentstring);
 //        return Json(new { lastId = Tools.PanelHelper.GetLastId(paperId, subLogId).ToString(), content = contentstring }, JsonRequestBehavior.AllowGet);
 //    }
 //    catch (Exception ex)
 //    {
 //        logger.Error(ex.Message);
 //        return File(System.Text.ASCIIEncoding.Default.GetBytes(ex.Message), "text");
 //    }
 //}
 private void changeState(int id, int state)
 {
     lock (locker)
     {
         using (PaperSubmissionsContext db = new PaperSubmissionsContext())
         {
             var paper = db.PaperSubmissions.First(x => x.Id == id);
             paper.submissionState = state;
             paper.lastStatusChangeDate = DateTime.Now.ToString("yyyy.MM.dd HH:mm");
             if (paper.Authors.Count == 0)
                 foreach (Author a in db.Authors.ToList())
                 {
                     if (a.PaperSubmissionModelId == id)
                         paper.Authors.Add(a);
                 }
             paper.Attachment = new FakePreprintAttachment("bogus.pdf");
             if (paper.Reviewer == null)
                 paper.Reviewer = db.Reviewers.FirstOrDefault(x => x.PaperSubmissionModelId == id);
             db.Entry(paper).State = System.Data.Entity.EntityState.Modified;
             db.SaveChanges();
         }
     }
 }
 public ActionResult Index()
 {
     try
     {
         using (PaperSubmissionsContext db = new PaperSubmissionsContext())
         {
             List<PaperSubmissionModel> backwards = db.PaperSubmissions.ToList();
             foreach (var paper in backwards)
             {
                 if (paper.Authors.Count == 0)
                     foreach (Author a in db.Authors.ToList())
                     {
                         if (a.PaperSubmissionModelId == paper.Id)
                             paper.Authors.Add(a);
                     }
                 if (paper.Reviewer == null)
                     paper.Reviewer = db.Reviewers.FirstOrDefault(x => x.PaperSubmissionModelId == paper.Id);
             }
             backwards.Reverse();
             return View(backwards);
         }
     }
     catch (Exception ex)
     {
         logger.Error(ex.Message);
         return File(System.Text.ASCIIEncoding.Default.GetBytes(ex.Message), "text");
     }
 }