private void CompleteTrace() { try { SIPMonitorConsoleEvent traceCompleteEvent = new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Dialplan trace completed at " + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss:fff") + ".", Owner); TraceLog.AppendLine(traceCompleteEvent.EventType + "=> " + traceCompleteEvent.Message); if (!m_traceDirectory.IsNullOrBlank() && Directory.Exists(m_traceDirectory)) { string traceFilename = m_traceDirectory + Owner + "-" + DateTime.Now.ToString("ddMMMyyyyHHmmss") + ".txt"; StreamWriter traceSW = new StreamWriter(traceFilename); traceSW.Write(TraceLog.ToString()); traceSW.Close(); } if (TraceEmailAddress != null) { logger.Debug("Emailing trace to " + TraceEmailAddress + "."); SIPSorcerySMTP.SendEmail(TraceEmailAddress, TRACE_FROM_ADDRESS, TRACE_SUBJECT, TraceLog.ToString()); } } catch (Exception traceExcp) { logger.Error("Exception DialPlanContext CompleteTrace. " + traceExcp.Message); } }
private void ProcessBulkRateFile(string fullPath) { string fileName = Path.GetFileName(fullPath); bool wasSuccess = true; string updateLog = "Commencing bulk rate update of file " + fileName + " at " + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss") + ".\r\n"; string customerEmailAddress = null; Stopwatch sw = new Stopwatch(); sw.Start(); try { logger.Debug("BulkRateFileCreated new file created " + fullPath + "."); // Find the customer that the new file belongs to. string ftpPrefix = fileName.Substring(0, fileName.IndexOf('_')); var customer = m_customerDataLayer.GetForFTPPrefix(ftpPrefix); if (customer == null) { string badFileName = _badUpdateFilesDirectory + DateTime.Now.ToString("ddMMMyyyyHHmmss") + "_" + fileName; logger.Warn("No customer record found with an FTP prefix of " + ftpPrefix + ", moving to bad file directory " + badFileName + "."); File.Move(fullPath, badFileName); } else { string owner = customer.Name; customerEmailAddress = customer.EmailAddress; logger.Debug("Processing bulk rate update file for " + owner + "."); using (FileStream fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { StreamReader sr = new StreamReader(fs); using (var transaction = new TransactionScope()) { bool isFirstLine = true; while (!sr.EndOfStream) { string rateUpdate = sr.ReadLine(); logger.Debug("Processing rate update line: " + rateUpdate); updateLog += rateUpdate.Trim(); if (rateUpdate.NotNullOrBlank()) { if (rateUpdate.Trim() == DELETE_ALL_RATES_KEY && isFirstLine) { logger.Debug("Deleting all rates."); m_rateDataLayer.DeleteAll(owner); updateLog += " <- All rates successfully deleted.\r\n"; } else { string[] rateUpdateFields = rateUpdate.Split(','); string command = rateUpdateFields[0].ToUpper(); switch (command) { case INSERT_COMMAND_KEY: if (rateUpdateFields.Length < 8) { wasSuccess = false; updateLog += " <- Insert command failed, the required number of fields were not present.\r\n"; throw new ApplicationException("A rate insert command was not processed as not enough fields were present. " + rateUpdate); } else { logger.Debug("Inserting new rate for " + rateUpdateFields[1] + "."); var insertRate = new Rate() { Owner = owner, Description = rateUpdateFields[1], Prefix = rateUpdateFields[2], Rate1 = Convert.ToDecimal(rateUpdateFields[3]), SetupCost = Convert.ToDecimal(rateUpdateFields[4]), IncrementSeconds = Convert.ToInt32(rateUpdateFields[5]), RateCode = rateUpdateFields[6], RatePlan = Convert.ToInt32(rateUpdateFields[7]) }; m_rateDataLayer.Add(insertRate); updateLog += " <- Insert command successful.\r\n"; } break; case UPDATE_COMMAND_KEY: if (rateUpdateFields.Length < 9) { wasSuccess = false; updateLog += " <- Update command failed, the required number of fields were not present.\r\n"; throw new ApplicationException("A rate update command was not processed as not enough fields were present. " + rateUpdate); } else { string updateRateID = rateUpdateFields[1]; logger.Debug("Updating rate with ID " + updateRateID + "."); var updateRate = m_rateDataLayer.Get(updateRateID, owner); if (updateRate != null) { updateRate.Description = rateUpdateFields[2]; updateRate.Prefix = rateUpdateFields[3]; updateRate.Rate1 = Convert.ToDecimal(rateUpdateFields[4]); updateRate.SetupCost = Convert.ToDecimal(rateUpdateFields[5]); updateRate.IncrementSeconds = Convert.ToInt32(rateUpdateFields[6]); updateRate.RateCode = rateUpdateFields[7]; updateRate.RatePlan = Convert.ToInt32(rateUpdateFields[8]); m_rateDataLayer.Update(updateRate); updateLog += " <- Update command successful.\r\n"; } else { wasSuccess = false; updateLog += " <- Update command failed, the rate to update could not be found.\r\n"; throw new ApplicationException("The rate to update could not be found."); } } break; case DELETE_COMMAND_KEY: string deleteRateID = rateUpdateFields[1]; logger.Debug("Deleting rate with ID " + deleteRateID + "."); var deleteRate = m_rateDataLayer.Get(deleteRateID, owner); if (deleteRate != null) { m_rateDataLayer.Delete(deleteRate.ID); } else { wasSuccess = false; updateLog += " <- Delete command failed, the rate to delete could not be found.\r\n"; throw new ApplicationException("The rate to delete could not be found."); } break; default: wasSuccess = false; updateLog += " <- Command was not recognised.\r\n"; throw new ApplicationException("Command " + command + " was not recognised, ignoring."); } } isFirstLine = false; } } transaction.Complete(); } } sw.Stop(); updateLog += "Successfully completed bulk rate update of " + fileName + " at " + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss") + " in " + sw.Elapsed.TotalSeconds.ToString("0") + "s."; logger.Debug("Successfully processed bulk rate update file " + fileName + ", moving to processed directory."); File.Move(fullPath, _processedUpdateFilesDirectory + DateTime.Now.ToString("ddMMMyyyyHHmmss") + "_" + fileName); } } catch (Exception excp) { wasSuccess = false; updateLog += " <- Exception " + excp.GetType().ToString() + " " + excp.Message + ".\r\n"; logger.Error("Exception ProcessBulkRateFile. " + excp); try { File.Move(fullPath, _badUpdateFilesDirectory + DateTime.Now.ToString("ddMMMyyyyHHmmss") + "_" + fileName); } catch (Exception moveExcp) { logger.Error("Exception ProcessBulkRateFile moving bad file. " + moveExcp); } } finally { if (customerEmailAddress.NotNullOrBlank()) { try { logger.Debug("Sending bulk rate update result to " + customerEmailAddress + "."); string subject = (wasSuccess) ? "SIP Sorcery Bulk Rate Update Success" : "SIP Sorcery Bulk Rate Update Failure"; SIPSorcerySMTP.SendEmail(customerEmailAddress, EMAIL_FROM_ADDRESS, null, EMAIL_FROM_ADDRESS, subject, updateLog); } catch (Exception sendResultExcp) { logger.Error("Exception ProcessBulkRateFile sending result email. " + sendResultExcp); } } } }
public void CreateCustomer(Customer customer) { try { if (m_inviteCodeRequired && customer.InviteCode == null) { throw new ApplicationException("Sorry new account creations currently require an invite code, please see http://sipsorcery.wordpress.com/new-accounts/."); } else if (m_newCustomersAllowedLimit != 0 && CRMCustomerPersistor.Count(null) >= m_newCustomersAllowedLimit) { // Check whether the number of customers is within the allowed limit. throw new ApplicationException("Sorry new account creations are currently disabled, please see http://sipsorcery.wordpress.com/new-accounts/."); } else { // Check whether the username is already taken. customer.CustomerUsername = customer.CustomerUsername.ToLower(); Customer existingCustomer = CRMCustomerPersistor.Get(c => c.CustomerUsername == customer.CustomerUsername); if (existingCustomer != null) { throw new ApplicationException("The requested username is already in use please try a different one."); } // Check whether the email address is already taken. customer.EmailAddress = customer.EmailAddress.ToLower(); existingCustomer = CRMCustomerPersistor.Get(c => c.EmailAddress == customer.EmailAddress); if (existingCustomer != null) { throw new ApplicationException("The email address is already associated with an account."); } string validationError = Customer.ValidateAndClean(customer); if (validationError != null) { throw new ApplicationException(validationError); } customer.MaxExecutionCount = Customer.DEFAULT_MAXIMUM_EXECUTION_COUNT; customer.APIKey = Crypto.GetRandomByteString(Customer.API_KEY_LENGTH / 2); CRMCustomerPersistor.Add(customer); logger.Debug("New customer record added for " + customer.CustomerUsername + "."); // Create a default dialplan. SIPDialPlan defaultDialPlan = new SIPDialPlan(customer.CustomerUsername, "default", null, "sys.Log(\"hello world\")\n", SIPDialPlanScriptTypesEnum.Ruby); DialPlanPersistor.Add(defaultDialPlan); logger.Debug("Default dialplan added for " + customer.CustomerUsername + "."); // Get default domain name. string defaultDomain = SIPDomainManager.GetDomain("local", true); // Create SIP account. if (SIPAccountPersistor.Get(s => s.SIPUsername == customer.CustomerUsername && s.SIPDomain == defaultDomain) == null) { SIPAccount sipAccount = new SIPAccount(customer.CustomerUsername, defaultDomain, customer.CustomerUsername, customer.CustomerPassword, "default"); SIPAccountPersistor.Add(sipAccount); logger.Debug("SIP account " + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + " added for " + sipAccount.Owner + "."); } else { int attempts = 0; while (attempts < 10) { string testUsername = customer.CustomerUsername + Crypto.GetRandomString(4); if (SIPAccountPersistor.Get(s => s.SIPUsername == testUsername && s.SIPDomain == defaultDomain) == null) { SIPAccount sipAccount = new SIPAccount(customer.CustomerUsername, defaultDomain, testUsername, customer.CustomerPassword, "default"); SIPAccountPersistor.Add(sipAccount); logger.Debug("SIP account " + sipAccount.SIPUsername + "@" + sipAccount.SIPDomain + " added for " + sipAccount.Owner + "."); break; } else { attempts++; } } } if (!m_customerConfirmLink.IsNullOrBlank()) { logger.Debug("Sending new account confirmation email to " + customer.EmailAddress + "."); SIPSorcerySMTP.SendEmail(customer.EmailAddress, NEW_ACCOUNT_EMAIL_FROM_ADDRESS, NEW_ACCOUNT_EMAIL_SUBJECT, String.Format(NEW_ACCOUNT_EMAIL_BODY, customer.FirstName, m_customerConfirmLink, customer.Id)); } else { logger.Debug("Customer confirmation email was not sent as no confirmation link has been set."); } } } catch (Exception excp) { logger.Error("Exception CreateNewCustomer. " + excp.Message); throw; } }