Example #1
0
        private static void CreateAndSaveOutboundRule(PhoneSystem ps, Tenant tenant, OutBoundRuleDetails outbound_rule_to_create)
        {
            OutboundRule[] rules = tenant.GetOutboundRules();
            int            last_maximum_priority = 0;



            /* Determine the highest priority outbound rule in the system at the moment.
             * While we're here, might as well see if this new rule exists or not...there are allowed to be duplicates though */
            foreach (OutboundRule rule in rules)
            {
                if (rule.Priority > last_maximum_priority)
                {
                    last_maximum_priority = rule.Priority;
                }

                if (rule.Name.Equals(outbound_rule_to_create.Name) == true)
                {
                    if (isDebug)
                    {
                        LogMessage("Duplicate rule found, " + rule.Name, Severity.Warn);
                    }
                }

                if (print_rules == true)
                {
                    LogMessage(rule.Name, Severity.Info);
                }
            }

            if (tenant != null)
            {
                OutboundRule outbound_rule = null;
                outbound_rule = tenant.CreateOutboundRule();

                if (outbound_rule != null)
                {
                    /* Populate the outbound rule, using defaults where non is explicity set */

                    outbound_rule.Name               = String.IsNullOrEmpty(outbound_rule_to_create.Name) ? outbound_rule.Name : outbound_rule_to_create.Name;
                    outbound_rule.Prefix             = String.IsNullOrEmpty(outbound_rule_to_create.Prefix) ? outbound_rule.Prefix : outbound_rule_to_create.Prefix;
                    outbound_rule.NumberLengthRanges = String.IsNullOrEmpty(outbound_rule_to_create.Calls_to_numbers_with_a_length_of) ? outbound_rule.NumberLengthRanges : outbound_rule_to_create.Calls_to_numbers_with_a_length_of;

                    /* Get a list of gateways the system is aware of */

                    Gateway[] gateways = ps.GetGateways();
                    bool      found_user_specified_gateway_in_system = false;
                    if (gateways.Length > 0)
                    {
                        foreach (Gateway gw in gateways)
                        {
                            if (print_gateways)
                            {
                                LogMessage(String.Format("GATEWAY {0}", gw.Name), Severity.Info);
                            }

                            /* GetAppPath the gateways that the user wants to add to this outbound_rule_to_create rule */

                            if (gw.Name.Equals(outbound_rule_to_create.Outbound_route[0].name) == true)
                            {
                                outbound_rule.OutboundRoutes[0].Gateway = gw;
                                found_user_specified_gateway_in_system  = true;
                            }
                        }
                        outbound_rule.OutboundRoutes[0].Prepend     = outbound_rule_to_create.Outbound_route[0].prepend;
                        outbound_rule.OutboundRoutes[0].StripDigits = outbound_rule_to_create.Outbound_route[0].strip_count;
                    }
                    else
                    {
                        LogMessage("No gateways are defined in the system, no specifying one in the outbound rule", Severity.Warn);
                    }

                    /*Use default gateway if one is available and we cant find the use specified gateway name*/
                    if (!found_user_specified_gateway_in_system && gateways.Length > 0)
                    {
                        outbound_rule.OutboundRoutes[0].Gateway = gateways[0];
                        LogMessage("Using default gateway as route for outbound rule - route not found or not provided.", Severity.Warn);
                    }



                    if (outbound_rule_to_create.External_lines != null)
                    {
                        if (outbound_rule_to_create.External_lines.Length > 0)
                        {
                            outbound_rule.ExternalLines = outbound_rule_to_create.External_lines;
                        }
                    }

                    if (String.IsNullOrEmpty(outbound_rule_to_create.ExtensionRange) == false)
                    {
                        string[] ranges = outbound_rule_to_create.ExtensionRange.Split(',');
                        //allocate space for extensio nranges
                        DNRange[] made_ranges = new DNRange[ranges.Length];

                        for (int i = 0; i < ranges.Length; i++)
                        {
                            made_ranges[i] = outbound_rule.CreateDNRange();
                            if (ranges[i].Contains("-") == true)
                            {
                                string[] toAndFrom = ranges[i].Split('-');
                                made_ranges[i].From = toAndFrom[0];
                                made_ranges[i].To   = toAndFrom[1];
                            }
                            else
                            {
                                // no range just single extension
                                made_ranges[i].From = ranges[i];
                                made_ranges[i].To   = ranges[i];
                            }
                        }
                        outbound_rule.DNRanges = made_ranges;
                    }

                    if (outbound_rule_to_create.DNGroups != null)
                    {
                        if (outbound_rule_to_create.DNGroups.Length > 0)
                        {
                            outbound_rule.DNGroups = outbound_rule_to_create.DNGroups;
                        }
                    }

                    /* NB - ensure that the priority of the successive Outbound rules are at consecutive multiples of 5 larger than the highest priority in the system */
                    outbound_rule.Priority = last_maximum_priority + 5; //this is a static variable because we cannot determine which order the last outbound rule was saved in when calling GetOutBoundRules
                    outbound_rule.Save();                               // Save it to the system
                    tenant.Refresh();                                   // This is so that the next call to the Tenant Object's GetOutboundRules() contains reference to the rule we just created.
                    LogMessage("Saved outbound rule, " + outbound_rule.Name, Severity.Info);
                }
                else
                {
                    LogMessage("Could not create/allocate an Outbound rule template to use to create a new rule.", Severity.Critical);
                }
            }
            else
            {
                LogMessage("Tenant " + tenant.Name + " is not found but is required.", Severity.Critical);
            }
        }
        public void Run(params string[] args)
        {
            PhoneSystem ps     = PhoneSystem.Root;
            int         showid = 0;

            switch (args[1])
            {
            case "create":
            case "update":
            {
                OutboundRule rule = args[1] == "create" ? ps.GetTenant().CreateOutboundRule() : ps.GetByID <OutboundRule>(int.Parse(args[2]));
                foreach (var paramdata in args.Skip(3).Select(x => x.Split('=')))
                {
                    var paramname  = paramdata[0];
                    var paramvalue = paramdata[1];
                    switch (paramname)
                    {
                    case "PREFIX":
                        rule.Prefix = paramvalue;
                        break;

                    case "PRIORITY":
                        rule.Priority = int.Parse(paramvalue);
                        break;

                    case "NUMBERLENGTH":
                        rule.NumberLengthRanges = paramvalue;
                        break;

                    case "DNRENGES":
                        rule.DNRanges = paramvalue.Split(',').Select(x => x.Split('-')).Select(x => { var range = rule.CreateDNRange(); range.From = x[0]; range.To = x.Length > 1 ? x[1] : x[0]; return(range); }).ToArray();
                        break;

                    case "GROUPS":
                        rule.DNGroups = paramvalue.Split(',').Where(x => !string.IsNullOrEmpty(x)).Select(x => ps.GetGroupByName(x)).ToArray();
                        break;

                    case "NAME":
                        using (var existing = ps.GetAll <OutboundRule>().GetDisposer(x => x.Name == paramvalue).ExtractFirstOrDefault())
                        {
                            if (existing != null)
                            {
                                throw new ArgumentException($"Outbound rule where NAME='{paramvalue}' already exists - {existing}");
                            }
                        }
                        rule.Name = paramvalue;
                        break;

                    default:
                        if (paramname.StartsWith("ROUTE"))
                        {
                            var routenumber = int.Parse(paramname.Substring(5));
                            if (routenumber < 1 || routenumber > 5)
                            {
                                throw new ArgumentOutOfRangeException("Only 5 routes [1..5] are allowed");
                            }
                            if (routenumber > rule.NumberOfRoutes)
                            {
                                rule.NumberOfRoutes = routenumber;
                            }
                            var routeindex = routenumber - 1;
                            var routeParam = paramvalue.Split('.');

                            rule[routeindex].StripDigits = byte.Parse(routeParam[0]);
                            rule[routeindex].Prepend     = routeParam[1];
                            var gwid = routeParam.Skip(2).FirstOrDefault();
                            rule[routeindex].Gateway = string.IsNullOrEmpty(gwid) ? null : (ps.GetByID <Gateway>(int.Parse(gwid)) ?? throw new ArgumentException($"Gateway.{gwid} is not found"));
                        }
                        else
                        {
                            throw new ArgumentException($"Unknown parameter {paramname}");
                        }
                        break;
                    }
                }
                rule.Save();
            }
            break;

            case "delete":
                ps.GetByID <OutboundRule>(int.Parse(args[2])).Delete();
                return;

            case "gateways":
                Console.WriteLine($"{string.Join("\n", ps.GetAll<Gateway>().Select(x => $"{x}"))}");
                return;

            case "show":
                break;

            default:
                throw new ArgumentException("Invalid action name");
            }
            using (var outboundrules = (showid != 0 ? new OutboundRule[] { ps.GetByID <OutboundRule>(showid) } : ps.GetAll <OutboundRule>().ToArray()).GetDisposer())
            {
                var first = outboundrules.First();
                foreach (var or in outboundrules)
                {
                    Console.WriteLine($"{or}");
                    Console.WriteLine($"\tNAME={or.Name}");
                    Console.WriteLine($"\tPREFIX={or.Prefix}");
                    Console.WriteLine($"\tPRIORITY={or.Priority}");
                    Console.WriteLine($"\tNUMBERLENGTH={or.NumberLengthRanges}");
                    Console.WriteLine($"\tGROUPS={string.Join(",", or.DNGroups.Select(x => x.Name))}");
                    Console.WriteLine($"\tDNRANGES={string.Join(",", or.DNRanges.Select(x => $"{x.From }-{x.To}"))}");
                    int i = 0;
                    Console.WriteLine($"\t{string.Join("\n\t", or.Select(x => $"ROUTE{++i}={x}"))}");
                }
            }
        }