public void TimePatternAllDaysExceptWednesdayDayTest()
        {
            SimpleWizardRule target = new SimpleWizardRule()
            {
                TimePattern = "MTuThFSaSu;00:00-23:59"
            };

            // Wednesday.
            var now = new DateTimeOffset(2011, 11, 23, 14, 28, 0, 0, TimeSpan.Zero);

            Assert.IsFalse(target.IsTimeMatch(now, null));
        }
        public void TimePatternAllDaysIncludedDayTest()
        {
            SimpleWizardRule target = new SimpleWizardRule()
            {
                TimePattern = "MTuWThFSaSu;00:00-23:59"
            };

            // Sunday.
            var now = new DateTimeOffset(2011, 11, 27, 14, 28, 0, 0, TimeSpan.Zero);

            Assert.IsTrue(target.IsTimeMatch(now, null));
        }
 /// <summary>
 /// Sets the content of the UI controls representing command parameter fields based on the specified rule. 
 /// The command parameters mean different things and apply to different controls dependent on the rule's command type.
 /// </summary>
 private void SetUICommandFieldsForRule(SimpleWizardRule rule)
 {
     if (rule.CommandType == SimpleWizardCommandTypes.Dial && m_ruleProvider.Items != null && m_ruleProvider.Items.Count > 0)
     {
         m_ruleCommandString.Text = rule.CommandParameter1;
         if (m_ruleProvider.Items.Any(x => x as string == rule.CommandParameter2))
         {
             // The second command parameter holds the provider.
             m_ruleProvider.SelectedIndex = m_ruleProvider.Items.IndexOf(m_ruleProvider.Items.Single(x => x as string == rule.CommandParameter2));
         }
     }
     else if (rule.CommandType == SimpleWizardCommandTypes.DialAdvanced)
     {
         m_ruleAdvancedDialString.Text = rule.CommandParameter1;
         m_ruleRingDuration.Text = rule.CommandParameter2;
         m_ruleAnswerDuration.Text = rule.CommandParameter3;
     }
     else if (rule.CommandType == SimpleWizardCommandTypes.Reject)
     {
         m_rejectResponseCode.SelectedIndex = m_rejectResponseCode.Items.IndexOf(m_rejectResponseCode.Items.Single(x => ((TextBlock)x).Text.StartsWith(rule.CommandParameter1)));
         m_rejectReason.Text = rule.CommandParameter2;
     }
     else if (rule.CommandType == SimpleWizardCommandTypes.HighriseLookup)
     {
         m_highriseURL.Text = rule.CommandParameter1;
         m_highriseToken.Text = rule.CommandParameter2;
         m_recordHighriseNote.IsChecked = (rule.CommandParameter3 != null) ? Convert.ToBoolean(rule.CommandParameter3) : false;
         m_asyncHighrise.IsChecked = (rule.CommandParameter4 != null) ? Convert.ToBoolean(rule.CommandParameter4) : false;
     }
 }
        /// <summary>
        /// Sets the To header match portions of the simple wizard rule based on the UI values.
        /// </summary>
        private string SetRuleToMatchFields(SimpleWizardRule rule)
        {
            if (m_toMatchType.SelectedValue == null)
            {
                return "A To matching choice must be specified.";
            }
            else
            {
                rule.ToMatchType = ((TextBlock)m_toMatchType.SelectedValue).Text;
            }

            if (rule.SimpleWizardToMatchType == SimpleWizardToMatchTypes.ToSIPAccount)
            {
                rule.ToMatchParameter = m_ruleToAccount.SelectedValue as string;
                if (rule.ToMatchParameter == null || rule.ToMatchParameter == PLEASE_CHOOSE_OPTION)
                {
                    return "A SIP account must be selected for the ToSIPAccount matching choice.";
                }
            }
            else if (rule.SimpleWizardToMatchType == SimpleWizardToMatchTypes.ToSIPProvider)
            {
                rule.ToMatchParameter = m_ruleToProvider.SelectedValue as string;
                if (rule.ToMatchParameter == null || rule.ToMatchParameter == PLEASE_CHOOSE_OPTION)
                {
                    return "A provider must be selected for the ToSIPProvider matching choice.";
                }
            }
            else if (rule.SimpleWizardToMatchType == SimpleWizardToMatchTypes.Regex)
            {
                rule.ToMatchParameter = m_ruleToRegexText.Text;
                if (rule.ToMatchParameter.IsNullOrBlank())
                {
                    return "A regular expression must be entered for the Regex matching choice.";
                }
            }
            else if (rule.SimpleWizardToMatchType == SimpleWizardToMatchTypes.Any)
            {
                rule.ToMatchParameter = null;
            }

            return null;
        }
        private void UpdateRule(SimpleWizardRule rule)
        {
            if (rule.Direction == SIPCallDirection.Out.ToString())
            {
                m_outgoingRulesUpdateControl.SetStatusMessage("Saving...", true);
            }
            else
            {
                m_incomingRulesUpdateControl.SetStatusMessage("Saving...", true);
            }

            m_riaContext.SubmitChanges(UpdateRuleComplete, rule);
        }
 /// <summary>
 /// Create a new SimpleWizardRule object.
 /// </summary>
 /// <param name="id">Initial value of the ID property.</param>
 /// <param name="owner">Initial value of the Owner property.</param>
 /// <param name="dialPlanID">Initial value of the DialPlanID property.</param>
 /// <param name="direction">Initial value of the Direction property.</param>
 /// <param name="priority">Initial value of the Priority property.</param>
 /// <param name="command">Initial value of the Command property.</param>
 /// <param name="commandParameter1">Initial value of the CommandParameter1 property.</param>
 /// <param name="isDisabled">Initial value of the IsDisabled property.</param>
 public static SimpleWizardRule CreateSimpleWizardRule(global::System.String id, global::System.String owner, global::System.String dialPlanID, global::System.String direction, global::System.Decimal priority, global::System.String command, global::System.String commandParameter1, global::System.Boolean isDisabled)
 {
     SimpleWizardRule simpleWizardRule = new SimpleWizardRule();
     simpleWizardRule.ID = id;
     simpleWizardRule.Owner = owner;
     simpleWizardRule.DialPlanID = dialPlanID;
     simpleWizardRule.Direction = direction;
     simpleWizardRule.Priority = priority;
     simpleWizardRule.Command = command;
     simpleWizardRule.CommandParameter1 = commandParameter1;
     simpleWizardRule.IsDisabled = isDisabled;
     return simpleWizardRule;
 }
 public void SimpleWizardRuleConstructorTest()
 {
     SimpleWizardRule target = new SimpleWizardRule();
     Assert.IsNotNull(target);
 }
        private string Validate(SimpleWizardRule rule)
        {
            var validationResults = new List<ValidationResult>();
            var validationContext = new ValidationContext(rule, null, null);
            Validator.TryValidateObject(rule, validationContext, validationResults);
            rule.ValidationErrors.Clear();

            if (validationResults.Count > 0)
            {
                return validationResults[0].ErrorMessage;
            }
            //else
            //{
            //    if (rule.RuleType == SimpleWizardRuleTypes.Regex)
            //    {
            //        try
            //        {
            //            new Regex(rule.Pattern);
            //        }
            //        catch(Exception excp)
            //        {
            //            return "The rule pattern was not recognised as a valid regular expression. " + excp.Message;
            //        }
            //    }
            //
            //}

            return null;
        }
        public void UpdateSimpleWizardRule(string authUser, SimpleWizardRule rule)
        {
            if (authUser.IsNullOrBlank())
            {
                throw new ArgumentException("An authenticated user is required for InsertSimplWizardeDialPlanRule.");
            }

            SimpleWizardRule existingRule = null;

            using (var sipSorceryEntities = new SIPSorceryEntities())
            {
                existingRule = (from ru in sipSorceryEntities.SimpleWizardRules where ru.ID == rule.ID && ru.Owner == authUser.ToLower() select ru).FirstOrDefault();

                if (existingRule == null)
                {
                    throw new ApplicationException("The Simple Wizard rule to update could not be found.");
                }
                else if (existingRule.Owner != authUser.ToLower())
                {
                    throw new ApplicationException("Not authorised to update the Simple Wizard rule.");
                }

                //existingRule.ToProvider = rule.ToProvider;
                //existingRule.ToSIPAccount = rule.ToSIPAccount;
                existingRule.ToMatchType = rule.ToMatchType;
                existingRule.ToMatchParameter = rule.ToMatchParameter;
                existingRule.Description = rule.Description;
                existingRule.Command = rule.Command;
                existingRule.CommandParameter1 = rule.CommandParameter1;
                existingRule.CommandParameter2 = rule.CommandParameter2;
                existingRule.CommandParameter3 = rule.CommandParameter3;
                existingRule.CommandParameter4 = rule.CommandParameter4;
                existingRule.Direction = rule.Direction;
                existingRule.PatternType = rule.PatternType;
                existingRule.Pattern = rule.Pattern;
                existingRule.Priority = rule.Priority;
                existingRule.IsDisabled = rule.IsDisabled;
                existingRule.TimePattern = rule.TimePattern;

                sipSorceryEntities.SaveChanges();
            }
        }
        public void InsertSimpleWizardRule(string authUser, SimpleWizardRule rule)
        {
            if (authUser.IsNullOrBlank())
            {
                throw new ArgumentException("An authenticated user is required for InsertSimplWizardeDialPlanRule.");
            }

            rule.Owner = authUser.ToLower();

            using (var sipSorceryEntities = new SIPSorceryEntities())
            {
                if (rule.EntityState != EntityState.Detached)
                {
                    sipSorceryEntities.ObjectStateManager.ChangeObjectState(rule, EntityState.Added);
                }
                else
                {
                    sipSorceryEntities.SimpleWizardRules.AddObject(rule);
                }

                sipSorceryEntities.SaveChanges();
            }
        }
        /// <summary>
        /// Sets the UI fields based on the supplied rule. If the rule is null the fields are reset ready for a new rule to be added.
        /// </summary>
        public void SetRuleToUpdate(SimpleWizardRule rule)
        {
            if (rule != null)
            {
                m_ruleToUpdate = rule;
                SetStatusMessage(UPDATE_TEXT, false);

                m_rulePatternType.SelectedIndex = m_rulePatternType.Items.IndexOf(m_rulePatternType.Items.Single(x => ((TextBlock)x).Text == rule.PatternType));
                m_rulePattern.Text = rule.Pattern;
                m_ruleCommandType.SelectedIndex = m_ruleCommandType.Items.IndexOf(m_ruleCommandType.Items.Single(x => ((TextBlock)x).Text == rule.Command));
                m_ruleCommandString.Text = rule.CommandParameter1;
                m_ruleDescription.Text = rule.Description;
                m_rulePriority.Text = rule.Priority.ToString();
                m_ruleIsDisabled.IsChecked = rule.IsDisabled;

                SetCommandParameterFieldsForRule(rule);
            }
            else
            {
                m_ruleToUpdate = null;
                SetStatusMessage(ADD_TEXT, false);

                m_ruleIsDisabled.IsChecked = false;
                m_rulePatternType.SelectedIndex = 0;
                m_rulePattern.Text = String.Empty;
                m_ruleCommandString.Text = DEFAULT_DIAL_DESTINATION;
                m_ruleProvider.SelectedIndex = 0;
                m_ruleDescription.Text = String.Empty;
                m_rulePriority.Text = DEFAULT_RULE_PRIORITY.ToString();
                m_ruleAdvancedDialString.Text = String.Empty;
                m_ruleRingDuration.Text = String.Empty;
                m_ruleAnswerDuration.Text = String.Empty;
                m_rejectResponseCode.SelectedIndex = DEFAULT_REJECT_RESPONSE_INDEX;
                m_rejectReason.Text = String.Empty;
                m_ruleCommandType.SelectedIndex = 0;
                HideError.Begin();
            }
        }
        private void Submit(object sender, System.Windows.RoutedEventArgs e)
        {
            decimal priority = DEFAULT_RULE_PRIORITY;
            Decimal.TryParse(m_rulePriority.Text, out priority);

            if (m_ruleToUpdate == null)
            {
                SimpleWizardRule rule = new SimpleWizardRule()
                {
                    ID = Guid.Empty.ToString(),             // Will be set in the manager.
                    Owner = "None",                         // Will be set in the manager.
                    DialPlanID = Guid.Empty.ToString(),     // Will be set in the manager.
                    Direction = SIPCallDirection.Out.ToString(),
                    PatternType = ((TextBlock)m_rulePatternType.SelectedValue).Text,
                    Pattern = m_rulePattern.Text,
                    Command = ((TextBlock)m_ruleCommandType.SelectedValue).Text,
                    Description = m_ruleDescription.Text,
                    Priority = priority,
                    IsDisabled = m_ruleIsDisabled.IsChecked.GetValueOrDefault()
                };

                string commandParameterError = SetRuleCommandParameters(rule);
                if (commandParameterError != null)
                {
                    SetErrorMessage(commandParameterError);
                }
                else if (rule.Pattern.IsNullOrBlank())
                {
                    SetErrorMessage("A pattern must be specified to match the outgoing call.");
                }
                else
                {
                    HideError.Begin();
                    Add(rule);
                }
            }
            else
            {
                m_ruleToUpdate.IsDisabled = m_ruleIsDisabled.IsChecked.GetValueOrDefault();
                m_ruleToUpdate.PatternType = ((TextBlock)m_rulePatternType.SelectedValue).Text;
                m_ruleToUpdate.Pattern = m_rulePattern.Text;
                m_ruleToUpdate.Command = ((TextBlock)m_ruleCommandType.SelectedValue).Text;
                m_ruleToUpdate.Description = m_ruleDescription.Text;
                m_ruleToUpdate.Priority = priority;

                string commandParameterError = SetRuleCommandParameters(m_ruleToUpdate);
                if (commandParameterError != null)
                {
                    SetErrorMessage(commandParameterError);
                }
                else if (m_ruleToUpdate.Pattern.IsNullOrBlank())
                {
                    SetErrorMessage("A pattern must be specified to match the outgoing call.");
                }
                else
                {
                    HideError.Begin();
                    Update(m_ruleToUpdate);
                }
            }
        }
        /// <summary>
        /// Sets the command parameter properties on a rule based on the rule's command type. The rule's command type
        /// dictates which input fields will eb used for each command parameter.
        /// </summary>
        private string SetRuleCommandParameters(SimpleWizardRule rule)
        {
            if (rule.CommandType == SimpleWizardCommandTypes.Dial)
            {
                rule.CommandParameter1 = m_ruleCommandString.Text;
                if (m_ruleProvider.SelectedValue == null || ((SIPProvider)m_ruleProvider.SelectedValue).ProviderName == PLEASE_CHOOSE_OPTION)
                {
                    return "No provider was selected for the Dial command.";
                }
                else
                {
                    rule.CommandParameter2 = ((SIPProvider)m_ruleProvider.SelectedValue).ProviderName;
                }
            }
            else if (rule.CommandType == SimpleWizardCommandTypes.DialAdvanced)
            {
                rule.CommandParameter1 = m_ruleAdvancedDialString.Text;
                rule.CommandParameter2 = m_ruleRingDuration.Text;
                rule.CommandParameter3 = m_ruleAnswerDuration.Text;
            }
            else if (rule.CommandType == SimpleWizardCommandTypes.Reject)
            {
                rule.CommandParameter1 = ((TextBlock)m_rejectResponseCode.SelectedValue).Text.Substring(0, 3);
                rule.CommandParameter2 = m_rejectReason.Text;
            }

            return null;
        }
 /// <summary>
 /// Sets the command parameter fields based on the specified rule. The command parameters mean different 
 /// things and apply to different controls dependent on the rule's command type.
 /// </summary>
 private void SetCommandParameterFieldsForRule(SimpleWizardRule rule)
 {
     if (rule.CommandType == SimpleWizardCommandTypes.Dial && m_ruleProvider.Items != null && m_ruleProvider.Items.Count > 0)
     {
         m_ruleCommandString.Text = rule.CommandParameter1;
         if (m_ruleProvider.Items.Any(x => ((SIPProvider)x).ProviderName == rule.CommandParameter2))
         {
             // The second command parameter holds the provider.
             m_ruleProvider.SelectedIndex = m_ruleProvider.Items.IndexOf(m_ruleProvider.Items.Single(x => ((SIPProvider)x).ProviderName == rule.CommandParameter2));
         }
     }
     else if (rule.CommandType == SimpleWizardCommandTypes.DialAdvanced)
     {
         m_ruleAdvancedDialString.Text = rule.CommandParameter1;
         m_ruleRingDuration.Text = rule.CommandParameter2;
         m_ruleAnswerDuration.Text = rule.CommandParameter3;
     }
     else if (rule.CommandType == SimpleWizardCommandTypes.Reject)
     {
         m_rejectResponseCode.SelectedIndex = m_rejectResponseCode.Items.IndexOf(m_rejectResponseCode.Items.Single(x => ((TextBlock)x).Text.StartsWith(rule.CommandParameter1)));
         m_rejectReason.Text = rule.CommandParameter2;
     }
 }
        /// <summary>
        /// Sets the UI elements based on the To match type and paramters.
        /// </summary>
        /// <param name="rule"></param>
        private void SetUIToMatchFields(SimpleWizardRule rule)
        {
            m_toMatchType.SelectedIndex = m_toMatchType.Items.IndexOf(m_toMatchType.Items.SingleOrDefault(x => ((TextBlock)x).Text == rule.ToMatchType));

            if (rule.SimpleWizardToMatchType == SimpleWizardToMatchTypes.ToSIPAccount)
            {
                m_ruleToAccount.SelectedIndex = m_ruleToAccount.Items.IndexOf(m_ruleToAccount.Items.SingleOrDefault(x => x.ToString() == rule.ToMatchParameter));
            }
            else if (rule.SimpleWizardToMatchType == SimpleWizardToMatchTypes.ToSIPProvider)
            {
                m_ruleToProvider.SelectedIndex = m_ruleToProvider.Items.IndexOf(m_ruleToProvider.Items.SingleOrDefault(x => x.ToString() == rule.ToMatchParameter));
            }
            else if (rule.SimpleWizardToMatchType == SimpleWizardToMatchTypes.Regex)
            {
                m_ruleToRegexText.Text = rule.ToMatchParameter;
            }
        }
        private void Submit(object sender, System.Windows.RoutedEventArgs e)
        {
            decimal priority = DEFAULT_RULE_PRIORITY;
            Decimal.TryParse(m_rulePriority.Text, out priority);

            if (m_ruleToUpdate == null)
            {
                SimpleWizardRule rule = new SimpleWizardRule()
                {
                    ID = Guid.Empty.ToString(),             // Will be set in the manager.
                    Owner = "None",                         // Will be set in the manager.
                    DialPlanID = Guid.Empty.ToString(),     // Will be set in the manager.
                    Direction = SIPCallDirection.In.ToString(),
                    //ToSIPAccount = (m_ruleToSIPAccount.IsChecked.GetValueOrDefault()) ? m_ruleToAccount.SelectedValue as string : null,
                    //RuleTypeID = Enum.Parse(typeof(SimpleWizardRuleTypes), ((TextBlock)m_ruleType.SelectedValue).Text, true).GetHashCode(),
                    Pattern = m_rulePattern.Text,
                    Command = ((TextBlock)m_ruleCommandType.SelectedValue).Text,
                    Description = m_ruleDescription.Text,
                    Priority = priority,
                    IsDisabled = m_ruleIsDisabled.IsChecked.GetValueOrDefault()
                };

                string toFieldsError = SetRuleToMatchFields(rule);
                if (toFieldsError != null)
                {
                    SetErrorMessage(toFieldsError);
                    return;
                }

                string commandParameterError = SetRuleCommandFields(rule);
                if (commandParameterError != null)
                {
                    SetErrorMessage(commandParameterError);
                    return;
                }

                string timePatternError = GetTimePattern(rule);
                if (timePatternError != null)
                {
                    SetErrorMessage(timePatternError);
                    return;
                }

                string validationError = Validate(rule);
                if (validationError != null)
                {
                    SetErrorMessage(validationError);
                }
                else
                {
                    HideErrorSB.Begin();
                    Add(rule);
                }
            }
            else
            {
                //m_ruleToUpdate.ToSIPAccount = (m_ruleToSIPAccount.IsChecked.GetValueOrDefault()) ? m_ruleToAccount.SelectedValue as string : null;
                //m_ruleToUpdate.RuleTypeID = Enum.Parse(typeof(SimpleWizardRuleTypes), ((TextBlock)m_ruleType.SelectedValue).Text, true).GetHashCode();
                m_ruleToUpdate.Pattern = m_rulePattern.Text;
                m_ruleToUpdate.Command = ((TextBlock)m_ruleCommandType.SelectedValue).Text;
                m_ruleToUpdate.Description = m_ruleDescription.Text;
                m_ruleToUpdate.Priority = priority;
                m_ruleToUpdate.IsDisabled = m_ruleIsDisabled.IsChecked.GetValueOrDefault();

                string toFieldsError = SetRuleToMatchFields(m_ruleToUpdate);
                if (toFieldsError != null)
                {
                    SetErrorMessage(toFieldsError);
                    return;
                }

                string commandParameterError = SetRuleCommandFields(m_ruleToUpdate);
                if (commandParameterError != null)
                {
                    SetErrorMessage(commandParameterError);
                    return;
                }

                string timePatternError = GetTimePattern(m_ruleToUpdate);
                if (timePatternError != null)
                {
                    SetErrorMessage(timePatternError);
                    return;
                }

                string validationError = Validate(m_ruleToUpdate);
                if (validationError != null)
                {
                    SetErrorMessage(validationError);
                }
                else
                {
                    HideErrorSB.Begin();
                    Update(m_ruleToUpdate);
                }
            }
        }
        public void CopySIPDialPlan(string authUser, string sipDialPlanID)
        {
            if (authUser.IsNullOrBlank())
            {
                throw new ArgumentException("An authenticated user is required for CopySIPDialPlan.");
            }

            using (var sipSorceryEntities = new SIPSorceryEntities())
            {
                SIPDialPlan existingAccount = (from dp in sipSorceryEntities.SIPDialPlans where dp.ID == sipDialPlanID && dp.Owner.ToLower() == authUser.ToLower() select dp).FirstOrDefault();

                if (existingAccount == null)
                {
                    throw new ApplicationException("The SIP Dial Plan to copy could not be found.");
                }
                else if (existingAccount.Owner != authUser.ToLower())
                {
                    logger.Warn("User " + authUser + " was not authorised to copy dial plan " + existingAccount.DialPlanName + " belonging to " + existingAccount.Owner + ".");
                    throw new ApplicationException("Not authorised to copy the SIP Dial Plan.");
                }
                else if (existingAccount.IsReadOnly)
                {
                    throw new ApplicationException("This Dial Plan is read-only. Please upgrade to a Premium service to enable it.");
                }

                logger.Debug("Copying SIP dialplan " + existingAccount.DialPlanName + " for " + existingAccount.Owner + ".");

                string newDialPlanName = existingAccount.DialPlanName + " Copy";

                if (sipSorceryEntities.SIPDialPlans.Any(x => x.DialPlanName.ToLower() == newDialPlanName.ToLower() && x.Owner.ToLower() == authUser.ToLower()))
                {
                    int attempts = 2;
                    string newNameAttempt = newDialPlanName + " " + attempts.ToString();

                    while (sipSorceryEntities.SIPDialPlans.Any(x => x.DialPlanName.ToLower() == newNameAttempt.ToLower() && x.Owner.ToLower() == authUser.ToLower()) && attempts < 10)
                    {
                        attempts++;
                        newNameAttempt = newDialPlanName + " " + attempts.ToString();
                    }

                    if (attempts < 10)
                    {
                        newDialPlanName = newNameAttempt;
                    }
                    else
                    {
                        throw new ApplicationException("A new dial plan name could not be created for a dial plan copy operation.");
                    }
                }

                SIPDialPlan copy = new SIPDialPlan();
                copy.ID = Guid.NewGuid().ToString();
                copy.Owner = authUser.ToLower();
                copy.AdminMemberId = existingAccount.AdminMemberId;
                copy.Inserted = DateTimeOffset.UtcNow.ToString("o");
                copy.LastUpdate = DateTimeOffset.UtcNow.ToString("o");
                copy.MaxExecutionCount = SIPDialPlan.DEFAULT_MAXIMUM_EXECUTION_COUNT;
                copy.DialPlanName = newDialPlanName;
                copy.DialPlanScript = existingAccount.DialPlanScript;
                copy.ScriptTypeDescription = existingAccount.ScriptTypeDescription;
                copy.AuthorisedApps = existingAccount.AuthorisedApps;
                copy.AcceptNonInvite = existingAccount.AcceptNonInvite;

                sipSorceryEntities.SIPDialPlans.AddObject(copy);
                //sipSorceryEntities.SaveChanges();

                logger.Debug("A new dial plan copy was created for " + existingAccount.DialPlanName + ", new dial plan name " + copy.DialPlanName + ".");

                if (existingAccount.ScriptType == SIPDialPlanScriptTypesEnum.SimpleWizard)
                {
                    var simpleWizardRules = sipSorceryEntities.SimpleWizardRules.Where(x => x.Owner == authUser.ToLower() && x.DialPlanID == existingAccount.ID);

                    if (simpleWizardRules != null && simpleWizardRules.Count() > 0)
                    {
                        foreach (var rule in simpleWizardRules)
                        {
                            SimpleWizardRule copiedRule = new SimpleWizardRule();
                            copiedRule.ID = Guid.NewGuid().ToString();
                            copiedRule.DialPlanID = copy.ID;
                            copiedRule.Owner = authUser.ToLower();
                            copiedRule.ToMatchType = rule.ToMatchType;
                            copiedRule.ToMatchParameter = rule.ToMatchParameter;
                            copiedRule.Description = rule.Description;
                            copiedRule.Command = rule.Command;
                            copiedRule.CommandParameter1 = rule.CommandParameter1;
                            copiedRule.CommandParameter2 = rule.CommandParameter2;
                            copiedRule.CommandParameter3 = rule.CommandParameter3;
                            copiedRule.CommandParameter4 = rule.CommandParameter4;
                            copiedRule.Direction = rule.Direction;
                            copiedRule.PatternType = rule.PatternType;
                            copiedRule.Pattern = rule.Pattern;
                            copiedRule.Priority = rule.Priority;
                            copiedRule.IsDisabled = rule.IsDisabled;
                            copiedRule.TimePattern = rule.TimePattern;
                            copiedRule.ToSIPAccount = rule.ToSIPAccount;
                            copiedRule.ToProvider = rule.ToProvider;

                            sipSorceryEntities.SimpleWizardRules.AddObject(copiedRule);

                            logger.Debug("Copied simple wizard rule priority " + rule.Priority + " to dial plan " + copy.DialPlanName + ".");
                        }
                    }
                }

                sipSorceryEntities.SaveChanges();
            }
        }
        public void TimePatternExcludedDayTest()
        {
            SimpleWizardRule target = new SimpleWizardRule()
            {
                TimePattern = "Tu"
            };

            // Sunday.
            var now = new DateTimeOffset(2011, 11, 27, 14, 28, 0, 0, TimeSpan.Zero);

            Assert.IsFalse(target.IsTimeMatch(now, null));
        }
        public void DeleteSimpleWizardRule(string authUser, SimpleWizardRule rule)
        {
            using (var sipSorceryEntities = new SIPSorceryEntities())
            {
                SimpleWizardRule existingRule = (from ru in sipSorceryEntities.SimpleWizardRules where ru.ID == rule.ID && ru.Owner == authUser.ToLower() select ru).FirstOrDefault();

                if (existingRule == null)
                {
                    throw new ApplicationException("The Simple Wizard Rule to delete could not be found.");
                }
                else if (existingRule.Owner != authUser.ToLower())
                {
                    throw new ApplicationException("Not authorised to delete the Simple Wizard Rule.");
                }

                sipSorceryEntities.SimpleWizardRules.DeleteObject(existingRule);
                sipSorceryEntities.SaveChanges();
            }
        }
        public void SetRuleToUpdate(SimpleWizardRule rule)
        {
            if (rule != null)
            {
                m_ruleToUpdate = rule;
                SetStatusMessage(UPDATE_TEXT, false);

                SetUIToMatchFields(rule);

                m_rulePattern.Text = rule.Pattern;
                m_ruleCommandType.SelectedIndex = m_ruleCommandType.Items.IndexOf(m_ruleCommandType.Items.Single(x => ((TextBlock)x).Text == rule.Command));
                m_ruleDescription.Text = rule.Description;
                m_rulePriority.Text = rule.Priority.ToString();
                m_ruleIsDisabled.IsChecked = rule.IsDisabled;

                if (rule.TimePattern != null)
                {
                    m_ruleWhenSpecificTimes.IsChecked = true;
                    var matchedDays = rule.MatchedDays();
                    m_monCheckbox.IsChecked = matchedDays.Contains(DayOfWeek.Monday);
                    m_tueCheckbox.IsChecked = matchedDays.Contains(DayOfWeek.Tuesday);
                    m_wedCheckbox.IsChecked = matchedDays.Contains(DayOfWeek.Wednesday);
                    m_thuCheckbox.IsChecked = matchedDays.Contains(DayOfWeek.Thursday);
                    m_friCheckbox.IsChecked = matchedDays.Contains(DayOfWeek.Friday);
                    m_satCheckbox.IsChecked = matchedDays.Contains(DayOfWeek.Saturday);
                    m_sunCheckbox.IsChecked = matchedDays.Contains(DayOfWeek.Sunday);
                    m_startTimeHour.Text = rule.GetStartHour().ToString();
                    m_startTimeMin.Text = rule.GetStartMinute().ToString();
                    m_endTimeHour.Text = rule.GetEndHour().ToString();
                    m_endTimeMin.Text = rule.GetEndMinute().ToString();
                }
                else
                {
                    m_ruleWhenAnytime.IsChecked = true;
                }

                SetUICommandFieldsForRule(rule);
            }
            else
            {
                m_ruleToUpdate = null;
                SetStatusMessage(ADD_TEXT, false);

                //m_ruleToSIPAccount.IsChecked = false;
                //m_ruleToChoiceAny.IsChecked = true;
                m_ruleIsDisabled.IsChecked = false;
                m_toMatchType.SelectedIndex = 0;
                m_ruleToAccount.SelectedIndex = 0;
                m_ruleToProvider.SelectedIndex = 0;
                m_ruleToRegexText.Text = String.Empty;
                m_rulePattern.Text = String.Empty;
                m_ruleCommandType.SelectedIndex = 0;
                m_ruleCommandString.Text = DEFAULT_DIAL_DESTINATION;
                m_ruleProvider.SelectedIndex = 0;
                m_ruleDescription.Text = String.Empty;
                m_rulePriority.Text = DEFAULT_RULE_PRIORITY.ToString();
                m_ruleAdvancedDialString.Text = String.Empty;
                m_ruleRingDuration.Text = String.Empty;
                m_ruleAnswerDuration.Text = String.Empty;
                m_rejectResponseCode.SelectedIndex = DEFAULT_REJECT_RESPONSE_INDEX;
                m_rejectReason.Text = String.Empty;
                m_highriseURL.Text = String.Empty;
                m_highriseToken.Text = String.Empty;

                m_ruleCommandString.Text = "${EXTEN}";

                m_ruleWhenAnytime.IsChecked = true;
                m_ruleWhenSpecificTimes.IsChecked = false;
                m_monCheckbox.IsChecked = true;
                m_tueCheckbox.IsChecked = true;
                m_wedCheckbox.IsChecked = true;
                m_thuCheckbox.IsChecked = true;
                m_friCheckbox.IsChecked = true;
                m_satCheckbox.IsChecked = true;
                m_sunCheckbox.IsChecked = true;
                m_startTimeHour.Text = "00";
                m_startTimeMin.Text = "00";
                m_endTimeHour.Text = "23";
                m_endTimeMin.Text = "59";

                HideErrorSB.Begin();
            }
        }
        /// <summary>
        /// Extracts the time pattern from the UI controls that represent a rule that's being applied for a specific time.
        /// </summary>
        /// <returns>A string describing the time pattern.</returns>
        private string GetTimePattern(SimpleWizardRule rule)
        {
            if (!m_ruleWhenSpecificTimes.IsChecked.GetValueOrDefault())
            {
                rule.TimePattern = null;
                return null;
            }
            else
            {
                string timePattern = null;
                timePattern += (m_monCheckbox.IsChecked.GetValueOrDefault()) ? "M" : null;
                timePattern += (m_tueCheckbox.IsChecked.GetValueOrDefault()) ? "Tu" : null;
                timePattern += (m_wedCheckbox.IsChecked.GetValueOrDefault()) ? "W" : null;
                timePattern += (m_thuCheckbox.IsChecked.GetValueOrDefault()) ? "Th" : null;
                timePattern += (m_friCheckbox.IsChecked.GetValueOrDefault()) ? "F" : null;
                timePattern += (m_satCheckbox.IsChecked.GetValueOrDefault()) ? "Sa" : null;
                timePattern += (m_sunCheckbox.IsChecked.GetValueOrDefault()) ? "Su" : null;

                if (timePattern == null)
                {
                    return "At least one day must be checked for a rule using a specific time.";
                }
                else
                {
                    int startTimeHour = 0;
                    int startTimeMin = 0;
                    int endTimeHour = 0;
                    int endTimeMin = 0;

                    if (!Int32.TryParse(m_startTimeHour.Text, out startTimeHour))
                    {
                        return "The start time hour was invalid. Please make sure it contains only numbers.";
                    }
                    if (!Int32.TryParse(m_startTimeMin.Text, out startTimeMin))
                    {
                        return "The start time minute was invalid. Please make sure it contains only numbers.";
                    }
                    if (!Int32.TryParse(m_endTimeHour.Text, out endTimeHour))
                    {
                        return "The end time hour was invalid. Please make sure it contains only numbers.";
                    }
                    if (!Int32.TryParse(m_endTimeMin.Text, out endTimeMin))
                    {
                        return "The end time minute was invalid. Please make sure it contains only numbers.";
                    }

                    if (startTimeHour < 0 || startTimeHour > 23)
                    {
                        return "The start time hour was invalid. Please make sure it is between 0 and 23.";
                    }
                    else if (startTimeMin < 0 || startTimeMin > 59)
                    {
                        return "The start time minute was invalid. Please make sure it is between 0 and 59.";
                    }
                    if (endTimeHour < 0 || endTimeHour > 23)
                    {
                        return "The end time hour was invalid. Please make sure it is between 0 and 23.";
                    }
                    else if (endTimeMin < 0 || endTimeMin > 59)
                    {
                        return "The end time minute was invalid. Please make sure it is between 0 and 59.";
                    }
                    else if ((startTimeHour * 60 + startTimeMin) >= (endTimeHour * 60 + endTimeMin))
                    {
                        return "The start time must be less than the end time.";
                    }

                    rule.TimePattern = timePattern + ";" + startTimeHour.ToString("D2") + ":" + startTimeMin.ToString("D2") + "-" + endTimeHour.ToString("D2") + ":" + endTimeMin.ToString("D2");

                    return null;
                }
            }
        }
        public void TimePatternExcludeByEndTimeTest()
        {
            SimpleWizardRule target = new SimpleWizardRule()
            {
                TimePattern = "MTuWThFSaSu;08:00-17:00"
            };

            var now = new DateTimeOffset(2011, 11, 23, 18, 28, 0, 0, TimeSpan.Zero);

            Assert.IsFalse(target.IsTimeMatch(now, null));
        }
        /// <summary>
        /// Sets the value of the rules properties based on the UI controls representing command parameters. The rule's command type
        /// dictates which input fields will be used for each command parameter.
        /// </summary>
        /// <returns>If there is an error parsing the rule parameters an error message otherwise null.</returns>
        private string SetRuleCommandFields(SimpleWizardRule rule)
        {
            if (rule.CommandType == SimpleWizardCommandTypes.Dial)
            {
                rule.CommandParameter1 = m_ruleCommandString.Text ?? "${EXTEN}";
                if (m_ruleProvider.SelectedValue == null || m_ruleProvider.SelectedValue as string == PLEASE_CHOOSE_OPTION)
                {
                    return "No provider was selected for the Dial command.";
                }
                else
                {
                    rule.CommandParameter2 = m_ruleProvider.SelectedValue as string;
                }
            }
            else if (rule.CommandType == SimpleWizardCommandTypes.DialAdvanced)
            {
                rule.CommandParameter1 = m_ruleAdvancedDialString.Text;
                rule.CommandParameter2 = m_ruleRingDuration.Text;
                rule.CommandParameter3 = m_ruleAnswerDuration.Text;
            }
            else if (rule.CommandType == SimpleWizardCommandTypes.Reject)
            {
                rule.CommandParameter1 = ((TextBlock)m_rejectResponseCode.SelectedValue).Text.Substring(0, 3);
                rule.CommandParameter2 = m_rejectReason.Text;
            }
            else if (rule.CommandType == SimpleWizardCommandTypes.HighriseLookup)
            {
                rule.CommandParameter1 = m_highriseURL.Text;
                rule.CommandParameter2 = m_highriseToken.Text;
                rule.CommandParameter3 = m_recordHighriseNote.IsChecked.ToString();
                rule.CommandParameter4 = m_asyncHighrise.IsChecked.ToString();
            }

            return null;
        }
 /// <summary>
 /// Deprecated Method for adding a new object to the SimpleWizardRules EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddToSimpleWizardRules(SimpleWizardRule simpleWizardRule)
 {
     base.AddObject("SimpleWizardRules", simpleWizardRule);
 }
        private void AddRule(SimpleWizardRule rule)
        {
            rule.ID = Guid.NewGuid().ToString();
            rule.Owner = m_owner;
            rule.DialPlanID = m_dialPlan.ID;

            m_riaContext.SimpleWizardRules.Add(rule);

            if (rule.Direction == SIPCallDirection.Out.ToString())
            {
                m_outgoingRulesUpdateControl.SetStatusMessage("Saving...", true);
            }
            else
            {
                m_incomingRulesUpdateControl.SetStatusMessage("Saving...", true);
            }

            m_riaContext.SubmitChanges(AddRuleComplete, rule);
        }