public bool IsSlaPaused(int triggerId, int organizationId)
            {
                bool           isPaused = false;
                TicketStatuses statuses = new TicketStatuses(_loginUser);

                statuses.LoadByStatusIDs(organizationId, new int[] { TicketStatusId });

                if (statuses != null && statuses.Any())
                {
                    isPaused = statuses[0].PauseSLA;
                }

                //check if "Pause on Specific Dates"
                if (!isPaused)
                {
                    List <DateTime> daysToPause = SlaTriggers.GetSpecificDaysToPause(triggerId);
                    isPaused = daysToPause.Where(p => DateTime.Compare(p.Date, DateTime.UtcNow.Date) == 0).Any();
                }

                //If Pause on Company Holidays is selected
                SlaTrigger slaTrigger = SlaTriggers.GetSlaTrigger(_loginUser, triggerId);

                if (!isPaused && slaTrigger.PauseOnHoliday)
                {
                    isPaused = SlaTriggers.IsOrganizationHoliday(organizationId, DateTime.UtcNow);
                }

                return(isPaused);
            }
Example #2
0
        public static string GetSlaTrigger(RestCommand command, int slaTriggerID)
        {
            SlaTrigger slaTrigger = SlaTriggers.GetSlaTrigger(command.LoginUser, slaTriggerID);

            if (slaTrigger.OrganizationID != command.Organization.OrganizationID)
            {
                throw new RestException(HttpStatusCode.Unauthorized);
            }
            return(slaTrigger.GetXml("SlaTrigger", true));
        }
    public static void DeleteTrigger(int slaTriggerID)
    {
        SlaTrigger trigger = SlaTriggers.GetSlaTrigger(UserSession.LoginUser, slaTriggerID);
        SlaLevel   level   = SlaLevels.GetSlaLevel(UserSession.LoginUser, trigger.SlaLevelID);

        if (trigger != null && level.OrganizationID == UserSession.LoginUser.OrganizationID && UserSession.CurrentUser.IsSystemAdmin)
        {
            trigger.Delete();
            trigger.Collection.Save();
        }
    }
