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");
            }
        }
        public static void CreateContext(PaperSubmissionModel paper)
        {
            lock (lockTrigger)
            {
                PanelContextModel context = new PanelContextModel();
                context.paperId = paper.Id;
                string path = pathToWorkingDirectory + paper.Id + "/context.xml";

                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(PanelContextModel));
                using (MemoryStream stream = new MemoryStream())
                {
                    serializer.Serialize(stream, context);
                    File.WriteAllText(path, System.Text.Encoding.Default.GetString(stream.ToArray()));
                }
            }
        }
        public static List<MailInfo> GetMailsForCurrentState(int stateId, PaperSubmissionModel paper, string message)
        {
            List<MailInfo> result = new List<MailInfo>();
            string[] files = Directory.GetFiles(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/templates/" + stateId));
            foreach (string file in files)
            {
                string serialized = File.ReadAllText(file);
                MailInfo mail = MailInfo.DeserializeFromXmlString(serialized);
                mail.Subject = Tools.ConfigurationResourcesHelper.GetStringWithSubstitutions(mail.Subject.Replace("@message@", message).Trim(), paper, paper.Authors.FirstOrDefault());
                mail.Body = Tools.ConfigurationResourcesHelper.GetStringWithSubstitutions(mail.Body.Replace("@message@", message).Trim(), paper, paper.Authors.FirstOrDefault());
                mail.PaperId = paper.Id;
                if (mail.IsAnyAttachments)
                    for (int i = 0; i < mail.Attachments.Count; i++)
                    {
                        if (mail.Attachments[i] == "ReplaceForPathToPaper")
                        {
                            mail.Attachments[i] = Tools.UploadsManager.Latest(paper.Id).Path;
                        }
                        if (mail.Attachments[i] == "ReplaceForPathToSubmission")
                        {
                            mail.Attachments[i] = Tools.PaperSubmissionControllerHelper.CreateOrGetExistingDocument(paper, false, false);//submission file
                        }
                    }

                switch (mail.To)
                {
                    case "toAllAuthors":
                        var authors = paper.Authors;
                        if (authors == null || authors.Count == 0)
                            break;
                        mail.To = authors.First().Email;
                        for (int i = 1; i < paper.Authors.Count; i++)
                        {
                            Author a = paper.Authors.ElementAt(i);
                            MailInfo copymail = MailInfo.DeserializeFromXmlString(serialized);
                            copymail.Body = copymail.Body.Replace("@message@", message).Trim();
                            copymail.Attachments.Clear();
                            copymail.Attachments.AddRange(mail.Attachments);
                            copymail.To = a.Email;
                            result.Add(copymail);
                        }
                        break;
                    case "toEditor":
                        var editors = Tools.AccountHelper.GetUsersInRole("admin");
                        if (editors == null || editors.Count == 0)
                            break;
                        mail.To = editors.First();
                        for (int i = 1; i < editors.Count; i++)
                        {
                            string editor = editors[i];
                            MailInfo copymail = MailInfo.DeserializeFromXmlString(serialized);
                            copymail.Body = copymail.Body.Replace("@message@", message).Trim();
                            copymail.Attachments.Clear();
                            copymail.Attachments.AddRange(mail.Attachments);
                            copymail.To = editor;
                            result.Add(copymail);
                        }
                        break;
                    case "toCorrector":
                        var correctors = Tools.AccountHelper.GetUsersInRole("corrector");
                        if (correctors == null || correctors.Count == 0)
                            break;
                        mail.To = correctors.First();
                        for (int i = 1; i < correctors.Count; i++)
                        {
                            string corrector = correctors[i];
                            MailInfo copymail = MailInfo.DeserializeFromXmlString(serialized);
                            copymail.Body = copymail.Body.Replace("@message@", message).Trim();
                            copymail.Attachments.Clear();
                            copymail.Attachments.AddRange(mail.Attachments);
                            copymail.To = corrector;
                            result.Add(copymail);
                        }
                        break;
                    case "toAuthor":
                        mail.To = paper.Owner;
                        break;
                    case "toEditorialBoard":
                        throw new NotImplementedException("Рассылка почты редколлегии не реализована");
                        break;
                    case "toTypographer":
                        var typographers = Tools.AccountHelper.GetUsersInRole("typographer");
                        if (typographers == null || typographers.Count == 0)
                            break;
                        mail.To = typographers.First();
                        for (int i = 1; i < typographers.Count; i++)
                        {
                            string typographer = typographers[i];
                            MailInfo copymail = MailInfo.DeserializeFromXmlString(serialized);
                            copymail.Body = copymail.Body.Replace("@message@", message).Trim();
                            copymail.Attachments.Clear();
                            copymail.Attachments.AddRange(mail.Attachments);
                            copymail.To = typographer;
                            result.Add(copymail);
                        }
                        break;
                    case "toInternetGuy":
                        var internetGuys = Tools.AccountHelper.GetUsersInRole("internetguy");
                        if (internetGuys == null || internetGuys.Count == 0)
                            break;
                        mail.To = internetGuys.First();
                        for (int i = 1; i < internetGuys.Count; i++)
                        {
                            string internetGuy = internetGuys[i];
                            MailInfo copymail = MailInfo.DeserializeFromXmlString(serialized);
                            copymail.Body = copymail.Body.Replace("@message@", message).Trim();
                            copymail.Attachments.Clear();
                            copymail.Attachments.AddRange(mail.Attachments);
                            copymail.To = internetGuy;
                            result.Add(copymail);
                        }
                        break;
                }
                result.Add(mail);
            }
            return result;
        }
        public static void SendSmsForCurrentState(PaperSubmissionModel paper, int stateId)
        {
            var context = GetContext(paper.Id);
            if (context.smsForbidden)
                return;

            var messages = GetSmsForCurrentState(stateId, paper);
            foreach (SmsInfo sms in messages)
            {
                if (sms.HourInterval > 0)
                {
                    SMSSender.ScheduleMessage(sms);
                }
                else
                    SMSSender.SendSms(sms);
            }
        }
 public static void SendMailForCurrentState(PaperSubmissionModel paper, int stateId, string message)
 {
     var messages = GetMailsForCurrentState(stateId, paper, message);
     foreach (MailInfo mail in messages)
     {
         if (mail.HourInterval > 0)
         {
             MailSender.ScheduleMessage(mail);
         }
         else
             MailSender.SendMail(mail);
     }
 }
        public static List<SmsInfo> GetSmsForCurrentState(int stateId, PaperSubmissionModel paper)
        {
            List<SmsInfo> result = new List<SmsInfo>();
            string[] files = Directory.GetFiles(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/templates/sms/" + stateId));
            foreach (string file in files)
            {
                string serialized = File.ReadAllText(file);
                SmsInfo sms = SmsInfo.DeserializeFromXmlString(serialized);
                sms.PaperId = paper.Id;

                switch (sms.To)
                {
                    case "toAllAuthors":
                        sms.To = paper.ContactPhone.Replace("(", string.Empty).Replace(")", string.Empty).Replace("-", string.Empty).Replace(" ", string.Empty);
                        break;
                    case "toEditor":
                        sms.To = Tools.ConfigurationResourcesHelper.GetResource("mailinglist", "EditorPhone");
                        break;
                    case "toCorrector":
                        sms.To = Tools.ConfigurationResourcesHelper.GetResource("mailinglist", "CorrectorPhone");
                        break;
                    case "toAuthor":
                        sms.To = paper.ContactPhone;
                        break;
                    case "toEditorialBoard":
                        throw new NotImplementedException("Рассылка смс редколлегии не реализована");
                    //break;
                }
                result.Add(sms);
            }
            return result;
        }
        public ActionResult SaveTemporarySubmission(PaperSubmissionModel paper)
        {
            //try
            //{
            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;
            string content = Tools.PaperSubmissionControllerHelper.SerializeModel(paper);
            string authors = "";
            if (paper.Authors != null)
                authors = Tools.PaperSubmissionControllerHelper.SerializeAuthors(paper.Authors.ToList());

            string subId = (string)TempData["UniqueSubmissionId"];
            logger.Info("subid: " + subId);
            if (subId != null)
            {
                TempData["UniqueSubmissionId"] = subId;//kepeing in tempdata
                paper.Attachment = Tools.UploadsManager.GetUpload(subId);
                logger.Info("IsAttachmentNull:" + (paper.Attachment == null));
                //Tools.UploadsManager.SaveFile(paper.Id, subId);
            }

            Tools.PaperSubmissionControllerHelper.SaveTemporarySubmission(content, authors, subId, WebMatrix.WebData.WebSecurity.CurrentUserName);
            return new HttpStatusCodeResult(HttpStatusCode.OK);
            //}
            //catch (Exception ex)
            //{
            //    logger.Error(ex.Message);
            //    // return View();
            //    return File(System.Text.ASCIIEncoding.Default.GetBytes(ex.Message), "text");
            //}
        }
        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 string CreateOrGetExistingDocument(PaperSubmissionModel paper, bool correctorVersion, bool overrideExisting)
        {
            //first of all performing check whether the file already exists
            string filename = correctorVersion ? "submission_for_corrector.docx" : "submission.docx";
            string path = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads/" + paper.Id + "/" + filename);
            if (File.Exists(path) && !overrideExisting)
                return path;

            string pathToDocTemplate = "~/App_Data/request_template.docx";
            if (correctorVersion)
                pathToDocTemplate = "~/App_Data/request_template_corrector.docx";
            using (DocX document = DocX.Load(HttpContext.Current.Server.MapPath(pathToDocTemplate)))
            {
                Row r = document.Tables[0].Rows[1];
                for (int i = 0; i < paper.Authors.Count - 1; i++)//there is always 2 rows(one for title, one for author), so adding insufficient amount of rows
                    document.Tables[0].InsertRow(r, 1);
                List<Author> authors = paper.Authors.ToList();
                if (authors.Count > 0)
                    for (int i = 0; i < document.Tables[0].RowCount - 1; i++)
                    {
                        Row currentRow = document.Tables[0].Rows[i + 1];
                        //string shortNameRussian = authors[i].LastnameRussian + " " + authors[i].FirstnameRussian[0] + ".";
                        //if (authors[i].PatronymRussian.Length > 0)
                        //    shortNameRussian += authors[i].PatronymRussian[0] + ".";
                        currentRow.Cells[0].Paragraphs[0].InsertText(authors[i].LastnameRussian + " " + authors[i].FirstnameRussian + " " + authors[i].PatronymRussian);
                        //p1.IndentationBefore = 0.0f;
                        //string shortNameEnglish = authors[i].LastnameEnglish + " " + authors[i].FirstnameEnglish[0] + ".";
                        //if (authors[i].PatronymEnglish.Length > 0)
                        //    shortNameEnglish += authors[i].PatronymEnglish[0] + ".";
                        currentRow.Cells[1].Paragraphs[0].InsertText(authors[i].LastnameEnglish + " " + authors[i].FirstnameEnglish + " " + authors[i].PatronymEnglish);

                        currentRow.Cells[2].Paragraphs[0].InsertText(authors[i].PlaceOfWork);
                        currentRow.Cells[3].Paragraphs[0].InsertText(authors[i].Email + " " + authors[i].PersonalWeb);
                        string spin = String.IsNullOrEmpty(authors[i].SPIN) ? "Нет" : authors[i].SPIN;
                        string orcid = String.IsNullOrEmpty(authors[i].ORCID) ? "Нет" : authors[i].ORCID;
                        string researcherid = String.IsNullOrEmpty(authors[i].ResearcherID) ? "Не указан" : authors[i].ResearcherID;
                        currentRow.Cells[4].Paragraphs[0].InsertText("SPIN " + spin + ";\r\nORCID " + orcid + ";\r\nResearcherID " + researcherid);
                    }

                document.ReplaceText("@TitleRussian@", paper.TitleRussian, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                document.ReplaceText("@TitleEnglish@", paper.TitleEnglish, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                document.ReplaceText("@KeywordsRussian@", paper.KeywordsRussian.Replace(";", "; "), false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                document.ReplaceText("@KeywordsEnglish@", paper.KeywordsEnglish.Replace(";", "; "), false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                document.ReplaceText("@Languages@", paper.Languages, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                document.ReplaceText("@NumOfPages@", paper.NumberOfPages.ToString(), false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                document.ReplaceText("@NumOfAuthorsCopies@", paper.NumberOfAuthorsCopies.ToString(), false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                document.ReplaceText("@FieldOfResearch@", FieldOfResearchConverter.GetRussian(paper.FieldOfResearch), false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                document.ReplaceText("@UDK@", paper.UDK, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                document.ReplaceText("@FinancialSupport@", paper.FinancialSupport, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                document.ReplaceText("@Contacts@", paper.ContactName + ", " + paper.ContactPhone, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                //signature fields
                int signatureTableIndex = 10;
                if (correctorVersion)
                    signatureTableIndex = 12;
                for (int i = 0; i < (paper.Authors.Count / 2); i++)//there is always 1 row, so adding insufficient amount of rows
                    document.Tables[signatureTableIndex].InsertRow(1);
                string signature = document.Tables[signatureTableIndex].Rows[0].Cells[0].Paragraphs[0].Text;//first cell always containing signature field
                int signatureCount = 0;
                document.Tables[signatureTableIndex].Rows[0].Cells[0].Paragraphs[0].RemoveText(0);
                document.Tables[signatureTableIndex].Rows[0].Cells[0].Paragraphs[0].InsertText(signature.Replace("@PartName@", authors[0].FirstnameRussian.FirstOrDefault() + "." + (authors[0].PatronymRussian != null ? authors[0].PatronymRussian.FirstOrDefault() + "." : string.Empty) + " " + authors[0].LastnameRussian));
                foreach (var row in document.Tables[signatureTableIndex].Rows)
                {
                    //there is just two columns, so i think it is better the way it is than for(int i=0; i<=1; i++)
                    //this is code for first column
                    if (signatureCount > 0)
                        row.Cells[0].Paragraphs[0].InsertText(signature.Replace("@PartName@", authors[signatureCount].FirstnameRussian.FirstOrDefault() + "." + (authors[signatureCount].PatronymRussian != null ? authors[signatureCount].PatronymRussian.FirstOrDefault() + "." : string.Empty) + " " + authors[signatureCount].LastnameRussian));
                    signatureCount++;
                    if (signatureCount == paper.Authors.Count)
                        break;
                    //this is code for second column
                    row.Cells[1].Paragraphs[0].InsertText(signature.Replace("@PartName@", authors[signatureCount].FirstnameRussian.FirstOrDefault() + "." + (authors[signatureCount].PatronymRussian != null ? authors[signatureCount].PatronymRussian.FirstOrDefault() + "." : string.Empty) + " " + authors[signatureCount].LastnameRussian));
                    signatureCount++;
                    if (signatureCount == paper.Authors.Count)
                        break;
                }

                if (correctorVersion)
                {
                    DocX add = DocX.Load(ConvertHtmlToDocx("<html><div><table><tr><td>" + paper.AbstractRussian + "</td><td>" + paper.AbstractEnglish + "</td></tr></table></div><br/><hr/><br/><div><table><tr><td>" + paper.Bibliography + "</td></tr></table></div><br/><hr/><br/><div><table><tr><td>" + paper.Review + "</td></tr></table></div></html>"));

                    foreach (Paragraph p in add.Tables[0].Rows[0].Cells[0].Paragraphs)//abstract russian
                    {
                        p.IndentationFirstLine = 0.0f;
                        document.Tables[2].Rows[1].Cells[0].InsertParagraph(p);
                    }
                    foreach (Paragraph p in add.Tables[0].Rows[0].Cells[1].Paragraphs)//abstract english
                    {
                        p.IndentationFirstLine = 0.0f;
                        document.Tables[2].Rows[1].Cells[1].InsertParagraph(p);
                    }

                    foreach (Paragraph p in add.Tables[1].Rows[0].Cells[0].Paragraphs)//bibliography
                    {
                        p.IndentationFirstLine = 0.0f;
                        document.Tables[9].Rows[0].Cells[0].InsertParagraph(p);
                    }

                    foreach (Paragraph p in add.Tables[2].Rows[0].Cells[0].Paragraphs)//review
                    {
                        p.IndentationFirstLine = 0.0f;
                        document.InsertParagraph(p);
                    }

                    add.Dispose();
                    DocX end = DocX.Load(HttpContext.Current.Server.MapPath("~/App_Data/request_template_ending.docx"));
                    end.ReplaceText("@JobPosition@", paper.Reviewer.JobTitle, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    string reviewerPartName = paper.Reviewer.Degree + " " + paper.Reviewer.Firstname.FirstOrDefault() + "." + (paper.Reviewer.Patronym != null ? paper.Reviewer.Patronym.FirstOrDefault() + "." : string.Empty) + " " + paper.Reviewer.Lastname;
                    end.ReplaceText("@ReviewerSignature@", reviewerPartName, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    document.InsertDocument(end);
                    end.Dispose();
                }
                else
                {
                    DocX add = DocX.Load(ConvertHtmlToDocx("<html>" + paper.Review + "</html>"));
                    document.InsertDocument(add);
                    add.Dispose();
                    DocX end = DocX.Load(HttpContext.Current.Server.MapPath("~/App_Data/request_template_ending.docx"));
                    end.ReplaceText("@JobPosition@", paper.Reviewer.JobTitle, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    string reviewerPartName = paper.Reviewer.Degree + " " + paper.Reviewer.Firstname.FirstOrDefault() + "." + (paper.Reviewer.Patronym != null ? paper.Reviewer.Patronym.FirstOrDefault() + "." : string.Empty) + " " + paper.Reviewer.Lastname;
                    end.ReplaceText("@ReviewerSignature@", reviewerPartName, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    document.InsertDocument(end);
                    end.Dispose();
                }
                document.SaveAs(path);
                return path;
                //using (var stream = new MemoryStream())
                //{
                //    // Save changes made to this document
                //    document.SaveAs(stream);
                //    return stream.ToArray();
                //}
            }
        }
 public static string SerializeModel(PaperSubmissionModel paper)
 {
     XmlSerializer serializer = new XmlSerializer(typeof(PaperSubmissionModel));
     using (MemoryStream stream = new MemoryStream())
     {
         serializer.Serialize(stream, paper);
         return System.Text.Encoding.Default.GetString(stream.ToArray());
     }
 }