protected void btnTaskAssignUpdate_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;

            if (btn == null || string.IsNullOrEmpty(btn.CommandArgument))
            {
                return;
            }

            if (ddlAssignPerson.SelectedItem != null)
            {
                TaskStatusMgr taskMgr = new TaskStatusMgr().CreateNew(0, 0);
                TASK_STATUS   task    = taskMgr.SelectTask(Convert.ToDecimal(btn.CommandArgument));
                task.COMMENTS       = tbAssignComment.Text;
                task.STATUS         = ((int)TaskStatus.New).ToString();
                task.RESPONSIBLE_ID = Convert.ToDecimal(ddlAssignPerson.SelectedValue);
                taskMgr.UpdateTask(task);
                // send email
                EHSNotificationMgr.NotifyTaskAssigment(task, 0);
            }

            if (OnTaskUpdate != null)
            {
                OnTaskUpdate("update");
            }
        }
        public int AddUpdateINCFORM_ALERT(decimal incidentId)
        {
            lblStatusMsg.Visible = false;
            int  status            = 0;
            bool allFieldsComplete = true;

            localCtx = new PSsqmEntities();

            INCFORM_ALERT incidentAlert = EHSIncidentMgr.LookupIncidentAlert(localCtx, IncidentId);

            if (incidentAlert == null)  // new alert
            {
                incidentAlert             = new INCFORM_ALERT();
                incidentAlert.INCIDENT_ID = LocalIncident.INCIDENT_ID;
                incidentAlert.ALERT_TYPE  = ((int)TaskRecordType.HealthSafetyIncident).ToString();
                incidentAlert.CREATE_DT   = DateTime.UtcNow;
                incidentAlert.CREATE_BY   = SessionManager.UserContext.UserName();
                localCtx.AddToINCFORM_ALERT(incidentAlert);
                lblAlertStatus.Text = XLATList.Where(l => l.XLAT_GROUP == "TASK_STATUS" && l.XLAT_CODE == "0").FirstOrDefault().DESCRIPTION;
            }
            SaveAttachments(incidentId);
            incidentAlert.LOCATION_LIST = "";
            foreach (RadComboBoxItem item in ddlLocations.Items.Where(i => i.Checked == true && i.Value.Contains("BU") == false).ToList())
            {
                incidentAlert.LOCATION_LIST += string.IsNullOrEmpty(incidentAlert.LOCATION_LIST) ? item.Value : (item.Value + ",");
            }

            incidentAlert.ALERT_GROUP = "";
            foreach (RadComboBoxItem item in ddlNotifyGroup.Items.Where(i => i.Checked == true).ToList())
            {
                incidentAlert.ALERT_GROUP += string.IsNullOrEmpty(incidentAlert.ALERT_GROUP) ? item.Value : (item.Value + ",");
            }

            incidentAlert.RESPONSIBLE_GROUP = ddlResponsibleGroup.SelectedValue;
            //  incidentAlert.ALERT_DESC = tbAlertDesc.Text;
            incidentAlert.COMMENTS = tbComments.Text;
            incidentAlert.DUE_DT   = rdpDueDate.SelectedDate;



            // Update CEO-Comments value.
            incidentAlert.CEO_COMMENTS = tbCeoComments.Text.Trim();

            // send general notifications
            if (incidentAlert.INCIDENT_ALERT_ID < 1)
            {
                EHSNotificationMgr.NotifyIncidentAlert(LocalIncident, ((int)SysPriv.notify).ToString(), "380",
                                                       ddlLocations.Items.Where(i => i.Checked == true && i.Value.Contains("BU") == false).Select(i => Convert.ToDecimal(i.Value)).ToList());
            }

            List <TASK_STATUS> alertTaskList = UpdateAlertTaskList(EHSIncidentMgr.GetAlertTaskList(localCtx, LocalIncident.INCIDENT_ID));

            status = localCtx.SaveChanges();

            // send specific task assignments
            EHSNotificationMgr.NotifyIncidentAlertTaskAssignment(LocalIncident, alertTaskList.Where(l => l.RESPONSIBLE_ID.HasValue).ToList());

            return(status);
        }
        private int SaveActions(decimal incidentId, List <TASK_STATUS> actionList)
        {
            PSsqmEntities entities = new PSsqmEntities();
            int           status   = 0;

            foreach (TASK_STATUS action in actionList)
            {
                if (!string.IsNullOrEmpty(action.DESCRIPTION) && action.DUE_DT.HasValue && action.RESPONSIBLE_ID.HasValue)
                {
                    EHSIncidentMgr.CreateOrUpdateTask(ActionIncident, action, WebSiteCommon.LocalTime(DateTime.UtcNow, IncidentLocationTZ));
                }
            }

            if (status > -1)
            {
                EHSNotificationMgr.NotifyIncidentStatus(ActionIncident, ((int)SysPriv.update).ToString(), "Corrective action specified");
            }

            EHSIncidentMgr.UpdateIncidentStatus(incidentId, IncidentStepStatus.correctiveaction, WebSiteCommon.LocalTime(DateTime.UtcNow, IncidentLocationTZ));

            return(status);
        }