Example #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["TicketID"] == null)
        {
            EndResponse("Invalid Ticket");
        }
        LoginUser loginUser = TSAuthentication.GetLoginUser();
        int       ticketID  = int.Parse(Request["TicketID"]);
        Ticket    ticket    = Tickets.GetTicket(loginUser, ticketID);

        if (ticket == null)
        {
            EndResponse("Invalid Ticket");
        }

        tipNumber.InnerText = "Ticket #" + ticket.TicketNumber.ToString();
        tipNumber.Attributes.Add("onclick", "top.Ts.MainPage.openTicket(" + ticket.TicketNumber + "); return false;");
        tipName.InnerHtml = ticket.Name;

        bool      isStatusPaused = false;
        SlaTicket slaTicket      = SlaTickets.GetSlaTicket(loginUser, ticket.TicketID);

        if (slaTicket != null)
        {
            SlaTrigger slaTrigger = SlaTriggers.GetSlaTrigger(loginUser, slaTicket.SlaTriggerId);

            if (slaTrigger != null)
            {
                isStatusPaused = ticket.IsSlaStatusPaused();
                string slaName = new SlaLevels(TSAuthentication.GetLoginUser()).GetSlaveLevelName(slaTicket.SlaTriggerId);
                wslaName.InnerText = slaName;
            }
            else
            {
                ticket.SlaViolationInitialResponse = null;
                ticket.SlaViolationTimeClosed      = null;
                ticket.SlaViolationLastAction      = null;
                ticket.SlaWarningInitialResponse   = null;
                ticket.SlaWarningTimeClosed        = null;
                ticket.SlaWarningLastAction        = null;
                ticket.Collection.Save();
            }
        }

        if (isStatusPaused)
        {
            wClose.InnerText = "Paused";
            vClose.InnerText = "Paused";
            wLast.InnerText  = "Paused";
            vLast.InnerText  = "Paused";
            wInit.InnerText  = "Paused";
            vInit.InnerText  = "Paused";
            wNext.InnerText  = "Paused";
            vNext.InnerText  = "Paused";
        }
        else
        {
            DateTime?nextViolation = GetUtcDate(ticket, "SlaViolationInitialResponse");
            nextViolation = GetMinDate(loginUser, nextViolation, GetUtcDate(ticket, "SlaViolationLastAction"));
            nextViolation = GetMinDate(loginUser, nextViolation, GetUtcDate(ticket, "SlaViolationTimeClosed"));

            DateTime?nextWarning = GetUtcDate(ticket, "SlaWarningInitialResponse");
            nextWarning = GetMinDate(loginUser, nextWarning, GetUtcDate(ticket, "SlaWarningLastAction"));
            nextWarning = GetMinDate(loginUser, nextWarning, GetUtcDate(ticket, "SlaWarningTimeClosed"));

            if (nextViolation != null && nextViolation < DateTime.UtcNow)
            {
                tipSla.Attributes.Add("class", "ts-icon ts-icon-sla-bad");
            }
            else if (nextWarning != null && nextWarning < DateTime.UtcNow)
            {
                tipSla.Attributes.Add("class", "ts-icon ts-icon-sla-warning");
            }
            else
            {
                tipSla.Attributes.Add("class", "ts-icon ts-icon-sla-good");
            }

            wClose.InnerText = GetDateString(loginUser, GetUtcDate(ticket, "SlaWarningTimeClosed"));
            vClose.InnerText = GetDateString(loginUser, GetUtcDate(ticket, "SlaViolationTimeClosed"));
            wLast.InnerText  = GetDateString(loginUser, GetUtcDate(ticket, "SlaWarningLastAction"));
            vLast.InnerText  = GetDateString(loginUser, GetUtcDate(ticket, "SlaViolationLastAction"));
            wInit.InnerText  = GetDateString(loginUser, GetUtcDate(ticket, "SlaWarningInitialResponse"));
            vInit.InnerText  = GetDateString(loginUser, GetUtcDate(ticket, "SlaViolationInitialResponse"));
            wNext.InnerText  = GetDateString(loginUser, nextWarning);
            vNext.InnerText  = GetDateString(loginUser, nextViolation);
        }
    }
        public override void Run()
        {
            try
            {
                SlaTickets slaTickets = new SlaTickets(LoginUser);
                slaTickets.LoadPending();

                if (slaTickets != null && slaTickets.Count > 0)
                {
                    Logs.WriteEvent(string.Format("{0} pending tickets to calculate the SLA values for.", slaTickets.Count));
                }

                foreach (SlaTicket slaTicket in slaTickets)
                {
                    if (IsStopped)
                    {
                        break;
                    }
                    UpdateHealth();

                    try
                    {
                        Ticket ticket = Tickets.GetTicket(LoginUser, slaTicket.TicketId);

                        if (ticket != null)
                        {
                            bool     isStatusPaused                 = ticket.IsSlaStatusPaused();
                            bool     isClosed                       = ticket.DateClosed != null;
                            DateTime?newSlaViolationTimeClosed      = null;
                            DateTime?newSlaWarningTimeClosed        = null;
                            DateTime?newSlaViolationLastAction      = null;
                            DateTime?newSlaWarningLastAction        = null;
                            DateTime?newSlaViolationInitialResponse = null;
                            DateTime?newSlaWarningInitialResponse   = null;

                            if (!isClosed && !isStatusPaused)
                            {
                                DateTime?lastActionDateCreated = Actions.GetLastActionDateCreated(LoginUser, ticket.TicketID);
                                int      totalActions          = Actions.TotalActionsForSla(LoginUser, ticket.TicketID, ticket.OrganizationID);

                                Organization organization = Organizations.GetOrganization(LoginUser, ticket.OrganizationID);
                                SlaTrigger   slaTrigger   = SlaTriggers.GetSlaTrigger(LoginUser, slaTicket.SlaTriggerId);

                                if (slaTrigger == null)
                                {
                                    Logs.WriteEventFormat("Trigger {0} not found.", slaTicket.SlaTriggerId);
                                }

                                SlaTickets.BusinessHours businessHours = new SlaTickets.BusinessHours()
                                {
                                    DayStartUtc  = organization.BusinessDayStartUtc,
                                    DayEndUtc    = organization.BusinessDayEndUtc,
                                    BusinessDays = organization.BusinessDays
                                };

                                //Check if we should use SLA's business hours instead of Account's
                                if (!slaTrigger.UseBusinessHours &&
                                    !slaTrigger.NoBusinessHours &&
                                    slaTrigger.DayStartUtc.HasValue &&
                                    slaTrigger.DayEndUtc.HasValue)
                                {
                                    businessHours.DayStartUtc  = slaTrigger.DayStartUtc.Value;
                                    businessHours.DayEndUtc    = slaTrigger.DayEndUtc.Value;
                                    businessHours.BusinessDays = slaTrigger.Weekdays;
                                }
                                else if (!slaTrigger.UseBusinessHours && !slaTrigger.NoBusinessHours)
                                {
                                    Logs.WriteEventFormat("Using Account's business hours {0} to {1} because while the trigger is set to use sla's business hours one of them has no value. Sla DayStartUtc {2}, Sla DayEndUtc {3}",
                                                          organization.BusinessDayStartUtc.ToShortTimeString(),
                                                          organization.BusinessDayEndUtc.ToShortTimeString(),
                                                          slaTrigger.DayStartUtc.HasValue ? slaTrigger.DayStartUtc.Value.ToShortTimeString() : "NULL",
                                                          slaTrigger.DayEndUtc.HasValue ? slaTrigger.DayEndUtc.Value.ToShortTimeString() : "NULL");
                                }

                                Logs.WriteEvent(string.Format("Ticket #{0} id {1}. LastAction: {2}, TotalActions: {3}, Org({4}) {5}, SlaTriggerId {6}.", ticket.TicketNumber,
                                                              ticket.TicketID,
                                                              lastActionDateCreated == null ? "none" : lastActionDateCreated.Value.ToString(),
                                                              totalActions,
                                                              organization.OrganizationID,
                                                              organization.Name,
                                                              slaTrigger.SlaTriggerID));
                                List <DateTime> daysToPause    = SlaTriggers.GetSpecificDaysToPause(slaTrigger.SlaTriggerID);
                                bool            pauseOnHoliday = slaTrigger.PauseOnHoliday;
                                CalendarEvents  holidays       = new CalendarEvents(LoginUser);

                                if (pauseOnHoliday)
                                {
                                    holidays.LoadHolidays(organization.OrganizationID);
                                }

                                Dictionary <int, double> businessPausedTimes = new Dictionary <int, double>();

                                //We need to have two calculations for the paused time, one for the Time To Close and Initial Response which should count the paused time since the Ticket creation
                                //and another one for Last Action where it should only count starting from the last action added
                                TimeSpan totalPausedTimeSpan = SlaTickets.CalculatePausedTime(ticket.TicketID, organization, businessHours, slaTrigger, daysToPause, holidays, LoginUser, businessPausedTimes, Logs);
                                Logs.WriteEventFormat("Total Paused Time: {0}", totalPausedTimeSpan.ToString());

                                UpdateBusinessPausedTimes(LoginUser, businessPausedTimes);

                                newSlaViolationTimeClosed = SlaTickets.CalculateSLA(ticket.DateCreatedUtc, businessHours, slaTrigger, slaTrigger.TimeToClose, totalPausedTimeSpan, daysToPause, holidays);

                                if (newSlaViolationTimeClosed != null)
                                {
                                    newSlaWarningTimeClosed = SlaTickets.CalculateSLAWarning(newSlaViolationTimeClosed.Value,
                                                                                             businessHours,
                                                                                             slaTrigger.NoBusinessHours,
                                                                                             slaTrigger.TimeToClose,
                                                                                             slaTrigger.WarningTime,
                                                                                             daysToPause,
                                                                                             holidays);
                                }

                                TimeSpan pausedTimeSpanSinceLastAction = SlaTickets.CalculatePausedTime(ticket.TicketID,
                                                                                                        organization, businessHours,
                                                                                                        slaTrigger,
                                                                                                        daysToPause,
                                                                                                        holidays,
                                                                                                        LoginUser,
                                                                                                        businessPausedTimes,
                                                                                                        Logs,
                                                                                                        false,
                                                                                                        lastActionDateCreated.HasValue ? lastActionDateCreated.Value : (DateTime?)null);
                                Logs.WriteEventFormat("Total Paused Time: {0}", pausedTimeSpanSinceLastAction.ToString());

                                if (lastActionDateCreated == null)
                                {
                                    newSlaViolationLastAction = null;
                                    newSlaWarningLastAction   = null;
                                }
                                else
                                {
                                    newSlaViolationLastAction = SlaTickets.CalculateSLA(lastActionDateCreated.Value,
                                                                                        businessHours,
                                                                                        slaTrigger,
                                                                                        slaTrigger.TimeLastAction,
                                                                                        pausedTimeSpanSinceLastAction,
                                                                                        daysToPause,
                                                                                        holidays);

                                    if (newSlaViolationLastAction != null)
                                    {
                                        newSlaWarningLastAction = SlaTickets.CalculateSLAWarning((DateTime)newSlaViolationLastAction.Value,
                                                                                                 businessHours,
                                                                                                 slaTrigger.NoBusinessHours,
                                                                                                 slaTrigger.TimeLastAction,
                                                                                                 slaTrigger.WarningTime,
                                                                                                 daysToPause,
                                                                                                 holidays);
                                    }
                                }

                                if (slaTrigger.TimeInitialResponse < 1 || totalActions > 0)
                                {
                                    newSlaViolationInitialResponse = null;
                                    newSlaWarningInitialResponse   = null;
                                }
                                else
                                {
                                    newSlaViolationInitialResponse = SlaTickets.CalculateSLA(ticket.DateCreatedUtc,
                                                                                             businessHours,
                                                                                             slaTrigger,
                                                                                             slaTrigger.TimeInitialResponse,
                                                                                             totalPausedTimeSpan,
                                                                                             daysToPause,
                                                                                             holidays);

                                    if (newSlaViolationInitialResponse != null)
                                    {
                                        newSlaWarningInitialResponse = SlaTickets.CalculateSLAWarning((DateTime)newSlaViolationInitialResponse.Value,
                                                                                                      businessHours,
                                                                                                      slaTrigger.NoBusinessHours,
                                                                                                      slaTrigger.TimeInitialResponse,
                                                                                                      slaTrigger.WarningTime,
                                                                                                      daysToPause,
                                                                                                      holidays);
                                    }
                                }
                            }
                            else
                            {
                                Logs.WriteEventFormat("Ticket is {0}, clearing its SLA values.", isClosed ? "Closed" : "Status Paused");
                            }

                            if (HasAnySlaChanges(ticket,
                                                 newSlaViolationTimeClosed,
                                                 newSlaWarningTimeClosed,
                                                 newSlaViolationLastAction,
                                                 newSlaWarningLastAction,
                                                 newSlaViolationInitialResponse,
                                                 newSlaWarningInitialResponse))
                            {
                                ticket.SlaViolationTimeClosed      = newSlaViolationTimeClosed;
                                ticket.SlaWarningTimeClosed        = newSlaWarningTimeClosed;
                                ticket.SlaViolationLastAction      = newSlaViolationLastAction;
                                ticket.SlaWarningLastAction        = newSlaWarningLastAction;
                                ticket.SlaViolationInitialResponse = newSlaViolationInitialResponse;
                                ticket.SlaWarningInitialResponse   = newSlaWarningInitialResponse;
                                Tickets.UpdateTicketSla(LoginUser,
                                                        ticket.TicketID,
                                                        newSlaViolationInitialResponse,
                                                        newSlaViolationLastAction,
                                                        newSlaViolationTimeClosed,
                                                        newSlaWarningInitialResponse,
                                                        newSlaWarningLastAction,
                                                        newSlaWarningTimeClosed);
                                Logs.WriteEvent("Ticket SLA calculation completed.");

                                string signalRUrl = Settings.ReadString("SignalRUrl");

                                if (!string.IsNullOrEmpty(signalRUrl))
                                {
                                    //Dictionary<string, string> queryStringData = new Dictionary<string, string>();
                                    //queryStringData.Add("userID", "-1");
                                    //queryStringData.Add("organizationID", ticket.OrganizationID.ToString());
                                    //HubConnection connection = new HubConnection(signalRUrl, queryStringData);
                                    //IHubProxy signalRConnection = connection.CreateHubProxy("TicketSocket");

                                    //try
                                    //{
                                    //    connection.Start().Wait();
                                    //    signalRConnection.Invoke("RefreshSLA", ticket.TicketNumber);
                                    //}
                                    //catch (Exception ex)
                                    //{
                                    //    Logs.WriteEvent("Could not send signalR to refresh the SLA. Message: " + ex.Message);
                                    //}
                                }
                            }
                            else
                            {
                                Logs.WriteEvent("Ticket SLA calculation completed. SLA values did not change, ticket was not updated.");
                            }

                            slaTicket.IsPending = false;
                            slaTicket.Collection.Save();
                        }
                        else
                        {
                            SlaPausedTimes slaPausedTimes = new SlaPausedTimes(LoginUser);
                            slaPausedTimes.LoadByTicketId(slaTicket.TicketId);
                            slaPausedTimes.DeleteAll();
                            slaPausedTimes.Save();

                            slaTicket.Delete();
                            slaTicket.Collection.Save();
                            Logs.WriteEventFormat("Ticket id {0} does not exist anymore, deleted from SlaTickets.", slaTicket.TicketId);
                        }

                        System.Threading.Thread.Sleep(100);
                    }
                    catch (System.Data.SqlClient.SqlException sqlEx)
                    {
                        //Handle the deadlock exception, any other bubble up.
                        if (sqlEx.Number == 1205 || sqlEx.Message.Contains("deadlocked"))
                        {
                            ExceptionLogs.LogException(LoginUser, sqlEx, "SLA Calculator", "Sync");
                            Logs.WriteEventFormat("Exception. Message {0}{1}StackTrace {2}", sqlEx.Message, Environment.NewLine, sqlEx.StackTrace);
                            slaTicket.IsPending = true;
                            slaTicket.Collection.Save();
                            Logs.WriteEventFormat("SlaTicket: TicketId {0} TriggerId {1} still pending.", slaTicket.TicketId, slaTicket.SlaTriggerId);
                        }
                        else
                        {
                            throw;
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogs.LogException(LoginUser, ex, "SLA Calculator", "Sync");
                        Logs.WriteEventFormat("Exception. Message {0}{1}StackTrace {2}", ex.Message, Environment.NewLine, ex.StackTrace);

                        slaTicket.IsPending = false;
                        slaTicket.Collection.Save();
                        Logs.WriteEventFormat("SlaTicket: TicketId {0} TriggerId {1} set to not pending.", slaTicket.TicketId, slaTicket.SlaTriggerId);
                    }
                }

                if (slaTickets != null && slaTickets.Count > 0)
                {
                    Logs.WriteEvent(string.Format("Completed processing the {0} pending tickets to calculate the SLA values for.", slaTickets.Count));
                }
            }
            catch (Exception ex)
            {
                ExceptionLogs.LogException(LoginUser, ex, "SLA Calculator", "Sync");
                Logs.WriteEvent(string.Format("Exception. Message {0}{1}StackTrace {2}", ex.Message, Environment.NewLine, ex.StackTrace));
            }
        }
    public override bool Save()
    {
        if (rbCustomBusinessHours.Checked && (timeSLAStart.SelectedDate == null || timeSLAEnd.SelectedDate == null))
        {
            string script = "alert('Please select both the SLA Day Start and End.');";
            string name   = "ValidationAlert";
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), name + "_function", "function " + name + "(){" + script + "Sys.Application.remove_load(" + name + ");}", true);
            ScriptManager.RegisterStartupScript(this, typeof(Page), name, "Sys.Application.add_load(" + name + ");", true);
            DialogResult = "";
            return(false);
        }

        SlaTrigger  trigger;
        SlaTriggers triggers = new SlaTriggers(UserSession.LoginUser);

        if (_slaTriggerID < 0)
        {
            trigger              = triggers.AddNewSlaTrigger();
            trigger.SlaLevelID   = _slaLevelID;
            trigger.TicketTypeID = _ticketTypeID;
        }
        else
        {
            trigger = SlaTriggers.GetSlaTrigger(UserSession.LoginUser, _slaTriggerID);
            if (trigger == null)
            {
                return(false);
            }
        }

        trigger.TicketSeverityID       = int.Parse(cmbSeverities.SelectedValue);
        trigger.NotifyGroupOnViolation = cbGroupViolations.Checked;
        trigger.NotifyGroupOnWarning   = cbGroupWarnings.Checked;
        trigger.NotifyUserOnViolation  = cbUserViolations.Checked;
        trigger.NotifyUserOnWarning    = cbUserWarnings.Checked;
        trigger.NoBusinessHours        = rbNoBusinessHours.Checked;
        trigger.UseBusinessHours       = rbBusinessHours.Checked;
        trigger.PauseOnHoliday         = cbPauseOnOrganizationHolidays.Checked;
        trigger.DayStart = null;
        trigger.DayEnd   = null;
        trigger.TimeZone = cbTimeZones.SelectedValue;
        UserSession.LoginUser.TimeZoneInfo = null;

        try
        {
            TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(trigger.TimeZone);

            if (timeSLAStart.SelectedDate != null)
            {
                trigger.DayStart = TimeZoneInfo.ConvertTimeToUtc((DateTime)timeSLAStart.SelectedDate, timeZoneInfo);
            }

            if (timeSLAEnd.SelectedDate != null)
            {
                trigger.DayEnd = TimeZoneInfo.ConvertTimeToUtc((DateTime)timeSLAEnd.SelectedDate, timeZoneInfo);
            }
        }
        catch (Exception ex)
        {
        }

        int weekdays = 0;

        AddSLADay(ref weekdays, DayOfWeek.Sunday, cbSLASunday.Checked);
        AddSLADay(ref weekdays, DayOfWeek.Monday, cbSLAMonday.Checked);
        AddSLADay(ref weekdays, DayOfWeek.Tuesday, cbSLATuesday.Checked);
        AddSLADay(ref weekdays, DayOfWeek.Wednesday, cbSLAWednesday.Checked);
        AddSLADay(ref weekdays, DayOfWeek.Thursday, cbSLAThursday.Checked);
        AddSLADay(ref weekdays, DayOfWeek.Friday, cbSLAFriday.Checked);
        AddSLADay(ref weekdays, DayOfWeek.Saturday, cbSLASaturday.Checked);
        trigger.Weekdays = weekdays;

        List <string> daysToPause = new List <string>();

        if (!String.IsNullOrEmpty(DaysToPauseHidden.Value))
        {
            daysToPause = DaysToPauseHidden.Value.Split(',').Distinct().Where(p => !string.IsNullOrEmpty(p)).ToList();
        }

        SlaPausedDays slaPausedDays = new SlaPausedDays(UserSession.LoginUser);

        if (_slaTriggerID > 0)
        {
            slaPausedDays.LoadByTriggerID(trigger.SlaTriggerID);

            if (slaPausedDays != null && slaPausedDays.Any())
            {
                slaPausedDays.DeleteAll();
                slaPausedDays.Save();
            }

            slaPausedDays = new SlaPausedDays(UserSession.LoginUser);
        }

        int value = numWarning.Value == null ? 0 : (int)numWarning.Value;

        if (rbWarningDay.Checked)
        {
            trigger.WarningTime = value * 24 * 60;
        }
        else if (rbWarningHour.Checked)
        {
            trigger.WarningTime = value * 60;
        }
        else
        {
            trigger.WarningTime = value;
        }

        value = numInitial.Value == null ? 0 : (int)numInitial.Value;
        if (rbInitialDay.Checked)
        {
            trigger.TimeInitialResponse = value * 24 * 60;
        }
        else if (rbInitialHour.Checked)
        {
            trigger.TimeInitialResponse = value * 60;
        }
        else
        {
            trigger.TimeInitialResponse = value;
        }

        value = numAction.Value == null ? 0 : (int)numAction.Value;
        if (rbActionDay.Checked)
        {
            trigger.TimeLastAction = value * 24 * 60;
        }
        else if (rbActionHour.Checked)
        {
            trigger.TimeLastAction = value * 60;
        }
        else
        {
            trigger.TimeLastAction = value;
        }

        value = numClosed.Value == null ? 0 : (int)numClosed.Value;
        if (rbClosedDay.Checked)
        {
            trigger.TimeToClose = value * 24 * 60;
        }
        else if (rbClosedHour.Checked)
        {
            trigger.TimeToClose = value * 60;
        }
        else
        {
            trigger.TimeToClose = value;
        }

        try
        {
            trigger.Collection.Save();

            foreach (string day in daysToPause)
            {
                string decodedDay = System.Net.WebUtility.HtmlDecode(day);
                decodedDay = System.Text.RegularExpressions.Regex.Replace(decodedDay, @"[^\u0000-\u007F]+", string.Empty);
                decodedDay = System.Text.RegularExpressions.Regex.Replace(decodedDay, "[^.0-9/\\s]", "");

                DateTime dayToPause = new DateTime();
                Settings.UserDB.WriteString("SlaTriggerDayToPauseDebug", day + " => " + decodedDay);

                if (DateTime.TryParse(decodedDay, new CultureInfo("en-US"), DateTimeStyles.None, out dayToPause))
                {
                    SlaPausedDay slaPausedDay = slaPausedDays.AddNewSlaPausedDay();
                    slaPausedDay.SlaTriggerId = trigger.SlaTriggerID;
                    slaPausedDay.DateToPause  = dayToPause.ToUniversalTime();
                    slaPausedDay.Collection.Save();
                    Settings.UserDB.WriteString("SlaTriggerDayToPauseParseDebug", "us-US: " + dayToPause.ToShortDateString());
                }
                else if (DateTime.TryParse(decodedDay, TSAuthentication.GetLoginUser().CultureInfo, DateTimeStyles.None, out dayToPause))
                {
                    SlaPausedDay slaPausedDay = slaPausedDays.AddNewSlaPausedDay();
                    slaPausedDay.SlaTriggerId = trigger.SlaTriggerID;
                    slaPausedDay.DateToPause  = dayToPause.ToUniversalTime();
                    slaPausedDay.Collection.Save();
                    Settings.UserDB.WriteString("SlaTriggerDayToPauseParseDebug", TSAuthentication.GetLoginUser().CultureInfo + ": " + dayToPause.ToShortDateString());
                }
                else
                {
                    Settings.UserDB.WriteString("SlaTriggerDayToPauseParseDebug", "none");
                }
            }

            Settings.UserDB.WriteInt("SlaTriggerWarningTime", trigger.WarningTime);
            Settings.UserDB.WriteInt("SlaTriggerInitialResponseTime", trigger.TimeInitialResponse);
            Settings.UserDB.WriteInt("SlaTriggerLastActionTime", trigger.TimeLastAction);
            Settings.UserDB.WriteInt("SlaTriggerClosedTime", trigger.TimeToClose);
            Settings.UserDB.WriteBool("SlaTriggerGroupViolations", cbGroupViolations.Checked);
            Settings.UserDB.WriteBool("SlaTriggerGroupWarnings", cbGroupWarnings.Checked);
            Settings.UserDB.WriteBool("SlaTriggerUserViolations", cbUserViolations.Checked);
            Settings.UserDB.WriteBool("SlaTriggerUserWarnings", cbUserWarnings.Checked);
            Settings.UserDB.WriteBool("SlaTriggerNoBusinessHours", rbNoBusinessHours.Checked);
            Settings.UserDB.WriteBool("SlaTriggerUseBusinessHours", rbBusinessHours.Checked);
            Settings.UserDB.WriteBool("SlaTriggerPauseOnOrganizationHolidays", cbPauseOnOrganizationHolidays.Checked);

            DialogResult = trigger.SlaTriggerID.ToString();
        }
        catch (System.Data.SqlClient.SqlException sqlEx)
        {
            if (sqlEx.Message.Contains("duplicate key") && sqlEx.Message.Contains("SlaTriggers"))
            {
                ExceptionLogs.LogException(TSAuthentication.GetLoginUser(), sqlEx, "SlaTrigger.Save");
            }
            else
            {
                throw sqlEx;
            }
        }

        return(true);
    }
    protected override void OnLoad(EventArgs e)
    {
        if (!UserSession.CurrentUser.IsSystemAdmin)
        {
            Response.Write("Invalid Request");
            Response.End();
            return;
        }


        base.OnLoad(e);

        if (Request["SlaTriggerID"] != null)
        {
            _slaTriggerID = int.Parse(Request["SlaTriggerID"]);
        }
        if (Request["SlaLevelID"] != null)
        {
            _slaLevelID = int.Parse(Request["SlaLevelID"]);
        }
        if (Request["TicketTypeID"] != null)
        {
            _ticketTypeID = int.Parse(Request["TicketTypeID"]);
        }

        if (!IsPostBack)
        {
            LoadTimeZones();
            SetTimes(Settings.UserDB.ReadInt("SlaTriggerWarningTime", 1440),
                     Settings.UserDB.ReadInt("SlaTriggerInitialResponseTime", 60),
                     Settings.UserDB.ReadInt("SlaTriggerLastActionTime", 60),
                     Settings.UserDB.ReadInt("SlaTriggerClosedTime", 60));

            cbGroupViolations.Checked             = Settings.UserDB.ReadBool("SlaTriggerGroupViolations", true);
            cbGroupWarnings.Checked               = Settings.UserDB.ReadBool("SlaTriggerGroupWarnings", true);
            cbUserViolations.Checked              = Settings.UserDB.ReadBool("SlaTriggerUserViolations", true);
            cbUserWarnings.Checked                = Settings.UserDB.ReadBool("SlaTriggerUserWarnings", true);
            rbBusinessHours.Checked               = Settings.UserDB.ReadBool("SlaTriggerUseBusinessHours", true);
            rbCustomBusinessHours.Checked         = !rbBusinessHours.Checked;
            cbPauseOnOrganizationHolidays.Checked = Settings.UserDB.ReadBool("SlaTriggerPauseOnOrganizationHolidays", true);
            daysToPauseList.Attributes.Add("onkeydown", "DeleteSelectedItems(event);");
        }

        if (_slaTriggerID > -1)
        {
            _trigger = SlaTriggers.GetSlaTrigger(UserSession.LoginUser, _slaTriggerID);
            if (_trigger == null || SlaLevels.GetSlaLevel(UserSession.LoginUser, _trigger.SlaLevelID).OrganizationID != UserSession.LoginUser.OrganizationID)
            {
                Response.Write("Invalid Request");
                Response.End();
                return;
            }
            _slaLevelID   = _trigger.SlaLevelID;
            _ticketTypeID = _trigger.TicketTypeID;

            if (!IsPostBack)
            {
                LoadTrigger(_trigger);
            }
        }
        else
        {
            DisableEnableCustomBusinessHours(rbBusinessHours.Checked, rbNoBusinessHours.Checked);
        }

        SlaLevel   level = SlaLevels.GetSlaLevel(UserSession.LoginUser, _slaLevelID);
        TicketType type  = TicketTypes.GetTicketType(UserSession.LoginUser, _ticketTypeID);

        if (level == null || type == null || level.OrganizationID != UserSession.LoginUser.OrganizationID || type.OrganizationID != UserSession.LoginUser.OrganizationID)
        {
            Response.Write("Invalid Request");
            Response.End();
            return;
        }

        lblSla.Text        = level.Name;
        lblTicketType.Text = type.Name;

        if (!IsPostBack)
        {
            LoadSeverities();
        }
    }