Пример #1
0
        public void TestGetCustomerAccountByNumber()
        {
            string accountNumber = "000111222";

            try
            {
                var customerAccount = new CustomerAccount()
                {
                    ID          = Guid.NewGuid().ToString(), AccountName = accountNumber, Owner = "aaron", RatePlan = 1,
                    AccountCode = "AC" + accountNumber, AccountNumber = accountNumber, Inserted = DateTime.UtcNow.ToString("o")
                };

                using (var db = new SIPSorceryEntities())
                {
                    db.CustomerAccounts.Add(customerAccount);
                    db.SaveChanges();
                }

                CustomerAccountDataLayer customerAccountDataLayer = new CustomerAccountDataLayer();
                var checkCustomerAccount = customerAccountDataLayer.Get("aaron", accountNumber);

                Assert.IsNotNull(checkCustomerAccount);
                Assert.AreEqual(customerAccount.ID, checkCustomerAccount.ID);
            }
            finally
            {
                TestHelper.ExecuteQuery("delete from customeraccount where accountnumber = '" + accountNumber + "'");
            }
        }
 public List <SIPDialplanLookup> GetLookups(string dialplanName)
 {
     try
     {
         using (var ssEntities = new SIPSorceryEntities())
         {
             if (!dialplanName.IsNullOrBlank())
             {
                 return((from lookup in ssEntities.SIPDialplanLookups
                         join dialplan in ssEntities.SIPDialPlans on lookup.DialPlanID equals dialplan.ID
                         where lookup.Owner == m_owner && dialplan.DialPlanName.Contains(dialplanName)
                         select lookup).ToList());
             }
             else
             {
                 return((from lookup in ssEntities.SIPDialplanLookups
                         where lookup.Owner == m_owner
                         select lookup).ToList());
             }
         }
     }
     catch (Exception excp)
     {
         logger.Error("Exception GetLookups. " + excp.Message);
         return(null);
     }
 }
Пример #3
0
 public static void ExecuteQuery(string query)
 {
     using (var sipSorceryEntities = new SIPSorceryEntities())
     {
         sipSorceryEntities.Database.ExecuteSqlCommand(query);
     }
 }
 public SIPDialplanOption GetOptions(string dialplanName)
 {
     try
     {
         using (var ssEntities = new SIPSorceryEntities())
         {
             if (!dialplanName.IsNullOrBlank())
             {
                 return((from option in ssEntities.SIPDialplanOptions
                         join dialplan in ssEntities.SIPDialPlans on option.DialPlanID equals dialplan.ID
                         where option.Owner == m_owner && dialplan.DialPlanName == dialplanName
                         select option).FirstOrDefault());
             }
             else
             {
                 return((from option in ssEntities.SIPDialplanOptions
                         where option.Owner == m_owner
                         select option).FirstOrDefault());
             }
         }
     }
     catch (Exception excp)
     {
         logger.Error("Exception GetOptions. " + excp.Message);
         return(null);
     }
 }