示例#4
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            var verifications = new List <INCIDENT_VERIFICATION>();

            if (tbInstructions.Text.Trim().Length == 0 || !rdpDueDate.SelectedDate.HasValue)
            {
                lblRequired.Visible = true;
                return;
            }
            lblRequired.Visible = false;

            PSsqmEntities entities = new PSsqmEntities();

            if (IsEditContext == true)
            {
                if (IncidentId != null)
                {
                    // Update description, date
                    INCIDENT incident = (from i in entities.INCIDENT where i.INCIDENT_ID == IncidentId select i).FirstOrDefault();
                    incident.DESCRIPTION = tbInstructions.Text;
                    if (rdpDueDate.SelectedDate.HasValue)
                    {
                        incident.INCIDENT_DT = (DateTime)rdpDueDate.SelectedDate;
                    }
                    if (!string.IsNullOrEmpty(rcbCases.SelectedValue))
                    {
                        incident.VERIFY_PROBCASE_ID = Convert.ToDecimal(rcbCases.SelectedValue);
                    }
                    entities.SaveChanges();

                    // Add notified people and plants to database
                    foreach (GridViewRow gvr in gvPreventLocationsList.Rows)
                    {
                        decimal plantId = (decimal)gvPreventLocationsList.DataKeys[gvr.RowIndex].Value;

                        if (plantId != null)
                        {
                            RadGrid currentGridView = (RadGrid)gvr.FindControl("rgPlantContacts");
                            foreach (GridDataItem item in currentGridView.Items)
                            {
                                decimal personId = (decimal)item.GetDataKeyValue("PERSON_ID");
                                if (personId != null)
                                {
                                    var incidentVerification = (from iv in entities.INCIDENT_VERIFICATION
                                                                where iv.INCIDENT_ID == IncidentId &&
                                                                iv.PLANT_ID == plantId &&
                                                                iv.PERSON_ID == personId
                                                                select iv).FirstOrDefault();

                                    if (item.Selected == true)
                                    {
                                        var newVerification = new INCIDENT_VERIFICATION()
                                        {
                                            INCIDENT_ID   = IncidentId,
                                            PLANT_ID      = plantId,
                                            PERSON_ID     = personId,
                                            DATE_NOTIFIED = DateTime.Now
                                        };
                                        // Add to list to use for emails
                                        verifications.Add(newVerification);

                                        // Add to database if it does not exist
                                        if (incidentVerification == null)
                                        {
                                            entities.INCIDENT_VERIFICATION.AddObject(newVerification);
                                            entities.SaveChanges();
                                        }
                                    }
                                    else
                                    {
                                        // Delete if exists
                                        if (incidentVerification != null)
                                        {
                                            entities.INCIDENT_VERIFICATION.DeleteObject(incidentVerification);
                                            entities.SaveChanges();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else             // Is add context
            {
                decimal verifyProbcaseId = 0;
                if (!string.IsNullOrEmpty(rcbCases.SelectedValue))
                {
                    verifyProbcaseId = Convert.ToDecimal(rcbCases.SelectedValue);
                }

                // Add incident to database
                var incident = new INCIDENT()
                {
                    DETECT_COMPANY_ID  = SessionManager.UserContext.WorkingLocation.Company.COMPANY_ID,
                    DETECT_BUS_ORG_ID  = SessionManager.UserContext.WorkingLocation.BusinessOrg.BUS_ORG_ID,
                    DETECT_PLANT_ID    = SessionManager.UserContext.WorkingLocation.Plant.PLANT_ID,
                    INCIDENT_TYPE      = "EHS",
                    CREATE_DT          = DateTime.Now,
                    CREATE_BY          = SessionManager.UserContext.Person.FIRST_NAME + " " + SessionManager.UserContext.Person.LAST_NAME,
                    DESCRIPTION        = tbInstructions.Text,
                    CREATE_PERSON      = SessionManager.UserContext.Person.PERSON_ID,
                    INCIDENT_DT        = rdpDueDate.SelectedDate.Value,
                    ISSUE_TYPE         = "Prevention Verification",
                    ISSUE_TYPE_ID      = 10,
                    VERIFY_PROBCASE_ID = verifyProbcaseId
                };
                entities.INCIDENT.AddObject(incident);
                entities.SaveChanges();
                decimal incidentId = incident.INCIDENT_ID;


                // Add notified people and plants to database
                foreach (GridViewRow gvr in gvPreventLocationsList.Rows)
                {
                    decimal plantId = (decimal)gvPreventLocationsList.DataKeys[gvr.RowIndex].Value;

                    if (plantId != null)
                    {
                        RadGrid currentGridView = (RadGrid)gvr.FindControl("rgPlantContacts");
                        foreach (GridDataItem item in currentGridView.Items)
                        {
                            decimal personId = (decimal)item.GetDataKeyValue("PERSON_ID");
                            if (personId != null)
                            {
                                if (item.Selected == true)
                                {
                                    var incidentVerification = new INCIDENT_VERIFICATION()
                                    {
                                        INCIDENT_ID   = incidentId,
                                        PLANT_ID      = plantId,
                                        PERSON_ID     = personId,
                                        DATE_NOTIFIED = DateTime.Now
                                    };
                                    verifications.Add(incidentVerification);
                                    entities.INCIDENT_VERIFICATION.AddObject(incidentVerification);
                                    entities.SaveChanges();
                                }
                            }
                        }
                    }
                }
            }

            // Send email(s)

            List <SETTINGS> mailSettings = SQMSettings.SelectSettingsGroup("MAIL", "");

            foreach (var v in verifications)
            {
                var    thisVerification = v;
                PERSON emailPerson      = (from p in entities.PERSON where p.PERSON_ID == thisVerification.PERSON_ID select p).FirstOrDefault();

                string emailSubject = SessionManager.PrimaryCompany().COMPANY_NAME + " Issue Acknowledgement Notification";                 // AW20140129 - use company name variable instead of hard coding.

                string path = "http://" + HttpContext.Current.Request.Url.Authority + "/EHS/EHS_Incident_Verification.aspx";

                path += string.Format("?inid={0}&plid={1}&peid={2}", v.INCIDENT_ID, v.PLANT_ID, emailPerson.PERSON_ID);
                var sb = new StringBuilder();
                sb.AppendLine("<p>You have been sent an issue acknowledgement notification from " + SessionManager.PrimaryCompany().COMPANY_NAME + ".</p>");
                sb.AppendLine();
                sb.AppendLine("<p><b>DETAILS</b></p>");
                sb.AppendLine();
                sb.AppendLine("<p>Date: " + rdpDueDate.SelectedDate.Value.ToShortDateString() + "</p>");
                sb.AppendLine();
                sb.AppendLine("<p>Instructions: " + tbInstructions.Text + "</p>");
                sb.AppendLine();
                sb.AppendLine("<p>Please go here to acknowledge receipt of this issue:<br/>");
                sb.AppendLine("<a href=\"" + path + "\">" + path + "</a></p>");
                sb.AppendLine();                                      // AW20140129
                sb.AppendLine();                                      // AW20140129
                sb.AppendLine("Please Do Not Reply To This Message"); // AW20140129

                string emailBody    = sb.ToString();
                string emailAddress = emailPerson.EMAIL;
                string rtn          = "";        // WebSiteCommon.SendEmail(emailAddress, emailSubject, emailBody, "");
                Thread thread       = new Thread(() => WebSiteCommon.SendEmail(emailAddress, emailSubject, emailBody, "", "", null, mailSettings));
                thread.IsBackground = true;
                thread.Start();
                EHSNotificationMgr.WriteEmailLog(entities, emailAddress, mailSettings.Find(x => x.SETTING_CD == "MailFrom").VALUE, emailSubject, emailBody, (int)TaskRecordType.HealthSafetyIncident, v.INCIDENT_ID, "prevention notification verification", rtn, "");
            }

            Response.Redirect("EHS_Incidents.aspx");
        }
示例#5
0
        public int AddUpdateINCFORM_APPROVAL(decimal incidentId, string option)
        {
            //To get approvertype from usercontext. -NIHARIKA SAXENA
            var approveerType = (SessionManager.UserContext.PrivList.Where(p => p.PRIV <= 100).FirstOrDefault()).PRIV_GROUP.ToString();
            //Check status of severityLevel of Global Safety Group
            bool severityLevel = false;

            var  itemList      = new List <INCFORM_APPROVAL>();
            int  status        = 0;
            int  numRequired   = 0;
            int  requiredCount = 0;
            int  approvalCount = 0;
            bool isRequired;
            bool isChanged = false;



            List <INCFORM_APPROVAL> approvalList = new List <INCFORM_APPROVAL>();

            using (PSsqmEntities ctx = new PSsqmEntities())
            {
                foreach (RepeaterItem item in rptApprovals.Items)
                {
                    isRequired = false;
                    HiddenField hfreq = (HiddenField)item.FindControl("hfReqdComplete");
                    if (hfreq.Value.ToLower() == "true")
                    {
                        ++numRequired;
                        isRequired = true;
                    }

                    INCFORM_APPROVAL approval = new INCFORM_APPROVAL();
                    approval.INCIDENT_ID    = incidentId;
                    approval.APPROVAL_LEVEL = 0;
                    approval.STEP           = ApprovalStep.STEP;
                    Label         lba    = (Label)item.FindControl("lbApprover");
                    Label         lb     = (Label)item.FindControl("lbItemSeq");
                    CheckBox      cba    = (CheckBox)item.FindControl("cbIsAccepted");
                    RadDatePicker rda    = (RadDatePicker)item.FindControl("rdpAcceptDate");
                    HiddenField   hfrole = (HiddenField)item.FindControl("hfRoleDesc");
                    HiddenField   hf     = (HiddenField)item.FindControl("hfItemSeq");
                    HiddenField   hfINCFORM_APPROVER_LIST_ID = (HiddenField)item.FindControl("hfINCFORM_APPROVER_LIST_ID");
                    approval.ITEM_SEQ       = Convert.ToInt32(hf.Value);
                    approval.APPROVER_TITLE = hfrole.Value;
                    if (IncidentId > MaxIncidentForNewFeature && ApprovalStep.STEP < 6)
                    {
                        approval.INCFORM_APPROVER_LIST_ID = Convert.ToDecimal(hfINCFORM_APPROVER_LIST_ID.Value);
                    }

                    //Update SEVERITY_LEVEL value. -
                    if (chkSeverityLevel00.Checked && chkSeverityLevel00.Visible == true)
                    {
                        severityLevel           = chkSeverityLevel00.Checked;
                        approval.SEVERITY_LEVEL = SysPriv.first_add.ToString();
                    }
                    else if (chkSeverityLevel01.Checked && chkSeverityLevel01.Visible == true)
                    {
                        severityLevel           = chkSeverityLevel01.Checked;
                        approval.SEVERITY_LEVEL = SysPriv.l1.ToString();
                    }

                    else if (chkSeverityLevel02.Checked && chkSeverityLevel02.Visible == true)
                    {
                        severityLevel           = chkSeverityLevel02.Checked;
                        approval.SEVERITY_LEVEL = SysPriv.l2.ToString();
                    }
                    else if (chkSeverityLevel03.Checked && chkSeverityLevel03.Visible == true)
                    {
                        severityLevel           = chkSeverityLevel03.Checked;
                        approval.SEVERITY_LEVEL = SysPriv.l3.ToString();
                    }
                    else if (chkSeverityLevel04.Checked && chkSeverityLevel04.Visible == true)
                    {
                        severityLevel           = chkSeverityLevel04.Checked;
                        approval.SEVERITY_LEVEL = SysPriv.l4.ToString();
                    }

                    approvalList.Add(approval);

                    if (cba.Checked == true)    // is approved
                    {
                        ++approvalCount;

                        if (isRequired)
                        {
                            ++requiredCount;
                        }

                        hf = (HiddenField)item.FindControl("hfApprovalID");
                        if (string.IsNullOrEmpty(hf.Value) || hf.Value == "0")
                        {
                            // save new approval to db
                            isChanged = true;
                            approval.APPROVAL_DATE = rda.SelectedDate;
                            approval.IsAccepted    = true;
                            hf = (HiddenField)item.FindControl("hfPersonID");
                            if (string.IsNullOrEmpty(hf.Value) || hf.Value == "0")
                            {
                                approval.APPROVER_PERSON_ID = SessionManager.UserContext.Person.PERSON_ID;
                                approval.APPROVER_PERSON    = SessionManager.UserContext.UserName();
                            }
                            else
                            {
                                approval.APPROVER_PERSON_ID = Convert.ToDecimal(hf.Value);
                                approval.APPROVER_PERSON    = lba.Text;
                            }

                            ctx.AddToINCFORM_APPROVAL(approval);
                        }
                    }
                }

                if (approveerType == "Global Safety Group")
                {
                    if (severityLevel)
                    {
                        lblResponseMsg.Text        = "";
                        chkSeverityLevel00.Enabled = false;

                        chkSeverityLevel01.Enabled = false;

                        chkSeverityLevel02.Enabled = false;

                        chkSeverityLevel03.Enabled = false;

                        chkSeverityLevel04.Enabled = false;

                        //status = ctx.ExecuteStoreCommand("DELETE FROM INCFORM_APPROVAL WHERE INCIDENT_ID = " + incidentId.ToString() + " AND STEP = " + ApprovalStep.ToString());
                        status = ctx.SaveChanges();
                    }
                    else
                    {
                        status = -1;
                    }
                }
                else
                {
                    status = ctx.SaveChanges();
                }

                bool   notifyStepComplete = false;
                string incidentStep       = "";

                // determine step status
                if (approvalCount > 0)
                {
                    if (ApprovalStep.STEP == 10.0m)
                    {
                        incidentStep = "Approvals";
                        IncidentStepStatus stat;
                        if ((numRequired > 0 && requiredCount == numRequired) || approvalCount == rptApprovals.Items.Count)
                        {
                            stat = (IncidentStepStatus)Math.Min(rptApprovals.Items.Count + 150, 155);
                            EHSIncidentMgr.UpdateIncidentStatus(incidentId, stat, true, WebSiteCommon.LocalTime(DateTime.UtcNow, IncidentLocationTZ));
                            notifyStepComplete = true;
                        }
                        else
                        {
                            incidentStep = ApprovalStep.STEP == 5.5m ? "CorrectiveActionApproval" : "InitialActionApproval";
                            stat         = (IncidentStepStatus)Math.Min(approvalCount + 150, 154);
                            EHSIncidentMgr.UpdateIncidentStatus(incidentId, stat, WebSiteCommon.LocalTime(DateTime.UtcNow, IncidentLocationTZ));
                        }
                    }
                    else
                    {
                        if ((numRequired > 0 && requiredCount == numRequired) || approvalCount == rptApprovals.Items.Count)
                        {
                            EHSIncidentMgr.UpdateIncidentApprovalStatus(incidentId, ApprovalStep.STEP);
                            notifyStepComplete = true;
                        }
                    }
                }

                // only send notifications when approvals are added
                if (isChanged)
                {
                    NotifyCycle notifyCycle;
                    try
                    {
                        notifyCycle = ApprovalStep.NOTIFY_CYCLE.HasValue ? (NotifyCycle)ApprovalStep.NOTIFY_CYCLE : NotifyCycle.None;
                    }
                    catch
                    {
                        notifyCycle = NotifyCycle.None;
                    }

                    if (notifyStepComplete && ApprovalStep.STEP == 10.0m)
                    {
                        EHSNotificationMgr.NotifyIncidentStatus(LocalIncident, ((int)SysPriv.approve).ToString(), "");
                    }

                    if (notifyCycle == NotifyCycle.notifyNext)
                    {
                        INCFORM_APPROVAL priorApproval = new INCFORM_APPROVAL();
                        foreach (INCFORM_APPROVAL approval in approvalList)
                        {
                            // notify missing approvers when prior roles approved or the step was completed by 380 or 390 priv
                            if (!approval.APPROVAL_DATE.HasValue && (priorApproval.APPROVAL_DATE.HasValue || notifyStepComplete))
                            {
                                List <string> infoList = new List <string>();
                                infoList.Add(approval.APPROVER_TITLE);
                                infoList.Add(priorApproval.APPROVER_TITLE);
                                EHSNotificationMgr.NotifyIncidentSignoffRequired(LocalIncident, approval, ApprovalStep.STEP_HEADING_TEXT, approval.ITEM_SEQ >= 390 ? "SIGNOFF" : "APPROVAL", infoList);
                            }
                            priorApproval = approval;
                        }
                    }
                }
            }
            if (IncidentId > MaxIncidentForNewFeature && ApprovalStep.STEP < 6)
            {
                bool isNotify = false;
                if (isChanged)
                {
                    using (PSsqmEntities ctx = new PSsqmEntities())
                    {
                        //foreach (RepeaterItem item in rptApprovals.Items)
                        //{
                        //    CheckBox cba = (CheckBox)item.FindControl("cbIsAccepted");
                        //    HiddenField hfINCFORM_APPROVER_LIST_ID = (HiddenField)item.FindControl("hfINCFORM_APPROVER_LIST_ID");
                        //    HiddenField hfAPPROVERType = (HiddenField)item.FindControl("hfAPPROVERType");
                        //    if (cba.Checked && (hfAPPROVERType.Value == "A" || hfAPPROVERType.Value == "N"))
                        //    {
                        //        isNotify = true;
                        //    }
                        //    else if (!cba.Checked && (hfAPPROVERType.Value == "A" || hfAPPROVERType.Value == "N"))
                        //    {
                        //        isNotify = false;
                        //        break;
                        //    }
                        //}
                        //if (isNotify)
                        //{

                        foreach (RepeaterItem item in rptApprovals.Items)
                        {
                            HiddenField   hfrole = (HiddenField)item.FindControl("hfRoleDesc");
                            CheckBox      cba    = (CheckBox)item.FindControl("cbIsAccepted");
                            HiddenField   hfINCFORM_APPROVER_LIST_ID = (HiddenField)item.FindControl("hfINCFORM_APPROVER_LIST_ID");
                            List <string> infoList = new List <string>();
                            infoList.Add(hfrole.Value);
                            decimal?applistid             = Convert.ToDecimal(hfINCFORM_APPROVER_LIST_ID.Value);
                            INCFORM_APPROVER_LIST appList = (from i in ctx.INCFORM_APPROVER_LIST where i.INCFORM_APPROVER_LIST_ID == applistid select i).FirstOrDefault();
                            PERSON person = (from i in ctx.PERSON where i.PERSON_ID == appList.PERSON_ID select i).FirstOrDefault();
                            if (!cba.Checked)
                            {
                                if (person != null)
                                {
                                    EHSNotificationMgr.NotifyApprover(LocalIncident, person.PERSON_ID, ApprovalStep.STEP_HEADING_TEXT, appList.PRIV >= 390 ? "SIGNOFF" : "APPROVAL", infoList);
                                }
                            }
                        }
                        //CheckBox cba = (CheckBox)item.FindControl("cbIsAccepted");
                        //HiddenField hfINCFORM_APPROVER_LIST_ID = (HiddenField)item.FindControl("hfINCFORM_APPROVER_LIST_ID");
                        //HiddenField hfAPPROVERType = (HiddenField)item.FindControl("hfAPPROVERType");
                        //if (!cba.Checked && (hfAPPROVERType.Value == "R"))
                        //{
                        //    decimal? applistid = Convert.ToDecimal(hfINCFORM_APPROVER_LIST_ID.Value);
                        //    INCFORM_APPROVER_LIST appList = (from i in ctx.INCFORM_APPROVER_LIST where i.INCFORM_APPROVER_LIST_ID == applistid select i).FirstOrDefault();
                        //    if (appList.PERSON_ID != null)
                        //    {
                        //        PERSON person = (from i in ctx.PERSON where i.PERSON_ID == appList.PERSON_ID select i).FirstOrDefault();
                        //        EHSNotificationMgr.NotifyRegionalApprover(person.PERSON_ID, "Notify Regional Approver");
                        //    }
                        //}

                        //}
                    }
                }
            }
            return(status);
        }
        protected void btnTaskUpdate_Click(object sender, EventArgs e)
        {
            PSsqmEntities ctx = new PSsqmEntities();

            lblErrorMessage.Text = "";
            Button btn = (Button)sender;

            if (btn == null || string.IsNullOrEmpty(btn.CommandArgument))
            {
                return;
            }

            TaskStatusMgr taskMgr = new TaskStatusMgr().CreateNew(0, 0);
            TASK_STATUS   task    = taskMgr.SelectTask(Convert.ToDecimal(btn.CommandArgument));

            //task.RECORD_TYPE = recordType;
            //task.RECORD_ID = recordID;
            //task.RECORD_SUBID = recordSubID;
            //task.TASK_STEP = taskStep;
            //task.TASK_TYPE = taskType;
            //task.TASK_SEQ = 0;
            task.DUE_DT = rdpTaskDueDT.SelectedDate;
            //task.RESPONSIBLE_ID = Convert.ToDecimal(ddlAssignPerson.SelectedValue.ToString());
            //task.DETAIL = lblTaskDetailValue.Text.ToString(); // this is the original detail, so we don't change it.
            //task.DESCRIPTION = tbTaskDescription.Text.ToString();
            task.COMMENTS = tbTaskComments.Text.ToString();
            //task.STATUS = ((int)TaskStatus.New).ToString();
            //task.CREATE_DT = SessionManager.UserContext.LocalTime != null ? SessionManager.UserContext.LocalTime : DateTime.UtcNow;
            //task.CREATE_ID = SessionManager.UserContext.Person.PERSON_ID;

            taskMgr.UpdateTask(task);
            taskMgr.UpdateTaskList(task.RECORD_ID);
            // send email
            PERSON assignTo = SQMModelMgr.LookupPerson(ctx, (decimal)task.RESPONSIBLE_ID, "", false);

            EHSNotificationMgr.NotifyTaskAssigment(task, assignTo.PLANT_ID);

            // reset the fields for the next add
            ddlAssignPersonAdd.SelectedValue = "";
            tbTaskDescriptionAdd.Text        = "";
            rdpTaskDueDTAdd.SelectedDate     = DateTime.Today;

            if (OnTaskAdd != null)
            {
                OnTaskAdd("added", task.RECORD_ID, (decimal)task.RECORD_SUBID);
            }
            if (task.RECORD_TYPE == (int)TaskRecordType.Audit)             // update the Question Status when adding tasks for an audit followup.
            {
                EHSAuditQuestion auditQuestion = EHSAuditMgr.SelectAuditQuestion(task.RECORD_ID, (decimal)task.RECORD_SUBID);

                if (auditQuestion != null)
                {
                    auditQuestion.Status = "02";
                    EHSAuditMgr.UpdateAnswer(auditQuestion);
                }
                //SessionManager.ReturnRecordID = task.RECORD_ID;
                //SessionManager.ReturnObject = "AddTask";
                //SessionManager.ReturnStatus = true;
            }

            if (Page.Request.Url.ToString().Contains("AssessmentForm"))
            {
                // now update the list and stay on the popup if adding through assessment form
                BindTaskAdd(task.RECORD_TYPE, task.RECORD_ID, (decimal)task.RECORD_SUBID, task.TASK_STEP, task.TASK_TYPE, lblTaskDetailValue.Text.ToString(), assignTo.PLANT_ID, "");
                lblErrorMessage.Text = "";

                string script = "function f(){OpenUpdateTaskWindow(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
            }
            else
            {
                SessionManager.ReturnRecordID = task.RECORD_ID;
                SessionManager.ReturnObject   = "UpdateTask";
                SessionManager.ReturnStatus   = true;

                if (OnTaskUpdate != null)
                {
                    OnTaskUpdate("update");
                }
            }
        }
        protected void btnTaskAdd_Click(object sender, EventArgs e)
        {
            PSsqmEntities ctx = new PSsqmEntities();

            lblErrorMessage.Text = "";
            Button btn = (Button)sender;

            if (btn == null || string.IsNullOrEmpty(btn.CommandArgument))
            {
                return;
            }

            string[] cmd         = btn.CommandArgument.Split('~');     // recordType, recordID, recordSubID, taskStep, taskType, plantID
            int      recordType  = Convert.ToInt32(cmd[0]);
            decimal  recordID    = Convert.ToDecimal(cmd[1]);
            decimal  recordSubID = Convert.ToDecimal(cmd[2]);
            string   taskStep    = cmd[3];
            string   taskType    = cmd[4];

            decimal plantID = 0;

            decimal.TryParse(cmd[5], out plantID);

            // make sure that the Assign To Employee has been selected
            if (ddlAssignPersonAdd.SelectedValue.ToString().Equals(""))
            {
                // I don't think we need to bind the list at this point
                BindTaskAdd(recordType, recordID, recordSubID, taskStep, taskType, lblTaskDetailValueAdd.Text.ToString(), plantID, "");
                lblErrorMessage.Text = lblErrRequiredInputs.Text.ToString();
                string script = "function f(){OpenUpdateTaskWindow(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
            }
            else
            {
                TaskStatusMgr taskMgr = new TaskStatusMgr();
                taskMgr.Initialize(recordType, recordID);
                TASK_STATUS task = new TASK_STATUS();
                task.RECORD_TYPE    = recordType;
                task.RECORD_ID      = recordID;
                task.RECORD_SUBID   = recordSubID;
                task.TASK_STEP      = taskStep;
                task.TASK_TYPE      = taskType;
                task.TASK_SEQ       = 0;
                task.DUE_DT         = rdpTaskDueDTAdd.SelectedDate;
                task.RESPONSIBLE_ID = Convert.ToDecimal(ddlAssignPersonAdd.SelectedValue.ToString());
                task.DETAIL         = lblTaskDetailValueAdd.Text.ToString();
                task.DESCRIPTION    = tbTaskDescriptionAdd.Text.ToString();
                task.STATUS         = ((int)TaskStatus.New).ToString();
                task.CREATE_DT      = SessionManager.UserContext.LocalTime != null ? SessionManager.UserContext.LocalTime : DateTime.UtcNow;
                task.CREATE_ID      = SessionManager.UserContext.Person.PERSON_ID;

                taskMgr.CreateTask(task);
                taskMgr.UpdateTaskList(task.RECORD_ID);
                // send email
                PERSON assignTo = SQMModelMgr.LookupPerson(ctx, (decimal)task.RESPONSIBLE_ID, "", false);
                EHSNotificationMgr.NotifyTaskAssigment(task, assignTo.PLANT_ID);

                // reset the fields for the next add
                ddlAssignPersonAdd.SelectedValue = "";
                tbTaskDescriptionAdd.Text        = "";
                rdpTaskDueDTAdd.SelectedDate     = DateTime.Today;

                if (OnTaskAdd != null)
                {
                    OnTaskAdd("added", task.RECORD_ID, (decimal)task.RECORD_SUBID);
                }
                if (recordType == (int)TaskRecordType.Audit)                 // update the Question Status when adding tasks for an audit followup.
                {
                    EHSAuditQuestion auditQuestion = EHSAuditMgr.SelectAuditQuestion(recordID, recordSubID);

                    if (auditQuestion != null)
                    {
                        auditQuestion.Status = "02";
                        EHSAuditMgr.UpdateAnswer(auditQuestion);
                    }
                    //SessionManager.ReturnRecordID = task.RECORD_ID;
                    //SessionManager.ReturnObject = "AddTask";
                    //SessionManager.ReturnStatus = true;
                }

                if (Page.Request.Url.ToString().Contains("AssessmentForm"))
                {
                    // now update the list and stay on the popup
                    BindTaskAdd(recordType, recordID, recordSubID, taskStep, taskType, lblTaskDetailValueAdd.Text.ToString(), plantID, "");
                    lblErrorMessage.Text = "";
                    string script = "function f(){OpenUpdateTaskWindow(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
                }
                else
                {
                    SessionManager.ReturnRecordID = task.RECORD_ID;
                    SessionManager.ReturnObject   = "AddTask";
                    SessionManager.ReturnStatus   = true;
                }
            }
        }
        protected void btnPassSave_Click(object sender, EventArgs e)
        {
            int status = 0;

            lblPassPolicyFail.Visible    = false;
            lblPasswordNoConfirm.Visible = false;
            lblPassFailUpdate.Visible    = false;
            lblPassFailError.Visible     = false;
            lblPassFail10.Visible        = false;
            divErrorMsg.Visible          = false;

            // validate the password criteria
            if (tbNewPassword.Text != tbConfirmPassword.Text)
            {
                status = -1;
            }
            else
            {
                status = SQMModelMgr.ChangeUserPassword(SessionManager.UserContext.Credentials.SSO_ID, "", tbCurrentPassword.Text.ToString().Trim(), tbNewPassword.Text.ToString().Trim());
            }

            if (status == 0)
            {
                // send a confirmation email
                string strEmailCompanyName = SQMSettings.SelectSettingByCode(new PSsqmEntities(), "MAIL", "TASK", "MailFromSystem").VALUE; // WebConfigurationManager.AppSettings["MailFromSystem"];
                string strEmailBody        = lblPasswordEmailBody1a.Text.ToString() + strEmailCompanyName + lblPasswordEmailBody1b.Text.ToString() + "<br><br>" + lblPasswordEmailBody2.Text.ToString();
                // ABW 20140117 - we are now usig the email on the Person record
                //string strEmailSent = WebSiteCommon.SendEmail(SessionManager.UserContext.Credentials.RECOVERY_EMAIL, lblPasswordEmailSubject.Text.ToString(), strEmailBody.Trim(), "");
                string strEmailSent = WebSiteCommon.SendEmail(SessionManager.UserContext.Person.EMAIL, strEmailCompanyName + lblPasswordEmailSubject.Text.ToString(), strEmailBody.Trim(), "");
                EHSNotificationMgr.WriteEmailLog(new PSsqmEntities(), SessionManager.UserContext.Person.EMAIL, "", strEmailCompanyName + lblPasswordEmailSubject.Text.ToString(), strEmailBody, 0, SessionManager.UserContext.Person.PERSON_ID, "user password changed", "", "");

                if (strCurrentControl.Equals("login"))
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "AlertPostback('" + hfPasswordChangedSucces.Value + "','loginContinue');", true);
                }
                else
                {
                    hideControl();
                }

                ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alertResult('hfAlertSaveSuccess');", true);
            }
            else
            {
                divErrorMsg.Visible = true;
                switch (status)
                {
                case -1:
                    lblPasswordNoConfirm.Visible = true;
                    break;

                case 10:
                    lblPassFail10.Visible = true;
                    break;

                case 100:
                    lblPassPolicyFail.Visible = true;
                    break;

                case 110:
                    lblPassPolicyFail.Visible = true;
                    break;

                case 120:
                    lblPassPolicyFail.Visible = true;
                    break;

                case 130:
                    lblPassPolicyFail.Visible = true;
                    break;

                case 140:
                    lblPassPolicyFail.Visible = true;
                    break;

                default:
                    lblPassFailUpdate.Visible = true;
                    lblPassFailError.Visible  = true;
                    lblPassFailError.Text     = status.ToString();
                    break;
                }
                BindPwdEdit(true);
            }
            // hide the control?
        }
        protected bool SaveUser(bool updateUser)
        {
            bool  bErrors = false;
            bool  success;
            Label lblErrorMessage = null;

            PERSON person        = LocalPerson();
            string currentSSOID  = LocalPerson().SSO_ID;
            PERSON currentPerson = new PERSON();

            if (isNew)
            {
                person.SSO_ID = string.IsNullOrEmpty(tbUserSSOID.Text) ? "" : tbUserSSOID.Text.Trim();  // trim traling blanks when creating new user
            }
            else
            {
                person             = SQMModelMgr.LookupPerson(entities, person.PERSON_ID, "", false);
                person.SSO_ID      = string.IsNullOrEmpty(tbUserSSOID.Text) ? "" : tbUserSSOID.Text;
                currentPerson.ROLE = person.ROLE;
            }

            person.FIRST_NAME  = string.IsNullOrEmpty(tbUserFirstName.Text) ? "" : tbUserFirstName.Text;
            person.LAST_NAME   = string.IsNullOrEmpty(tbUserLastName.Text) ? "" : tbUserLastName.Text;
            person.MIDDLE_NAME = string.IsNullOrEmpty(tbUserMiddleName.Text) ? "" : tbUserMiddleName.Text;
            person.JOBCODE_CD  = ddlJobCode.SelectedValue;
            if (string.IsNullOrEmpty(ddlPrivGroup.SelectedValue))
            {
                person.PRIV_GROUP = null;
            }
            else
            {
                person.PRIV_GROUP = ddlPrivGroup.SelectedValue;
            }
            person.PHONE       = tbUserPhone.Text;
            person.EMAIL       = tbUserEmail.Text;
            person.EMP_ID      = tbEmpID.Text;
            person.SUPV_EMP_ID = tbSupvEmpID.Text;

            if (!string.IsNullOrEmpty(ddlUserLanguage.SelectedValue))
            {
                person.PREFERRED_LANG_ID = Convert.ToInt32(ddlUserLanguage.SelectedValue);
            }
            if (!string.IsNullOrEmpty(ddlUserTimezone.SelectedValue))
            {
                person.PREFERRED_TIMEZONE = ddlUserTimezone.SelectedValue;
            }

            person.COMPANY_ID = SessionManager.EffLocation.Company.COMPANY_ID;
            if (!string.IsNullOrEmpty(ddlHRLocation.SelectedValue))
            {
                PLANT plant = SQMModelMgr.LookupPlant(Convert.ToDecimal(ddlHRLocation.SelectedValue));
                if (plant != null)
                {
                    person.PLANT_ID   = plant.PLANT_ID;
                    person.BUS_ORG_ID = (decimal)plant.BUS_ORG_ID;
                }
            }

            person.NEW_LOCATION_CD = "";
            foreach (RadComboBoxItem item in SQMBasePage.GetComboBoxCheckedItems(ddlPlantSelect))
            {
                if (string.IsNullOrEmpty(person.NEW_LOCATION_CD))
                {
                    person.NEW_LOCATION_CD = ",";
                }
                person.NEW_LOCATION_CD += (item.Value + ",");
            }

            person.OLD_LOCATION_CD = "";

            /* quality module reference
             * foreach (RadComboBoxItem item in SQMBasePage.GetComboBoxCheckedItems(ddlCustPlantSelect))
             * {
             *  person.OLD_LOCATION_CD += (item.Value + ",");
             * }
             * person.OLD_LOCATION_CD = person.OLD_LOCATION_CD.TrimEnd(',');
             */
            person.STATUS = ddlUserStatus.SelectedValue;

            // roles were originally a list - let's keep the logic below just in case we need to restore a multi-role strategy
            //person.PERSON_ROLE.Clear();
            person.ROLE           = 100;   /////
            person.RCV_ESCALATION = true;

            person.LOCKS = "";
            if (cbUserEmailLock.Checked)
            {
                person.LOCKS += (LockField.email.ToString() + ",");
            }
            if (cbPrivGroupLock.Checked)
            {
                person.LOCKS += (LockField.priv.ToString() + ",");
            }
            if (cbHRLocationLock.Checked)
            {
                person.LOCKS += (LockField.plant.ToString() + ",");
            }
            if (cbUserLanguageLock.Checked)
            {
                person.LOCKS += (LockField.lang.ToString() + ",");
            }
            person.LOCKS = person.LOCKS.TrimEnd(',');

            SetLocalPerson(person);

            if (string.IsNullOrEmpty(tbUserSSOID.Text) || string.IsNullOrEmpty(tbUserFirstName.Text) || string.IsNullOrEmpty(tbUserLastName.Text) ||
                ddlJobCode.SelectedIndex < 0 || string.IsNullOrEmpty(ddlHRLocation.SelectedValue) ||
                string.IsNullOrEmpty(ddlHRLocation.SelectedValue))
            {
                lblErrorMessage = lblErrRequiredInputs;
            }

            if (lblErrorMessage == null)
            {
                // AW20131106 - need to verify that the SSO_ID and email address are unique in the system
                lblDuplicateSSOId.Visible = false;
                lblDuplicateEmail.Visible = false;
                string strSSOId = tbUserSSOID.Text;
                string strEmail = tbUserEmail.Text;
                if (isNew) // || !strSSOId.Equals(person.SSO_ID))
                {
                    // verify unique sso_id
                    strSSOId = tbUserSSOID.Text.Trim();
                    SQM.Website.PSsqmEntities ctxAccess = new PSsqmEntities();
                    SQM_ACCESS access = SQMModelMgr.LookupCredentials(ctxAccess, strSSOId, "", false);
                    if (access != null && access.SSO_ID.ToLower().Equals(strSSOId.ToLower()))
                    {
                        lblErrorMessage = lblDuplicateSSOId;
                    }
                }
                if (lblErrorMessage == null && (isNew || !strEmail.Equals(person.EMAIL)))
                {
                    // verify unique email
                    SQM.Website.PSsqmEntities ctxAccess = new PSsqmEntities();
                    //SQM_ACCESS access = SQMModelMgr.LookupCredentialsByEmail(ctxAccess, strEmail, false);
                    // ABW 20140117 - we want to look up email on person record...
                    PERSON personEmail = SQMModelMgr.LookupPersonByEmail(ctxAccess, strEmail);
                    if (personEmail != null && personEmail.EMAIL.Trim().ToLower().Equals(strEmail.Trim().ToLower()))
                    {
                        lblErrorMessage = lblDuplicateEmail;
                    }
                }
            }
            if (lblErrorMessage != null)
            {
                DisplayUser();
                DisplayErrorMessage(lblErrorMessage);
                return(false);
            }

            if (updateUser)
            {
                string defaultPwd  = "";
                string environment = System.Configuration.ConfigurationManager.AppSettings["environment"].ToString();
                string altEmail    = !string.IsNullOrEmpty(environment) && environment.ToLower() == "dev" ?  System.Configuration.ConfigurationManager.AppSettings["altEmail"].ToString() : "";
                if (isNew)
                {
                    SETTINGS pwdInitial = SQMSettings.SelectSettingByCode(entities, "COMPANY", "TASK", "PasswordDefault");
                    if (pwdInitial != null)
                    {
                        switch (pwdInitial.VALUE.ToUpper())
                        {
                        case "LASTNAME":
                            defaultPwd = person.LAST_NAME;
                            break;

                        case "EMPID":
                            defaultPwd = person.EMP_ID;
                            break;

                        default:
                            break;
                        }
                    }
                }
                SetLocalPerson(SQMModelMgr.UpdatePerson(entities, person, SessionManager.UserContext.UserName(), false, currentSSOID, defaultPwd));
                //selectedUser = SQMModelMgr.UpdatePerson(entities, person, SessionManager.UserContext.UserName(), Convert.ToBoolean(GetFindControlValue("cbIsBuyer", hfBase, out success)), GetFindControlValue("tbBuyerCode", hfBase, out success));
                // AW20131106 - send an email for new users with random password generation
                List <SETTINGS> MailSettings = SQMSettings.SelectSettingsGroup("MAIL", ""); // ABW 20140805
                SETTINGS        setting      = new SETTINGS();                              // ABW 20140805
                setting = MailSettings.Find(x => x.SETTING_CD == "MailFromSystem");         // ABW 20140805
                string strEmailCompanyName = "";                                            // ABW 20140805
                if (setting != null)                                                        // ABW 20140805
                {
                    strEmailCompanyName = setting.VALUE;
                }
                bool sendEmail = false;
                setting = MailSettings.Find(x => x.SETTING_CD == "SendNewUserEmail");
                if (setting != null && setting.VALUE.ToLower().Equals("true"))                 // ABW 20140805
                {
                    sendEmail = true;
                }

                List <XLAT> XLATList = SQMBasePage.SelectXLATList(new string[1] {
                    "USER_EMAIL"
                }, 0);
                string         strEmailSubject = "";
                string         strEmailBody    = "";
                LOCAL_LANGUAGE lang            = SQMModelMgr.LookupLanguage(new PSsqmEntities(), "", (int)person.PREFERRED_LANG_ID, false);
                string         strTemp         = "";

                if (isNew && (string.IsNullOrEmpty(defaultPwd) || sendEmail))                  // send email notice only when a default password was not set
                {
                    // send a confirmation email
                    // string strength = WebConfigurationManager.AppSettings["PasswordComplexity"]; // ABW 20140805
                    SETTINGS complexity = SQMSettings.SelectSettingByCode(entities, "COMPANY", "TASK", "PasswordComplexity"); // ABW 20140805
                    string   strength   = "";                                                                                 // ABW 20140805
                    if (complexity == null)
                    {
                        strength = "4";
                    }
                    else
                    {
                        strength = complexity.VALUE;
                    }

                    SQM.Website.PSsqmEntities ctxAccess = new PSsqmEntities();
                    SQM_ACCESS access      = SQMModelMgr.LookupCredentials(ctxAccess, LocalPerson().SSO_ID, "", false);
                    string     key         = SQMModelMgr.GetPasswordKey();
                    string     strPassword = WebSiteCommon.Decrypt(access.PASSWORD, key);

                    // ABW 20140805 - Build the email based on fields in the SETTINGS table
                    //string strEmailSubject = "";
                    //setting = MailSettings.Find(x => x.SETTING_CD == "NewUserSubject");
                    //if (setting == null)
                    //	strEmailSubject = strEmailCompanyName + " " + lblPasswordEmailSubject.Text.ToString();
                    //else
                    //	strEmailSubject = setting.VALUE.Trim();
                    //setting = MailSettings.Find(x => x.SETTING_CD == "NewUserWelcome");
                    //string strEmailBody = "";
                    //if (setting == null)
                    //	strEmailBody = lblPasswordEmailBody1a.Text.ToString();
                    //else
                    //	strEmailBody = setting.VALUE.Trim();
                    //strEmailBody += lblPasswordEmailBody1b.Text.ToString() + " " + LocalPerson().SSO_ID + lblPasswordEmailBody2.Text.ToString() + " " + strPassword;
                    //setting = MailSettings.Find(x => x.SETTING_CD == "MailURL");
                    //if (setting != null)
                    //	strEmailBody += lblPasswordEmailBody2b.Text.ToString() + "<a href='" + setting.VALUE + "'>" + setting.VALUE + "</a>";
                    //complexity = SQMSettings.SelectSettingByCode(entities, "PASSWORDCOMPLEXITY", "TASK", strength); // ABW 20140805
                    //if (complexity != null)
                    //	strEmailBody += "<br><br>" + complexity.VALUE + "<br><br>";
                    //setting = MailSettings.Find(x => x.SETTING_CD == "NewUserSignature");
                    //if (setting == null)
                    //	strEmailBody += "<br><br>" + lblPasswordEmailBody3.Text.ToString();
                    //else
                    //	strEmailBody += "<br><br>" + setting.VALUE.Trim();

                    // ABW 20160115 - Build the email based on fields in the XLAT table
                    strTemp = SQMBasePage.GetXLAT(XLATList, "USER_EMAIL", "NewUserSubject", lang.NLS_LANGUAGE).DESCRIPTION;
                    if (strTemp == null || strTemp == "")
                    {
                        strEmailSubject = strEmailCompanyName + " " + lblPasswordEmailSubject.Text.ToString();
                    }
                    else
                    {
                        strEmailSubject = strTemp.Trim();
                    }
                    strTemp      = SQMBasePage.GetXLAT(XLATList, "USER_EMAIL", "NewUserWelcome", lang.NLS_LANGUAGE).DESCRIPTION;
                    strEmailBody = "";
                    if (strTemp == null || strTemp == "")
                    {
                        strEmailBody = lblPasswordEmailBody1a.Text.ToString();
                    }
                    else
                    {
                        strEmailBody = strTemp.Trim();
                    }
                    strTemp = SQMBasePage.GetXLAT(XLATList, "USER_EMAIL", "NewUserBodyUsername", lang.NLS_LANGUAGE).DESCRIPTION;
                    if (strTemp == null || strTemp == "")
                    {
                        strEmailBody += lblPasswordEmailBody1b.Text.ToString();
                    }
                    else
                    {
                        strEmailBody += strTemp.Trim();
                    }
                    strEmailBody += " " + LocalPerson().SSO_ID;
                    strTemp       = SQMBasePage.GetXLAT(XLATList, "USER_EMAIL", "NewUserBodyPassword", lang.NLS_LANGUAGE).DESCRIPTION;
                    if (strTemp == null || strTemp == "")
                    {
                        strEmailBody += lblPasswordEmailBody2.Text.ToString();
                    }
                    else
                    {
                        strEmailBody += strTemp.Trim();
                    }
                    strEmailBody += " " + strPassword;
                    strTemp       = SQMBasePage.GetXLAT(XLATList, "USER_EMAIL", "NewUserBodyUrl", lang.NLS_LANGUAGE).DESCRIPTION;
                    string strUrlLabel = "";
                    if (strTemp == null || strTemp == "")
                    {
                        strUrlLabel = lblPasswordEmailBody2b.Text.ToString();
                    }
                    else
                    {
                        strUrlLabel = strTemp.Trim();
                    }
                    setting = MailSettings.Find(x => x.SETTING_CD == "MailURL");
                    if (setting != null)
                    {
                        strEmailBody += strUrlLabel + " <a href='" + setting.VALUE + "'>" + setting.VALUE + "</a>";
                    }
                    complexity = SQMSettings.SelectSettingByCode(entities, "PASSWORDCOMPLEXITY", "TASK", strength);                     // ABW 20140805
                    if (complexity != null)
                    {
                        strEmailBody += "<br><br>" + complexity.VALUE + "<br><br>";
                    }
                    strTemp = SQMBasePage.GetXLAT(XLATList, "USER_EMAIL", "NewUserSignature", lang.NLS_LANGUAGE).DESCRIPTION;
                    if (strTemp == null || strTemp == "")
                    {
                        strEmailBody += "<br><br>" + lblPasswordEmailBody3.Text.ToString();
                    }
                    else
                    {
                        strEmailBody += "<br><br>" + strTemp.Trim();
                    }

                    // ABW 20140117 - we are now using the email on the Person record

                    /*
                     * Thread thread = new Thread(() => WebSiteCommon.SendEmail(person.EMAIL, strEmailSubject, strEmailBody.Trim(), ""));
                     * thread.IsBackground = true;
                     * thread.Start();
                     */
                    string mailStatus = WebSiteCommon.SendEmail(person.EMAIL, strEmailSubject, strEmailBody.Trim(), "");
                    EHSNotificationMgr.WriteEmailLog(entities, person.EMAIL, "", strEmailSubject, strEmailBody, 0, LocalPerson().PERSON_ID, ("user password notification - is new = " + isNew.ToString()), mailStatus, altEmail);
                }
                else
                {
                    bool roleChanged = person.ROLE != currentPerson.ROLE ? true : false;
                    // ABW 20160115 - send an email based on a parameter
                    setting = MailSettings.Find(x => x.SETTING_CD == "SendChangeUserEmail");
                    if (setting != null && setting.VALUE.ToLower().Equals("true"))
                    {
                        sendEmail = true;
                    }
                    else
                    {
                        sendEmail = false;
                    }

                    if (roleChanged && sendEmail)
                    {
                        //ABW 20140805 - Build the email based on fields in the SETTINGS table
                        //strEmailSubject = "";
                        //setting = MailSettings.Find(x => x.SETTING_CD == "AdminRoleChangeSubject");
                        //if (setting == null)
                        //	strEmailSubject = lblUserRoleEmailSubjecta.Text + strEmailCompanyName + lblUserRoleEmailSubjectb.Text;
                        //else
                        //	strEmailSubject = setting.VALUE.Trim();
                        //setting = MailSettings.Find(x => x.SETTING_CD == "AdminRoleChangeWelcome");
                        //string strEmailBody = "";
                        //if (setting == null)
                        //	strEmailBody = lblUserRoleEmailBodya.Text + strEmailCompanyName + lblUserRoleEmailBodyb.Text;
                        //else
                        //	strEmailBody = setting.VALUE.Trim();

                        //setting = MailSettings.Find(x => x.SETTING_CD == "AdminRoleChangeSignature");
                        //if (setting == null)
                        //	strEmailBody += "<br><br>" + lblUserRoleEmailBodyc.Text;
                        //else
                        //	strEmailBody += "<br><br>" + setting.VALUE.Trim();

                        //ABW 20160115 - Build the email based on fields in the XLAT table
                        strEmailSubject = "";
                        strTemp         = SQMBasePage.GetXLAT(XLATList, "USER_EMAIL", "AdminRoleChangeSubject", lang.NLS_LANGUAGE).DESCRIPTION;
                        if (strTemp == null || strTemp == "")
                        {
                            strEmailSubject = lblUserRoleEmailSubjecta.Text + strEmailCompanyName + lblUserRoleEmailSubjectb.Text;
                        }
                        else
                        {
                            strEmailSubject = strTemp.Trim();
                        }

                        strEmailBody = "";
                        strTemp      = SQMBasePage.GetXLAT(XLATList, "USER_EMAIL", "AdminRoleChangeWelcome", lang.NLS_LANGUAGE).DESCRIPTION;
                        if (strTemp == null || strTemp == "")
                        {
                            strEmailBody = lblUserRoleEmailBodya.Text + strEmailCompanyName + lblUserRoleEmailBodyb.Text;
                        }
                        else
                        {
                            strEmailBody = strTemp.Trim();
                        }

                        setting = MailSettings.Find(x => x.SETTING_CD == "AdminRoleChangeSignature");
                        strTemp = SQMBasePage.GetXLAT(XLATList, "USER_EMAIL", "AdminRoleChangeSignature", lang.NLS_LANGUAGE).DESCRIPTION;
                        if (strTemp == null || strTemp == "")
                        {
                            strEmailBody += "<br><br>" + lblUserRoleEmailBodyc.Text;
                        }
                        else
                        {
                            strEmailBody += strTemp.Trim();
                        }

                        /*
                         * Thread thread = new Thread(() => WebSiteCommon.SendEmail(person.EMAIL, strEmailSubject, strEmailBody, ""));
                         * thread.IsBackground = true;
                         * thread.Start();
                         */
                        string mailStatus = WebSiteCommon.SendEmail(person.EMAIL, strEmailSubject, strEmailBody, "");
                        EHSNotificationMgr.WriteEmailLog(entities, person.EMAIL, "", strEmailSubject, strEmailBody, 0, LocalPerson().PERSON_ID, "user role changed", mailStatus, altEmail);
                    }

                    if (cbResetPassword.Checked)                     // always send an email when the password changes
                    {
                        // build the email body in 3 segments
                        SETTINGS complexity = SQMSettings.SelectSettingByCode(entities, "COMPANY", "TASK", "PasswordComplexity");
                        string   strength   = "";
                        if (complexity == null)
                        {
                            strength = "4";
                        }
                        else
                        {
                            strength = complexity.VALUE;
                        }

                        // ABW 20140805 - Build the email based on fields in the SETTINGS table
                        //string strEmailSubject = "";
                        //setting = MailSettings.Find(x => x.SETTING_CD == "AdminPasswordResetSubject");
                        //if (setting == null)
                        //	strEmailSubject = strEmailCompanyName + " " + lblResetEmailSubject.Text.ToString();
                        //else
                        //	strEmailSubject = setting.VALUE.Trim();
                        //setting = MailSettings.Find(x => x.SETTING_CD == "AdminPasswordResetWelcome");
                        //string strEmailBodya = "";
                        //string strEmailBodyb = "";
                        //string strEmailBodyc = "";
                        //if (setting == null)
                        //	strEmailBodya = lblPasswordEmailBody1a.Text.ToString();
                        //else
                        //	strEmailBodya = setting.VALUE.Trim();
                        //strEmailBodya += lblPasswordEmailBody1b.Text.ToString();
                        //strEmailBodyb = lblPasswordEmailBody2.Text.ToString();
                        //setting = MailSettings.Find(x => x.SETTING_CD == "MailURL");
                        //if (setting != null)
                        //	strEmailBodyc += lblPasswordEmailBody2b.Text.ToString() + "<a href='" + setting.VALUE + "'>" + setting.VALUE + "</a>";
                        //complexity = SQMSettings.SelectSettingByCode(entities, "PASSWORDCOMPLEXITY", "TASK", strength);
                        //if (complexity != null)
                        //	strEmailBodyc += "<br><br>" + complexity.VALUE + "<br><br>";
                        //setting = MailSettings.Find(x => x.SETTING_CD == "AdminPasswordResetSignature");
                        //if (setting == null)
                        //	strEmailBodyc += "<br><br>" + lblPasswordEmailBody3.Text.ToString();
                        //else
                        //	strEmailBodyc += "<br><br>" + setting.VALUE.Trim();

                        // ABW 20160115 - Build the email based on fields in the XLAT table
                        strTemp = SQMBasePage.GetXLAT(XLATList, "USER_EMAIL", "AdminPasswordResetSubject", lang.NLS_LANGUAGE).DESCRIPTION;
                        if (strTemp == null || strTemp == "")
                        {
                            strEmailSubject = strEmailCompanyName + " " + lblPasswordEmailSubject.Text.ToString();
                        }
                        else
                        {
                            strEmailSubject = strTemp.Trim();
                        }

                        string strEmailBodya = "";
                        string strEmailBodyb = "";
                        string strEmailBodyc = "";
                        strTemp = SQMBasePage.GetXLAT(XLATList, "USER_EMAIL", "AdminPasswordResetWelcome", lang.NLS_LANGUAGE).DESCRIPTION;
                        if (strTemp == null || strTemp == "")
                        {
                            strEmailBodya = lblResetEmailBody1a.Text.ToString();
                        }
                        else
                        {
                            strEmailBodya = strTemp.Trim();
                        }

                        strTemp = SQMBasePage.GetXLAT(XLATList, "USER_EMAIL", "NewUserBodyUsername", lang.NLS_LANGUAGE).DESCRIPTION;
                        if (strTemp == null || strTemp == "")
                        {
                            strEmailBodya += lblPasswordEmailBody1b.Text.ToString();
                        }
                        else
                        {
                            strEmailBodya += strTemp.Trim();
                        }

                        strTemp = SQMBasePage.GetXLAT(XLATList, "USER_EMAIL", "NewUserBodyPassword", lang.NLS_LANGUAGE).DESCRIPTION;
                        if (strTemp == null || strTemp == "")
                        {
                            strEmailBodyb = lblPasswordEmailBody2.Text.ToString();
                        }
                        else
                        {
                            strEmailBodyb = strTemp.Trim();
                        }

                        strTemp = SQMBasePage.GetXLAT(XLATList, "USER_EMAIL", "NewUserBodyUrl", lang.NLS_LANGUAGE).DESCRIPTION;
                        string strUrlLabel = "";
                        if (strTemp == null || strTemp == "")
                        {
                            strUrlLabel = lblPasswordEmailBody2b.Text.ToString();
                        }
                        else
                        {
                            strUrlLabel = strTemp.Trim();
                        }
                        setting = MailSettings.Find(x => x.SETTING_CD == "MailURL");
                        if (setting != null)
                        {
                            strEmailBodyc += strUrlLabel.Trim() + "<a href='" + setting.VALUE + "'>" + setting.VALUE + "</a>";
                        }
                        complexity = SQMSettings.SelectSettingByCode(entities, "PASSWORDCOMPLEXITY", "TASK", strength);
                        if (complexity != null)
                        {
                            strEmailBodyc += "<br><br>" + complexity.VALUE + "<br><br>";
                        }

                        strTemp = SQMBasePage.GetXLAT(XLATList, "USER_EMAIL", "NewUserSignature", lang.NLS_LANGUAGE).DESCRIPTION;
                        if (strTemp == null || strTemp == "")
                        {
                            strEmailBodyc += "<br><br>" + lblPasswordEmailBody3.Text.ToString();
                        }
                        else
                        {
                            strEmailBodyc += "<br><br>" + strTemp.Trim();
                        }

                        int msg = WebSiteCommon.RecoverPassword(person.EMAIL, person.SSO_ID, strEmailSubject, strEmailBodya, strEmailBodyb, strEmailBodyc);
                        EHSNotificationMgr.WriteEmailLog(entities, person.EMAIL, "", strEmailSubject, strEmailBodya, 0, LocalPerson().PERSON_ID, "recover password", msg.ToString(), altEmail);
                    }
                }
                isNew = false;
                if (SQMModelMgr.updateStatus < 0)  // report error
                {
                    AlertUpdateResult(SQMModelMgr.updateStatus);
                }
            }
            else
            {
                SetLocalPerson(person);
            }
            return(true);
        }