protected void btnSubmit_Click(object sender, EventArgs e) { DataTable dbUse = objConnect.GetTableWithCommandText("select ADMIN_ID from tblAdministrators WHERE USERNAME='******'"); if (dbUse.Rows.Count > 0) { string rollID = dbUse.Rows[0]["ADMIN_ID"].ToString(); bool ktHoiDap = objConnect.ExcutedCMD("update tblHoiDap set ANSWER=N'" + txtContent.Text + "', ADMIN_ANSWER='" + Session["username"].ToString() + "', STATUS=1 where ID=" + id); DataTable db = objConnect.GetTableWithCommandText("select * from tblEmailTemplate where EMAILID=2"); string content = db.Rows[0]["CONTENT"].ToString(); string title = db.Rows[0]["DESCRIPTION"].ToString(); string email = txtEmail.Text.Trim(); content = content.Replace("$1", name); content = content.Replace("$2", txtContent.Text); bool kt = objMail.SendMail(email, title, content); //bool kt = objMail.SendMail(email, title, content); if (kt == true) { objAsk.UpdateStatus(id); string str = "<script type='text/javascript'>"; str += "function OnRemove(){self.parent.tb_remove();}OnRemove();"; str += "</script>"; Response.Write(str); } } else { Response.Redirect("Login.aspx"); } }
public void sendMailApproval(DataTable dtReceiver, string htmlstringtable, string loi_status, string executorname, int requestid, string ApproverRole) { try { StringBuilder sbResult = new StringBuilder(); string emailsubject = string.Empty; string fullname = dtReceiver.Rows[0]["Name"].ToString(); string email = dtReceiver.Rows[0]["Email"].ToString(); string paramapproveinemail = string.Concat("true;", requestid.ToString(), ";", ApproverRole, ";", dtReceiver.Rows[0]["USR_ID"].ToString()); string paramrejectinemail = string.Concat("false;", requestid.ToString(), ";", ApproverRole, ";", dtReceiver.Rows[0]["USR_ID"].ToString()); paramapproveinemail = EnDecController.EncryptLinkUrlApproval(paramapproveinemail); paramrejectinemail = EnDecController.EncryptLinkUrlApproval(paramrejectinemail); DataTable dtEmail = loi_get_email_data(loi_status, requestid); DataTable dtDocumentAvailibility = loi_supportingdoc_getall(requestid); string HtmlTableSupportingDocAvailibility = CreateHtmlTableSupportingDocAvailibility(dtDocumentAvailibility); if (dtEmail.Rows.Count > 0) { emailsubject = dtEmail.Select("config_key like '%subject%'")[0].ItemArray[1].ToString(); string emailbody = dtEmail.Select("config_key like '%body%'")[0].ItemArray[1].ToString(); emailbody = emailbody.Replace("[name]", fullname).Replace("[sourcename]", executorname); emailbody = emailbody.Replace("[tabledetail]", htmlstringtable); emailbody = emailbody.Replace("[param approve]", paramapproveinemail); emailbody = emailbody.Replace("[param reject]", paramrejectinemail); emailbody = emailbody.Replace("[document_avilibility]", HtmlTableSupportingDocAvailibility); sbResult.Append(emailbody); MailController.SendMail(email, emailsubject, sbResult.ToString(), GeneralConfig.MailConfigType()); } } catch (Exception ex) { EBOQ_Lib_New.DAL.DAL_AppLog.ErrLogInsert("LOIController:SendEmail", ex.Message, "NON-SP"); } }
/// <summary> /// 点击事件进行发送邮件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSendMail_Click(object sender, RoutedEventArgs e) { if (Username.Text == "#author#@domain.com") { MessageBox.Show("请修改默认发件人"); } else { ConfigInfo configInfo = _configController.ConfigQuery("config/preferences", "../../../common/res/CIConfig.xml"); _projectInfo.WorkDirectory = Workspace.Text; _projectInfo = _svnController.GetLocalInfo(_projectInfo); _projectInfo.Nameproperty = projectName.Text; _projectInfo.Log = (configInfo.StandarOutput == "true") ? ((log + err).Replace("\n", "<br/>")) : (err.Replace("\n", "<br/>")); _projectInfo.Result = lastRe.Text; _projectInfo.Duration = duration; _projectInfo.Revision = revision; _projectInfo.MailTo = Mailto.Text; _projectInfo.MailHost = Host.Text; _projectInfo.UserName = Username.Text; _projectInfo.Password = Password.Text; MailController mailController = new MailController(); Dictionary <string, Dictionary <string, string> > allStatics = _projectController.GetStatData("config/Member", "../../../common/res/InfoStatics.xml"); MailInfo mailInfo = mailController.EditBody(_projectInfo, allStatics, "../../../common/SendMail.html"); sendRe.Text = mailController.SendMail(mailInfo); } }
/// <summary> /// 发送邮件 /// </summary> public void SendMail() { string shortName = ""; //修改发送邮件名字 ,改为简写 foreach (XmlNode people in _mailPeople) { if (projectInfo.Author == people.Attributes["Name"].Value) { shortName = people.InnerText; break; } } try { if (projectInfo.IfMail == "true") { MailInfo mailInfo = _mailController.EditBody(projectInfo, allStatics, mailPath, shortName); _mailController.SendMail(mailInfo); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
static void TestMail() { var mailController = new MailController(); var result = Task.Run(async() => await mailController.SendMail("*****@*****.**", "Test", "Hello World")); result.Wait(); }
public async Task SendMailException_ReturnsCorrectResponse() { logger = new LoggerManager(); var controller = new MailController(logger); Action act = () => controller.SendMail(new Recepients { }); Assert.Throws <NullReferenceException>(act); }
public void Post([FromBody] List <Models.ReportIncident> incidents) { var incidentTypes = this._db.IncidentTypes.Where(t => t.incidentReportTypeId == 1).ToList(); foreach (Models.ReportIncident incident in incidents) { this._db.ReportIncidents.Add(incident); this._db.SaveChanges(); var incidentType = incidentTypes.Where(t => t.incidentTypeId == incident.incidentTypeId).SingleOrDefault(); if (incidentType != null) { if (incidentType.incidentCategoryId == 1 || incidentType.incidentCategoryId == 2) // REPORTABLE TO JC { ReportsController reportsController = new ReportsController(); Models.Presentation.ReportsViewModel report = reportsController.GetReportHeader(incident.incidentId); reportsController.Dispose(); Controllers.MailController mailer = new MailController(); List <string> sendTos = new List <string>(); StringBuilder msg = new StringBuilder(); sendTos.Add("*****@*****.**"); Models.Notification notification = new Models.Notification(); notification.incidentId = incident.incidentId; notification.notifyPartyId = 37; notification.notifyDateTime = DateTime.Now; notification.notifyContact = "CFS Compliance"; notification.notifyMethod = "E-Mail"; notification.notifyStaffId = 0; notification.notifyComments = "Automatic E-Mail sent to compliance by incident report system."; notification.isAcknowledged = 1; notification.acknowledgeUserId = 0; this._db.Notifications.Add(notification); this._db.SaveChanges(); msg.Append("<h1>Incident Report: Compliance Notification</h1>"); msg.Append("<p>A new incident report for client " + report.clientName + " by " + report.staffName + " has been created and is being forwarded to compliance.</p>"); msg.Append("<p><a href=\"http://cfs-incidents/Admin/Review/" + report.incidentId.ToString() + "\">Click here to view the report.</a></p>"); //sendTos.Add(notifier.emailAddress); //sendTos.Add("*****@*****.**"); //MTS - commented out March '18 mailer.SendMail(sendTos, "*****@*****.**", "Incident Report Compliance Notification: " + report.clientName, System.Net.Mail.MailPriority.High, msg); } } } }
// POST api/<controller> public void Post([FromBody] Models.Notification notification) { if (notification.notificationId == 0) { this._db.Notifications.Add(notification); } else { this._db.Notifications.Attach(notification); this._db.Entry(notification).State = System.Data.Entity.EntityState.Modified; } this._db.SaveChanges(); if (notification.notifyPartyId == 8) // JUSTICE CENTER { ReportsController reportsController = new ReportsController(); Models.Presentation.ReportsViewModel report = reportsController.GetReportHeader(notification.incidentId); reportsController.Dispose(); Controllers.MailController mailer = new MailController(); List <string> sendTos = new List <string>(); StringBuilder msg = new StringBuilder(); sendTos.Add("*****@*****.**"); Models.Notification complianceNotification = new Models.Notification(); complianceNotification.incidentId = notification.incidentId; complianceNotification.notifyPartyId = 37; complianceNotification.notifyDateTime = DateTime.Now; complianceNotification.notifyContact = "CFS Compliance"; complianceNotification.notifyMethod = "E-Mail"; complianceNotification.notifyStaffId = 0; complianceNotification.notifyComments = "Automatic E-Mail sent to compliance by incident report system."; complianceNotification.isAcknowledged = 1; complianceNotification.acknowledgeUserId = 0; this._db.Notifications.Add(complianceNotification); this._db.SaveChanges(); msg.Append("<h1>Incident Report: Compliance Notification</h1>"); msg.Append("<p>A new incident report for client " + report.clientName + " by " + report.staffName + " has been created and is being forwarded to compliance.</p>"); msg.Append("<p><a href=\"http://cfs-incidents/admin/review/" + report.incidentId.ToString() + "\">Click here to view the report.</a></p>"); //sendTos.Add(notifier.emailAddress); //sendTos.Add("*****@*****.**"); //MTS - commented out March '18 mailer.SendMail(sendTos, "*****@*****.**", "Incident Report Compliance Notification: Justice Center Called", System.Net.Mail.MailPriority.High, msg); } }
public async Task SendMail_ReturnsCorrectResponse() { logger = new LoggerManager(); var controller = new MailController(logger); try { var result = controller.SendMail(new Recepients { recepientString = "[email protected],[email protected]", requestedGroups = "Group1,Group5" }); Assert.IsAssignableFrom <IActionResult>(result); } catch (Exception e) { Action act = () => controller.SendMail(new Recepients { recepientString = "[email protected],[email protected]", requestedGroups = "Group1,Group5" }); Assert.Throws <NullReferenceException>(act); } }
/// <summary> /// 发送邮件 /// </summary> public void SendMail() { try { if (projectInfo.IfMail == "true") { MailInfo mailInfo = _mailController.EditBody(projectInfo, allStatics, mailPath); _mailController.SendMail(mailInfo); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
protected void btnSubmit_Click(object sender, EventArgs e) { try { string createdby = Session["USERNAME"].ToString(); admin.InsertAdministrators(txtAdminName.Text, txtUserName.Text, txtPassWord.Text, txtAddress.Text, txtPhoneNumber.Text, txtEmail.Text, int.Parse(txtSortDisplay.Text), DateTime.Now, createdby, DateTime.Now, "", 1, ddlRoll.SelectedValue); divMessage.InnerHtml = O2S_Message.Success("Hệ thống", "Thực hiện thành công"); MailController controller = new MailController(); string body = "Tên đăng nhập:<br/>" + txtUserName.Text + "<br/>Mật khẩu:" + txtPassWord.Text; controller.SendMail(txtEmail.Text, "TÀI KHOẢN QUẢN TRỊ MONEYLOVE", body); } catch (Exception ex) { divMessage.InnerHtml = O2S_Message.Error("Hệ thống", "Phát hiện lỗi" + ex.Message); } }
public void sendMail(string fullname, string email, string htmlstringtable, string loi_status, string executorname, int requestid) { try { StringBuilder sbResult = new StringBuilder(); string emailsubject = string.Empty; DataTable dtEmail = loi_get_email_data(loi_status, requestid); if (dtEmail.Rows.Count > 0) { emailsubject = dtEmail.Select("config_key like '%subject%'")[0].ItemArray[1].ToString(); string emailbody = dtEmail.Select("config_key like '%body%'")[0].ItemArray[1].ToString(); emailbody = emailbody.Replace("[name]", fullname).Replace("[sourcename]", executorname); emailbody = emailbody.Replace("[tabledetail]", htmlstringtable); sbResult.Append(emailbody); MailController.SendMail(email, emailsubject, sbResult.ToString(), GeneralConfig.MailConfigType()); } } catch (Exception ex) { EBOQ_Lib_New.DAL.DAL_AppLog.ErrLogInsert("LOIController:SendEmail", ex.Message, "NON-SP"); } }
/// <summary> /// 发送邮件 /// </summary> public void SendMail() { string[] statisticsTimes = dataDao.DataSearch(projectInfo.Author); string shortName = ""; if (projectInfo.ProjectType == "git") { //修改发送邮件名字 ,改为简写 foreach (XmlNode people in _mailPeople) { if (projectInfo.Author == people.Attributes["Name"].Value) { shortName = people.InnerText; break; } } } //svn名字本来就是简写,不用转换 if (projectInfo.ProjectType == "svn") { shortName = projectInfo.Author; } try { if (projectInfo.IfMail == "true") { MailInfo mailInfo = _mailController.NewEditBody(projectInfo, statisticsTimes, mailPath, shortName); _mailController.SendMail(mailInfo); } } catch (Exception ex) { } }
public void sendMailResetPassword(string fullname, string email, string loi_status, string userlogin, string password) { try { StringBuilder sbResult = new StringBuilder(); string emailsubject = string.Empty; DataTable dtEmail = loi_get_email_data(loi_status, 0); if (dtEmail.Rows.Count > 0) { emailsubject = dtEmail.Select("config_key like '%subject%'")[0].ItemArray[1].ToString(); string emailbody = dtEmail.Select("config_key like '%body%'")[0].ItemArray[1].ToString(); emailbody = emailbody.Replace("[name]", fullname); emailbody = emailbody.Replace("[userlogin]", userlogin); emailbody = emailbody.Replace("[password]", password); sbResult.Append(emailbody); MailController.SendMail(email, emailsubject, sbResult.ToString(), GeneralConfig.MailConfigType()); } } catch (Exception ex) { EBOQ_Lib_New.DAL.DAL_AppLog.ErrLogInsert("LOIController:SendEmail", ex.Message, "NON-SP"); } }
public void PostAutoNotifiers([FromBody] Models.Presentation.ProgramNotifiersModel[] notifiers) { Controllers.MailController mailer = new MailController(); long incidentId = 0; incidentId = notifiers.FirstOrDefault().incidentId; ReportsController reportsController = new ReportsController(); Models.Presentation.ReportsViewModel report = reportsController.GetReportHeader(incidentId); reportsController.Dispose(); List <string> sendTos = new List <string>(); StringBuilder msg = new StringBuilder(); //sendTos.Add(notifier.emailAddress); sendTos.Add("*****@*****.**"); msg.Append("<h1>New Incident Report</h1>"); msg.Append("<p>A new incident report has been created for client " + report.clientName + " by " + report.staffName + ".</p>"); msg.Append("<p><a href=\"http://cfs-incidents/report/residential/" + report.incidentId.ToString() + "\">Click here to view the report.</a></p>"); msg.Append("<p><a href=\"http://cfs-incidents/Medicals\">Click here to create a medical review.</a></p>"); // COMMENT OUT BEFORE LIVE //msg.Append("<p>To be included:<br />"); foreach (var notifier in notifiers) { //msg.Append(notifier.emailAddress + "<br />"); sendTos.Add(notifier.emailAddress.ToLower().Trim()); Models.Notification notification = new Models.Notification(); notification.incidentId = incidentId; notification.notifyPartyId = notifier.notifyPartyId; notification.notifyDateTime = DateTime.Now; notification.notifyContact = notifier.staffName; notification.notifyMethod = "E-Mail"; notification.notifyStaffId = notifier.userId == null ? 0 : (long)notifier.userId; notification.notifyComments = "Automatic E-Mail sent to " + notifier.emailAddress.ToLower().Trim() + " by incident report system."; notification.isAcknowledged = 1; notification.acknowledgeUserId = notifier.userId == null ? 0 : (long)notifier.userId; this._db.Notifications.Add(notification); } this._db.SaveChanges(); // COMMENT OUT BEFORE LIVE //msg.Append("</p>"); // ADD REPORT DETAILS AND LINK TO REPORT // ACKNOWLEDGEMENT LINK msg.Append("<p><a href='/'></a></p>"); mailer.SendMail(sendTos, "*****@*****.**", "New Incident Report: " + report.clientName, System.Net.Mail.MailPriority.High, msg); mailer.Dispose(); }
public long Post([FromBody] Models.Medical medical) { if (medical.incidentMedicalId == 0) { this._db.Medicals.Add(medical); } else { this._db.Medicals.Attach(medical); this._db.Entry(medical).State = System.Data.Entity.EntityState.Modified; } try { this._db.SaveChanges(); } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Combine the original exception message with the new one. var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); MailController mailer = new MailController(); mailer.SendMail( new List <string>() { "*****@*****.**" }, "*****@*****.**", "ERROR CREATING MEDICAL ASSESSMENT: VALIDATION", System.Net.Mail.MailPriority.High, exceptionMessage ); string currentUser = RequestContext.Principal.Identity.Name; mailer.SendExceptionDetail("post:/api/medicals", exceptionMessage, ex.StackTrace, currentUser, medical); // Throw a new DbEntityValidationException with the improved exception message. throw new System.Data.Entity.Validation.DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); } catch (Exception ex) { string errorMessage = ex.Message; if (ex.InnerException != null) { errorMessage += " Inner Exception: " + ex.InnerException; } MailController mailer = new MailController(); mailer.SendMail( new List <string>() { "*****@*****.**" }, "*****@*****.**", "ERROR CREATING MEDICAL ASSESSMENT", System.Net.Mail.MailPriority.High, errorMessage ); string currentUser = RequestContext.Principal.Identity.Name; mailer.SendExceptionDetail("post:/api/medicals", errorMessage, ex.StackTrace, currentUser, medical); throw new Exception(errorMessage); } return(medical.incidentMedicalId); }
public void FinalApprove([FromBody] Models.Presentation.ReportSignatureModel signatureInfo) { Models.IncidentReport report = this._db.IncidentReports.Where(r => r.incidentId == signatureInfo.incidentId).SingleOrDefault(); if (report != null) { string userName = System.Web.HttpContext.Current.User.Identity.Name.Substring(5).ToLower(); if (userName.ToLower() != signatureInfo.userName.ToLower()) { throw new Exception("Current user information is not synchronized. Cannot approve report."); } SessionController session = new SessionController(); bool userVerified = session.VerifyPassword(userName, signatureInfo.signature); session.Dispose(); if (userVerified) { Models.ReportSign staffSignature = new Models.ReportSign(); staffSignature.incidentId = signatureInfo.incidentId; staffSignature.incidentMedicalId = 0; staffSignature.reportSigType = "E"; staffSignature.reportSigUserId = signatureInfo.currentUser; staffSignature.staffName = signatureInfo.staffName; staffSignature.staffTitle = signatureInfo.staffTitle; staffSignature.approvalStatusId = 3; staffSignature.reportSigStamp = DateTime.Now; staffSignature.reportSigStation = signatureInfo.stationName; this._db.ReportSigns.Add(staffSignature); StaffController staffs = new StaffController(); Models.User supervisor = staffs.GetStaffSupervisor(signatureInfo.currentUser); staffs.Dispose(); Models.ReportSign supervisorSignature = new Models.ReportSign(); supervisorSignature.incidentId = signatureInfo.incidentId; supervisorSignature.incidentMedicalId = 0; supervisorSignature.reportSigType = "S"; supervisorSignature.reportSigUserId = supervisor.userId; supervisorSignature.staffName = supervisor.firstName + " " + supervisor.lastName; supervisorSignature.staffTitle = supervisor.jobTitle; supervisorSignature.approvalStatusId = 1; this._db.ReportSigns.Add(supervisorSignature); // WRITE CHANGES TO LOG Models.ReportLog log = new Models.ReportLog(); log.incidentId = signatureInfo.incidentId; log.userId = signatureInfo.currentUser; log.userStation = signatureInfo.stationName; log.logDateTime = DateTime.Now; log.logDetails = "Report signed by staff."; this._db.ReportLogs.Add(log); // EMAIL SUPERVISOR!!!! (INCLUDE ADMINS?) MailController mailer = new MailController(); StringBuilder messageBody = new StringBuilder(); messageBody.Append("<p>A new incident report for <b>" + report.clientName + "</b> has been posted by " + report.staffName + ".</p>"); messageBody.Append("<p><a href=\"http://cfs-incidents/report/residential/" + report.incidentId.ToString() + "\">Click here to view the report.</a></p>"); mailer.SendMail( new List <string>() { supervisor.eMail, "*****@*****.**" }, "*****@*****.**", "Incident Report Posted", System.Net.Mail.MailPriority.High, messageBody ); mailer.Dispose(); report.statusId = signatureInfo.statusId; report.currentUser = signatureInfo.currentUser; report.lastModified = DateTime.Now; report.lastModifiedBy = signatureInfo.currentUser; this._db.IncidentReports.Attach(report); this._db.Entry(report).State = System.Data.Entity.EntityState.Modified; this._db.SaveChanges(); } else { throw new Exception("Unable to validate signature. Please use your current CFS account password to sign."); } } }
protected void btnSend_Click(object sender, EventArgs e) { string fullname = txtFullName.Text.Trim(); string email = txtEmail.Text.Trim(); string phone = txtPhoneNumber.Text.Trim(); string address = txtDiaChi.Text; string content = txtNoiDung.Value.Trim(); int _customerID = 0; //kiểm tra xem email đã tồn tài trong hệ thống hay chưa DataTable dbCheckEmail = objCus.GetDataByEmail(email); if (dbCheckEmail.Rows.Count > 0) { _customerID = Convert.ToInt32(dbCheckEmail.Rows[0]["ID"].ToString()); } else { _customerID = objCus.Insert(fullname, email, phone, DateTime.Now, 0, address, "", DateTime.Now, 0); } if (_customerID > 0) { if (txtCapcha.Text.Trim().ToLower().Equals(Session["Capcha"].ToString().ToLower())) { int a = objLienHe.Insert(_customerID, content, DateTime.Now, 0); if (a > 0) { string rec = ""; DataTable dtRec = cnts.GetTableWithCommandText("select * from tblMailReceiver where STATUS = 1"); if (dtRec.Rows.Count > 0) { foreach (DataRow dr in dtRec.Rows) { rec += dr["EMAIL"].ToString() + ";"; } } else { rec = "[email protected];"; } DataTable db = cnts.GetTableWithCommandText("select * from tblEmailTemplate where EMAILID=1"); string contentSend = db.Rows[0]["CONTENT"].ToString(); contentSend = contentSend.Replace("$1", fullname); contentSend = contentSend.Replace("$2", email); contentSend = contentSend.Replace("$3", phone); contentSend = contentSend.Replace("$4", content); string[] _listEmail = rec.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < _listEmail.Length; i++) { objMail.SendMail(_listEmail[i], db.Rows[0]["DESCRIPTION"].ToString(), contentSend); } string str = "<script type='text/javascript'>"; str += "function OnRemove(){alert('Cảm ơn bạn đã đặt câu hỏi. Chúng tôi sẽ trả lời trong vòng 3 ngày làm việc!');self.parent.tb_remove();}OnRemove();"; str += "</script>"; Response.Write(str); } } else { labCaptcha.Text = "Nhập sai mã."; imgCapcha.ImageUrl = "../capcha.aspx"; } } else { string str = "<script type='text/javascript'>"; str += "function OnRemove(){self.parent.tb_remove();}OnRemove();"; str += "</script>"; Response.Write(str); } }
public void SupervisorFinalApprove([FromBody] Models.Presentation.ReportSignatureModel signatureInfo) { Models.IncidentReport report = this._db.IncidentReports.Where(r => r.incidentId == signatureInfo.incidentId).SingleOrDefault(); string logDetails = string.Empty; if (report != null) { string userName = System.Web.HttpContext.Current.User.Identity.Name.Substring(5).ToLower(); if (userName.ToLower() != signatureInfo.userName.ToLower()) { throw new Exception("Current user information is not synchronized. Cannot approve report."); } SessionController session = new SessionController(); bool userVerified = session.VerifyPassword(userName, signatureInfo.signature); session.Dispose(); if (userVerified) { // GET SUPERVISOR SIGNATURE RECORD Models.ReportSign supervisorSignature = this._db.ReportSigns.Where( s => s.incidentId == signatureInfo.incidentId && s.reportSigType == "S" && s.reportSigUserId == signatureInfo.currentUser).SingleOrDefault(); if (supervisorSignature == null) { throw new Exception("Could not find signature record. Cannot approve report."); } else { supervisorSignature.approvalStatusId = signatureInfo.approvalStatusId; supervisorSignature.reportSigStamp = DateTime.Now; supervisorSignature.reportSigStation = signatureInfo.stationName; supervisorSignature.approvalComments = signatureInfo.approvalComments; this._db.ReportSigns.Attach(supervisorSignature); this._db.Entry(supervisorSignature).State = System.Data.Entity.EntityState.Modified; if (signatureInfo.approvalStatusId == 3) // SUPERVISOR APPROVED { // SUPERVISOR APPROVES, REPORT SENT TO ADMINS FOR REVIEW Models.ReportSign adminSignature = new Models.ReportSign(); adminSignature.incidentId = signatureInfo.incidentId; adminSignature.incidentMedicalId = 0; adminSignature.reportSigType = "A"; adminSignature.reportSigUserId = 0; adminSignature.staffName = "Administrator"; adminSignature.staffTitle = "Administrator"; adminSignature.approvalStatusId = 1; this._db.ReportSigns.Add(adminSignature); // EMAIL ADMINS!!!! (INCLUDE ADMINS?) logDetails = "Supervisor approved report."; } else { // NOTIFY EMPLOYEE REPORT REJECTED logDetails = "Supervisor rejected report. Comments: " + signatureInfo.approvalComments; } // if (signatureInfo.approvalStatusId == 3) // UPDATE REPORT STATUS report.statusId = signatureInfo.statusId; report.currentUser = signatureInfo.currentUser; report.lastModified = DateTime.Now; report.lastModifiedBy = signatureInfo.currentUser; this._db.IncidentReports.Attach(report); this._db.Entry(report).State = System.Data.Entity.EntityState.Modified; // WRITE CHANGES TO LOG Models.ReportLog log = new Models.ReportLog(); log.incidentId = signatureInfo.incidentId; log.userId = signatureInfo.currentUser; log.userStation = signatureInfo.stationName; log.logDateTime = DateTime.Now; log.logDetails = logDetails; this._db.ReportLogs.Add(log); // IF JUSTICE CENTER CALLED, NOTIFY CORPORATE COMPLIANCE // notifyPartyId = 8 (Justice Center) bool jcCalled = this._db.Notifications.Where(n => n.incidentId == signatureInfo.incidentId && n.notifyPartyId == 8).Any(); if (jcCalled) { Models.Notification ccNotification = new Models.Notification(); ccNotification.incidentId = signatureInfo.incidentId; ccNotification.notifyPartyId = 37; // Corporate Compliance ccNotification.notifyDateTime = DateTime.Now; ccNotification.notifyContact = "CFS Corporate Compliance"; ccNotification.notifyMethod = "E-Mail"; ccNotification.notifyStaffId = 0; ccNotification.isAcknowledged = 1; ccNotification.acknowledgeUserId = 0; this._db.Notifications.Add(ccNotification); MailController mailer = new MailController(); List <string> sendTos = new List <string>(); sendTos.Add("*****@*****.**"); StringBuilder msg = new StringBuilder(); msg.Append("<h1>Incident Report Notification</h1>"); msg.Append("<p>An incident report has been created for client " + report.clientName + " by " + report.staffName); msg.Append(", and the Justice Center was called.</p>"); mailer.SendMail(sendTos, "*****@*****.**", "Incident Reports: Justice Center Called", System.Net.Mail.MailPriority.Normal, msg); } this._db.SaveChanges(); } // if (supervisorSignature == null) } else { throw new Exception("Unable to validate signature. Please use your current CFS account password to sign."); } // if (userVerified) } }
public long Post([FromBody] Models.IncidentReport report) { if (report.userId == 0) { SessionController session = new SessionController(); var user = session.Get(); report.userId = user.userId; report.createdStation = user.stationInfo; report.currentUser = user.userId; session.Dispose(); } if (report.incidentId == 0) { // CREATE REPORT this._db.IncidentReports.Add(report); } else { this._db.IncidentReports.Attach(report); this._db.Entry(report).State = System.Data.Entity.EntityState.Modified; } try { this._db.SaveChanges(); // WRITE TO REPORT LOG Models.ReportLog log = new Models.ReportLog(); log.incidentId = report.incidentId; log.userId = report.userId; log.userStation = report.createdStation; log.logDateTime = DateTime.Now; log.logDetails = "Report created."; LogController logController = new LogController(); logController.Post(log); logController.Dispose(); // NOTIFY MailController mailer = new MailController(); StringBuilder messageBody = new StringBuilder(); messageBody.Append("<p>A new incident report for <b>" + report.clientName + "</b> has been created by " + report.staffName + ".</p>"); messageBody.Append("<p><a href=\"http://cfs-incidents/report/residential/" + report.incidentId.ToString() + "\">Click here to view the report.</a></p>"); if (report.incidentReportTypeId == 1) { mailer.SendMail( new List <string>() { "*****@*****.**" }, "*****@*****.**", "New Incident Report", System.Net.Mail.MailPriority.High, messageBody ); } else { mailer.SendMail( new List <string>() { "*****@*****.**" }, "*****@*****.**", "New Incident Report", System.Net.Mail.MailPriority.High, messageBody ); } mailer.Dispose(); return(report.incidentId); } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Combine the original exception message with the new one. var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); MailController mailer = new MailController(); mailer.SendMail( new List <string>() { "*****@*****.**" }, "*****@*****.**", "ERROR CREATING INCIDENT: VALIDATION", System.Net.Mail.MailPriority.High, exceptionMessage ); string currentUser = RequestContext.Principal.Identity.Name; mailer.SendExceptionDetail("post:/api/reports", exceptionMessage, ex.StackTrace, currentUser, report); // Throw a new DbEntityValidationException with the improved exception message. throw new System.Data.Entity.Validation.DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); } catch (Exception ex) { string errorMessage = ex.Message; if (ex.InnerException != null) { errorMessage += " Inner Exception: " + ex.InnerException; } MailController mailer = new MailController(); mailer.SendMail( new List <string>() { "*****@*****.**" }, "*****@*****.**", "ERROR CREATING INCIDENT", System.Net.Mail.MailPriority.High, errorMessage ); string currentUser = RequestContext.Principal.Identity.Name; mailer.SendExceptionDetail("post:/api/reports", errorMessage, ex.StackTrace, currentUser, report); throw new Exception(errorMessage); } }