Пример #5
0
 public static void ExecuteQuery(string query)
 {
     using (var sipSorceryEntities = new SIPSorceryEntities())
     {
         sipSorceryEntities.ExecuteStoreCommand(query, null);
     }
 }
 public Dictionary <string, SIPDialplanProvider> GetProviders(string dialplanName)
 {
     try
     {
         using (var ssEntities = new SIPSorceryEntities())
         {
             if (!dialplanName.IsNullOrBlank())
             {
                 return((from provider in ssEntities.SIPDialplanProviders
                         join dialplan in ssEntities.SIPDialPlans on provider.DialPlanID equals dialplan.ID
                         where provider.Owner == m_owner && dialplan.DialPlanName.Contains(dialplanName)
                         select provider).ToDictionary(x => x.ProviderName));
             }
             else
             {
                 return((from provider in ssEntities.SIPDialplanProviders
                         where provider.Owner == m_owner
                         select provider).ToDictionary(x => x.ProviderName));
             }
         }
     }
     catch (Exception excp)
     {
         logger.Error("Exception GetProviders. " + excp.Message);
         return(null);
     }
 }
        public void TestGetCustomerAccountByNumber()
        {
            string accountNumber = "000111222";

            try
            {
                var customerAccount = new CustomerAccount() {
                    ID = Guid.NewGuid().ToString(), AccountName = accountNumber, Owner = "aaron", RatePlan = 1,
                    AccountCode = "AC" + accountNumber, AccountNumber = accountNumber, Inserted = DateTime.UtcNow.ToString("o") };

                using (var db = new SIPSorceryEntities())
                {
                    db.CustomerAccounts.AddObject(customerAccount);
                    db.SaveChanges();
                }

                CustomerAccountDataLayer customerAccountDataLayer = new CustomerAccountDataLayer();
                var checkCustomerAccount = customerAccountDataLayer.Get("aaron", accountNumber);

                Assert.IsNotNull(checkCustomerAccount);
                Assert.AreEqual(customerAccount.ID, checkCustomerAccount.ID);
            }
            finally
            {
                TestHelper.ExecuteQuery("delete from customeraccount where accountnumber = '" + accountNumber + "'");
            }
        }
        public List <SimpleWizardRule> GetSimpleWizardRules(string dialplanName, string callDirection)
        {
            try
            {
                SIPCallDirection callDirn = SIPCallDirection.None;
                Enum.TryParse <SIPCallDirection>(callDirection, out callDirn);

                if (callDirn == SIPCallDirection.None)
                {
                    throw new ApplicationException("The call direction string of " + callDirection + " passed to GetSimpleWizardRules was not recognised.");
                }

                using (var ssEntities = new SIPSorceryEntities())
                {
                    if (!dialplanName.IsNullOrBlank())
                    {
                        string callDirnStr = callDirn.ToString();

                        var rules = (from rule in ssEntities.SimpleWizardRules
                                     join dialplan in ssEntities.SIPDialPlans on rule.DialPlanID equals dialplan.ID
                                     where rule.Owner == m_owner && dialplan.DialPlanName == dialplanName &&
                                     rule.Direction == callDirnStr && !rule.IsDisabled
                                     orderby rule.Priority
                                     select rule).ToList();

                        logger.Debug("Rules count " + rules.Count + ".");

                        return(rules);
                    }
                    else
                    {
                        throw new ApplicationException("The dialplan name must be specified for GetSimpleWizardRules.");
                    }
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception GetSimpleWizardRules. " + excp.Message);
                return(null);
            }
        }
Пример #9
0
        /// <summary>
        /// Monitors the CDRs table for records that are using real-time call control and are within the limit that requires them to
        /// re-reserve credit.
        /// </summary>
        private void MonitorCDRs()
        {
            try
            {
                Thread.CurrentThread.Name = RTCC_THREAD_NAME;

                logger.Debug("RTCC Core Starting Monitor CDRs thread.");

                while (!m_exit)
                {
                    using (var db = new SIPSorceryEntities())
                    {
                        try
                        {
                            // Try and reserve credit on in progress calls.
                            DateTime reservationDue = DateTime.Now.AddSeconds(m_reserveDueSeconds);

                            var rtccReservationDue = (from rtcc in db.RTCCs1.Include("cdr")
                                                      where rtcc.AccountCode != null && rtcc.SecondsReserved != null && rtcc.SecondsReserved > 0 && rtcc.ReservationError == null && rtcc.ReconciliationResult == null &&
                                                      rtcc.cdr.HungupTime == null && rtcc.cdr.AnsweredAt != null && rtcc.cdr.AnsweredStatus >= 200 && rtcc.cdr.AnsweredStatus <= 299 &&
                                                      EntityFunctions.AddSeconds(rtcc.cdr.AnsweredAt, rtcc.SecondsReserved) <= reservationDue
                                                      orderby rtcc.cdr.AnsweredAt
                                                      select rtcc).Take(NUMBER_CDRS_PER_ROUNDTRIP);

                            while (rtccReservationDue.Count() > 0)
                            {
                                foreach (RTCC rtcc in rtccReservationDue)
                                {
                                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.RTCC, SIPMonitorEventTypesEnum.DialPlan, "Reserving credit for call " + rtcc.cdr.Dst + ".", rtcc.cdr.Owner));

                                    // Attempt to re-reserve the next chunk of credit for the call.
                                    m_customerAccountDataLayer.ReserveCredit(m_reservationAmountSeconds, rtcc.ID);
                                }
                            }
                        }
                        //catch (ReflectionTypeLoadException ex)
                        //{
                        //    StringBuilder sb = new StringBuilder();
                        //    foreach (Exception exSub in ex.LoaderExceptions)
                        //    {
                        //        sb.AppendLine(exSub.Message);
                        //        if (exSub is FileNotFoundException)
                        //        {
                        //            FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
                        //            if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                        //            {
                        //                sb.AppendLine("Fusion Log:");
                        //                sb.AppendLine(exFileNotFound.FusionLog);
                        //            }
                        //        }
                        //        sb.AppendLine();
                        //    }
                        //    string errorMessage = sb.ToString();
                        //    logger.Error(errorMessage);
                        //}
                        catch (Exception monitorExcp)
                        {
                            logger.Error("Exception MonitorCDRs Credit Reservation. " + monitorExcp);
                            logger.Error("InnerException MonitorCDRs Credit Reservation. " + monitorExcp.InnerException);
                        }

                        try
                        {
                            // Terminate any calls that have reached their time limit.
                            DateTime now = DateTime.Now;
                            var      rtccTerminationDue = (from rtcc in db.RTCCs1.Include("cdr")
                                                           where !rtcc.IsHangingUp && rtcc.AccountCode != null && rtcc.cdr.HungupTime == null && rtcc.cdr.AnsweredAt != null && rtcc.SecondsReserved != null &&
                                                           rtcc.cdr.AnsweredStatus >= 200 && rtcc.cdr.AnsweredStatus <= 299 && EntityFunctions.AddSeconds(rtcc.cdr.AnsweredAt, rtcc.SecondsReserved) <= now && !rtcc.IsHangingUp &&
                                                           rtcc.ReconciliationResult == null
                                                           orderby rtcc.cdr.AnsweredAt
                                                           select rtcc).Take(NUMBER_CDRS_PER_ROUNDTRIP);

                            while (rtccTerminationDue.Count() > 0)
                            {
                                foreach (RTCC rtcc in rtccTerminationDue)
                                {
                                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.RTCC, SIPMonitorEventTypesEnum.DialPlan, "Terminating call due to reservation limit being reached " + rtcc.cdr.Dst + ".", rtcc.cdr.Owner));

                                    m_customerAccountDataLayer.SetCDRIsHangingUp(rtcc.ID);

                                    var dialogue = m_sipDialoguePersistor.Get(x => x.CDRId == rtcc.CDRID, null, 0, 1).FirstOrDefault();
                                    if (dialogue != null)
                                    {
                                        m_sipDialogueManager.CallHungup(dialogue.SIPDialogue, "RTCC time limit reached", true);
                                    }
                                    else
                                    {
                                        Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.RTCC, SIPMonitorEventTypesEnum.Warn, "A dialogue could not be found when terminating a call due to reservation limit being reached.", rtcc.cdr.Owner));
                                    }
                                }
                            }
                        }
                        catch (Exception monitorExcp)
                        {
                            logger.Error("Exception RTCCCore MonitorCDRs Call Termination. " + monitorExcp.Message);
                        }
                    }

                    Thread.Sleep(1000);
                }

                logger.Warn("RTCCCore MonitorCDRs thread stopping.");
            }
            catch (Exception excp)
            {
                logger.Error("Exception RTCCCore MonitorCDRs. " + excp.Message);
            }
        }
Пример #10
0
        /// <summary>
        /// Monitors for CDR's that utilised real-time call control and that have now completed and require credit reconciliation.
        /// </summary>
        private void ReconcileCDRs()
        {
            try
            {
                Thread.CurrentThread.Name = RTCC_THREAD_NAME;

                logger.Debug("RTCC Core Starting Reconcile CDRs thread.");

                while (!m_exit)
                {
                    try
                    {
                        using (var db = new SIPSorceryEntities())
                        {
                            var rtccReconciliationDue = (from rtcc in db.RTCCs1.Include("cdr")
                                                         where rtcc.AccountCode != null && ((rtcc.cdr.AnsweredStatus > 0 && rtcc.cdr.AnsweredStatus < 200) || rtcc.cdr.AnsweredStatus >= 300 || rtcc.cdr.HungupTime != null || rtcc.cdr.HungupReason != null) &&
                                                         rtcc.ReconciliationResult == null && rtcc.PostReconciliationBalance == null && rtcc.Cost > 0
                                                         orderby rtcc.cdr.HungupTime
                                                         select rtcc).Take(NUMBER_CDRS_PER_ROUNDTRIP);

                            while (rtccReconciliationDue.Count() > 0)
                            {
                                foreach (RTCC rtcc in rtccReconciliationDue)
                                {
                                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.RTCC, SIPMonitorEventTypesEnum.DialPlan, "Reconciling credit for call " + rtcc.cdr.Dst + ".", rtcc.cdr.Owner));

                                    logger.Debug("Answered Status=" + rtcc.cdr.AnsweredStatus + ", hungup time=" + rtcc.cdr.HungupTime + ", hungup reason=" + rtcc.cdr.HungupReason + ".");

                                    logger.Debug("Reconciliation starting for CDR " + rtcc.cdr.ID + ", owner " + rtcc.cdr.Owner + ", destination " + rtcc.cdr.Dst + ", duration " + rtcc.cdr.Duration + ", rate " + rtcc.Rate + ", setup cost " +
                                                 rtcc.SetupCost + ", increment seconds " + rtcc.IncrementSeconds + " and reserved credit of " + rtcc.Cost + ".");

                                    decimal callCost = m_customerAccountDataLayer.ReturnUnusedCredit(rtcc.ID);

                                    if (callCost > Decimal.Zero)
                                    {
                                        // Check whether a reconciliation callback needs to be made for this customer account.
                                        var customer = _customerDataLayer.GetForName(rtcc.cdr.Owner);

                                        if (customer.RTCCReconciliationURL.NotNullOrBlank())
                                        {
                                            // Send an async HTTP GET request to the specified URL.
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception monitorExcp)
                    {
                        logger.Error("Exception ReconcileCDRs Monitoring. " + monitorExcp);
                    }

                    Thread.Sleep(1000);
                }

                logger.Warn("RTCCCore ReconcileCDRs thread stopping.");
            }
            catch (Exception excp)
            {
                logger.Error("Exception RTCCCore ReconcileCDRs. " + excp.Message);
                logger.Error("InnerException RTCCCore ReconcileCDRs. " + excp.InnerException);
            }
        }
        static void Main(string[] args)
        {
            bool isConsole = false;

            try
            {
                // Get DateTime.ToString() to use a format ot ToString("o") instead of ToString("G").
                CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
                culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
                culture.DateTimeFormat.LongTimePattern  = "THH:mm:ss.fffffffzzz";
                Thread.CurrentThread.CurrentCulture     = culture;

                m_serverStorageType    = (AppState.GetConfigSetting(m_storageTypeKey) != null) ? StorageTypesConverter.GetStorageType(AppState.GetConfigSetting(m_storageTypeKey)) : StorageTypes.Unknown;
                m_serverStorageConnStr = AppState.GetConfigSetting(m_connStrKey);
                bool monitorCalls = true;

                if (m_serverStorageType == StorageTypes.Unknown || m_serverStorageConnStr.IsNullOrBlank())
                {
                    throw new ApplicationException("The SIP Application Service cannot start with no persistence settings specified.");
                }

                // Need to force the System.Data.Entity assembly to load before a dialplan instantiation. The assembly will fail to load if
                // requested from the Dynamic Language Runtime which is what happens if the first time it's requested is in an IronRuby dialplan.
                using (SIPSorceryEntities appEntities = new SIPSorceryEntities())
                {
                    logger.Debug("Lookups count=" + (from lookup in appEntities.SIPDialplanLookups select lookup).Count() + ", forcing entity framework assemblies to load.");
                }

                //if (args != null && args.Length > 0)
                //{
                isConsole = true;
                Console.WriteLine("SIP App Server starting");
                logger.Debug("SIP App Server Console starting...");

                string sipSocket             = null;
                string callManagerSvcAddress = null;

                foreach (string arg in args)
                {
                    if (arg.StartsWith("-sip:"))
                    {
                        sipSocket = arg.Substring(5);
                    }
                    else if (arg.StartsWith("-cms:"))
                    {
                        callManagerSvcAddress = arg.Substring(5);
                    }
                    else if (arg.StartsWith("-hangupcalls:"))
                    {
                        monitorCalls = Convert.ToBoolean(arg.Substring(13));
                    }
                }

                SIPAppServerDaemon daemon = null;

                if (sipSocket.IsNullOrBlank() || callManagerSvcAddress.IsNullOrBlank())
                {
                    daemon = new SIPAppServerDaemon(m_serverStorageType, m_serverStorageConnStr);
                }
                else
                {
                    daemon = new SIPAppServerDaemon(m_serverStorageType, m_serverStorageConnStr, SIPEndPoint.ParseSIPEndPoint(sipSocket), callManagerSvcAddress, monitorCalls);
                }

                Thread daemonThread = new Thread(new ThreadStart(daemon.Start));
                daemonThread.Start();

                m_proxyUp.WaitOne();
                //}
                //else
                //{
                //    logger.Debug("SIP App Server Windows Service Starting...");
                //    System.ServiceProcess.ServiceBase[] ServicesToRun;
                //    SIPAppServerDaemon daemon = new SIPAppServerDaemon(m_serverStorageType, m_serverStorageConnStr);
                //    ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service(daemon) };
                //    System.ServiceProcess.ServiceBase.Run(ServicesToRun);
                //}
            }
            catch (Exception excp)
            {
                Console.WriteLine("Exception SIP App Server Main. " + excp.Message);

                if (isConsole)
                {
                    Console.WriteLine("press any key to exit...");
                    Console.ReadLine();
                }
            }
        }
Пример #12
0
        public override bool ValidateUser(string username, string password)
        {
            try
            {
                string ipAddress = null;

                if (OperationContext.Current != null)
                {
                    OperationContext              context    = OperationContext.Current;
                    MessageProperties             properties = context.IncomingMessageProperties;
                    RemoteEndpointMessageProperty endpoint   = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
                    if (endpoint != null)
                    {
                        ipAddress = endpoint.Address;
                    }
                }
                else if (HttpContext.Current != null)
                {
                    ipAddress = HttpContext.Current.Request.UserHostAddress;
                }

                if (username.IsNullOrBlank() || password.IsNullOrBlank())
                {
                    logger.Debug("Login from " + ipAddress + " failed, either username or password was not specified.");
                    return(false);
                }
                else
                {
                    using (var sipSorceryEntities = new SIPSorceryEntities())
                    {
                        Customer customer = (from cust in sipSorceryEntities.Customers
                                             where cust.Name.ToLower() == username.ToLower()
                                             select cust).SingleOrDefault();

                        if (customer != null && PasswordHash.Hash(password, customer.Salt) == customer.CustomerPassword)
                        {
                            if (!customer.EmailAddressConfirmed)
                            {
                                throw new ApplicationException("Your email address has not yet been confirmed.");
                            }
                            else if (customer.Suspended)
                            {
                                throw new ApplicationException("Your account is suspended.");
                            }
                            else if (customer.ServiceLevel == CustomerServiceLevels.PremiumPayReqd.ToString() ||
                                     customer.ServiceLevel == CustomerServiceLevels.ProfessionalPayReqd.ToString() ||
                                     customer.ServiceLevel == CustomerServiceLevels.SwitchboardPayReqd.ToString())
                            {
                                var serviceLevel = (CustomerServiceLevels)Enum.Parse(typeof(CustomerServiceLevels), customer.ServiceLevel);
                                throw new PaymentRequiredException(serviceLevel, "Your account requires payment before it can be activated. Please visit the payment page.");
                            }
                            else if (customer.ServiceRenewalDate != null && DateTimeOffset.Parse(customer.ServiceRenewalDate) < DateTimeOffset.Now.AddDays(-1))
                            {
                                throw new PaymentRequiredException(CustomerServiceLevels.RenewalReqd, "Your account is overdue please login to the web site (non-Silverlight login) to renew.");
                            }
                            else
                            {
                                logger.Debug("Login from " + ipAddress + " successful for " + username + ".");
                                return(true);
                            }
                        }
                        else
                        {
                            logger.Debug("Login from " + ipAddress + " failed for " + username + ".");
                            return(false);
                        }
                    }
                }
            }
            catch (ApplicationException)
            {
                throw;
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPSorceryMembershipProvider ValidateUser. " + excp);
                throw new ApplicationException("There was an " + excp.GetType().ToString() + " server error attempting to login.");
            }
        }