/// <summary> /// Adds a new rate. /// </summary> /// <param name="rate">The rate record to add.</param> public void Add(Rate rate) { using (var sipSorceryEntities = new SIPSorceryEntities()) { if ((from rt in sipSorceryEntities.Rates where rt.Prefix == rate.Prefix select rt).Any()) { throw new ApplicationException("The rate prefix is already in use."); } else { rate.ID = Guid.NewGuid().ToString(); rate.Inserted = DateTimeOffset.UtcNow.ToString("o"); sipSorceryEntities.Rates.AddObject(rate); sipSorceryEntities.SaveChanges(); } } }
/// <summary> /// Updates an existing rate. /// </summary> /// <param name="rate">The rate to update.</param> public void Update(Rate rate) { using (var db = new SIPSorceryEntities()) { var existingRate = (from ra in db.Rates where ra.ID == rate.ID select ra).SingleOrDefault(); if (existingRate == null) { throw new ApplicationException("The rate to update could not be found"); } else if (existingRate.Owner.ToLower() != rate.Owner.ToLower()) { throw new ApplicationException("You are not authorised to update this rate."); } else { if (existingRate.Prefix != rate.Prefix) { if ((from rt in db.Rates where rt.Prefix == rate.Prefix select rt).Any()) { throw new ApplicationException("The rate prefix is already in use."); } } logger.Debug("Updating rate " + existingRate.Description + " for " + existingRate.Owner + "."); existingRate.Description = rate.Description; existingRate.Prefix = rate.Prefix; existingRate.Rate1 = rate.Rate1; existingRate.RateCode = rate.RateCode; existingRate.SetupCost = rate.SetupCost; existingRate.IncrementSeconds = rate.IncrementSeconds; existingRate.RatePlan = rate.RatePlan; db.SaveChanges(); } } }
public void GetRateTestMethod() { string id = null; try { RateDataLayer rateDataLayer = new RateDataLayer(); var rate = new Rate() {Description = "test", Owner = "aaron", Rate1 = 0.1M, Prefix = "012" }; rateDataLayer.Add(rate); id = rate.ID; var retrievedRate = rateDataLayer.Get("aaron", rate.ID); Assert.IsNotNull(retrievedRate); } finally { if (id != null) { TestHelper.ExecuteQuery("delete from rate where id = '" + id + "'"); } } }
/// <summary> /// Deprecated Method for adding a new object to the Rates EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// </summary> public void AddToRates(Rate rate) { base.AddObject("Rates", rate); }
/// <summary> /// Create a new Rate object. /// </summary> /// <param name="id">Initial value of the ID property.</param> /// <param name="owner">Initial value of the Owner property.</param> /// <param name="description">Initial value of the Description property.</param> /// <param name="prefix">Initial value of the Prefix property.</param> /// <param name="rate1">Initial value of the Rate1 property.</param> /// <param name="inserted">Initial value of the Inserted property.</param> /// <param name="setupCost">Initial value of the SetupCost property.</param> /// <param name="incrementSeconds">Initial value of the IncrementSeconds property.</param> /// <param name="ratePlan">Initial value of the RatePlan property.</param> public static Rate CreateRate(global::System.String id, global::System.String owner, global::System.String description, global::System.String prefix, global::System.Decimal rate1, global::System.String inserted, global::System.Decimal setupCost, global::System.Int32 incrementSeconds, global::System.Int32 ratePlan) { Rate rate = new Rate(); rate.ID = id; rate.Owner = owner; rate.Description = description; rate.Prefix = prefix; rate.Rate1 = rate1; rate.Inserted = inserted; rate.SetupCost = setupCost; rate.IncrementSeconds = incrementSeconds; rate.RatePlan = ratePlan; return rate; }
/// <summary> /// This method acts as a call rate lookup engine. It's very basic and simply matches the call destination /// based on the record that has the longest matching prefix. /// </summary> /// <param name="owner">The owner the call rate lookup is for.</param> /// <param name="rateCode">The rate code for the call. If specified and a matching rate is found it will /// take precedence over the destination.</param> /// <param name="destination">The call desintation the rate lookup is for.</param> /// <returns>If a matching rate is found a greater than 0 decimal value otherwise 0.</returns> public Rate GetRate(string owner, string rateCode, string destination, int ratePlan) { logger.Debug("GetRate for owner " + owner + ", ratecode " + rateCode + " and destination " + destination + "."); if (owner.IsNullOrBlank() || destination.IsNullOrBlank()) { return(null); } using (var db = new SIPSorceryEntities()) { Rate callRate = null; if (rateCode.NotNullOrBlank()) { callRate = (from rate in db.Rates where rate.Owner.ToLower() == owner.ToLower() && rate.RateCode == rateCode && rate.RatePlan == ratePlan select rate).SingleOrDefault(); } if (callRate == null) { callRate = (from rate in db.Rates where rate.Owner.ToLower() == owner.ToLower() && destination.StartsWith(rate.Prefix) && rate.RatePlan == ratePlan orderby rate.Prefix.Length descending select rate).FirstOrDefault(); } // If the rate is still null check for international prefixes. if (callRate == null) { //var customerAccount = db.CustomerAccounts.Where(x => x.AccountCode == accountCode).SingleOrDefault(); //if (customerAccount == null) //{ // logger.Debug("The rate lookup for " + accountCode + " failed due to the no matching accountcode."); // return null; //} string rtccInternationalPrefixes = (from cust in db.Customers where cust.Name.ToLower() == owner.ToLower() select cust.RTCCInternationalPrefixes).Single(); if (rtccInternationalPrefixes.NotNullOrBlank()) { string trimmedDestination = null; string[] prefixes = rtccInternationalPrefixes.Split(','); foreach (string prefix in prefixes.OrderByDescending(x => x.Length)) { if (destination.StartsWith(prefix)) { trimmedDestination = destination.Substring(prefix.Length); logger.Debug("The destination matched international prefix of " + prefix + ", looking up rate for " + trimmedDestination + "."); break; } } if (trimmedDestination != null) { callRate = (from rate in db.Rates where rate.Owner.ToLower() == owner.ToLower() && trimmedDestination.StartsWith(rate.Prefix) && rate.RatePlan == ratePlan orderby rate.Prefix.Length descending select rate).FirstOrDefault(); } } } if (callRate != null) { logger.Debug("Rate found for " + owner + " and " + destination + " was " + callRate.Rate1 + "."); return(callRate); } else { logger.Debug("No rate found for " + owner + " and " + destination + "."); return(null); } } }
/// <summary> /// Updates an existing rate. /// </summary> /// <param name="rate">The rate to update.</param> public void Update(Rate rate) { using (var db = new SIPSorceryEntities()) { var existingRate = (from ra in db.Rates where ra.ID == rate.ID select ra).SingleOrDefault(); if (existingRate == null) { throw new ApplicationException("The rate to update could not be found"); } else if (existingRate.Owner.ToLower() != rate.Owner.ToLower()) { throw new ApplicationException("You are not authorised to update this rate."); } else { if (existingRate.Prefix != rate.Prefix) { if ((from rt in db.Rates where rt.Prefix == rate.Prefix select rt).Any()) { throw new ApplicationException("The rate prefix is already in use."); } } logger.Debug("Updating rate " + existingRate.Description + " for " + existingRate.Owner + "."); existingRate.Description = rate.Description; existingRate.Prefix = rate.Prefix; existingRate.Rate1 = rate.Rate1; existingRate.RateCode = rate.RateCode; db.SaveChanges(); } } }
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); } } } }
/// <summary> /// Erstellt ein neues Rate-Objekt. /// </summary> /// <param name="id">Anfangswert der Eigenschaft ID.</param> /// <param name="owner">Anfangswert der Eigenschaft Owner.</param> /// <param name="description">Anfangswert der Eigenschaft Description.</param> /// <param name="prefix">Anfangswert der Eigenschaft Prefix.</param> /// <param name="rate1">Anfangswert der Eigenschaft Rate1.</param> /// <param name="inserted">Anfangswert der Eigenschaft Inserted.</param> public static Rate CreateRate(global::System.String id, global::System.String owner, global::System.String description, global::System.String prefix, global::System.Decimal rate1, global::System.String inserted) { Rate rate = new Rate(); rate.ID = id; rate.Owner = owner; rate.Description = description; rate.Prefix = prefix; rate.Rate1 = rate1; rate.Inserted = inserted; return rate; }
public void DeleteRate(string authUser, Rate rate) { using (var sipSorceryEntities = new SIPSorceryEntities()) { var existingRate = (from ra in sipSorceryEntities.Rates where ra.ID == rate.ID && ra.Owner == authUser.ToLower() select ra).FirstOrDefault(); if (existingRate == null) { throw new ApplicationException("The rate to delete could not be found."); } else if (existingRate.Owner != authUser.ToLower()) { throw new ApplicationException("Not authorised to delete the rate."); } sipSorceryEntities.Rates.DeleteObject(existingRate); sipSorceryEntities.SaveChanges(); } }
public void UpdateRate(string authUser, Rate rate) { if (authUser.IsNullOrBlank()) { throw new ArgumentException("An authenticated user is required for UpdateRate."); } rate.Owner = authUser; _rateDataLayer.Update(rate); }
/// <summary> /// This method attempts to reserve a the initial amount of credit for a call. /// </summary> /// <param name="accountCode">The accountCode the credit should be reserved against.</param> /// <param name="amount">The amount of credit to reserve.</param> /// <param name="rate">The rate for the call destination and the values that will be used for subsequent credit reservations.</param> /// <param name="initialSeconds">IF the reservation is successful this parameter will hold the number of seconds that were reserved for the initial reservation.</param> /// <returns>True if there was enough credit for the reservation otherwise false.</returns> public decimal ReserveInitialCredit(string accountCode, Rate rate, SIPCDR cdr, out int initialSeconds) { try { logger.Debug("ReserveInitialCredit for " + accountCode + ", rate " + rate.Rate1 + ", setup cost " + rate.SetupCost + ", increment seconds " + rate.IncrementSeconds + "."); initialSeconds = 0; if (accountCode.IsNullOrBlank() || rate.Rate1 <= 0) { return Decimal.MinusOne; } using (var db = new SIPSorceryEntities()) { using (var trans = new TransactionScope()) { var customerAccount = db.CustomerAccounts.Where(x => x.AccountCode == accountCode).SingleOrDefault(); if (customerAccount == null) { logger.Debug("The initial reservation for " + accountCode + " failed due to the no matching accountcode."); return Decimal.MinusOne; } // Get the owning customer's RTCC billing increment. //int rtccIncrement = (from cust in db.Customers where cust.Name.ToLower() == customerAccount.Owner.ToLower() select cust.RTCCBillingIncrement).Single(); initialSeconds = (rate.IncrementSeconds > MINIMUM_INITIAL_RESERVATION_SECONDS) ? rate.IncrementSeconds : MINIMUM_INITIAL_RESERVATION_SECONDS; decimal reservationCost = ((decimal)initialSeconds / (decimal)60 * rate.Rate1) + rate.SetupCost; if (customerAccount.Credit < reservationCost) { logger.Debug("The initial reservation for " + accountCode + ", duration " + initialSeconds + "s and " + reservationCost.ToString("0.#####") + " failed due to lack of credit."); return Decimal.MinusOne; } else { var rtccRecord = new RTCC() { ID = Guid.NewGuid().ToString(), CDRID = cdr.CDRId.ToString(), AccountCode = accountCode, SecondsReserved = initialSeconds, Cost = reservationCost, Rate = rate.Rate1, SetupCost = rate.SetupCost, IncrementSeconds = rate.IncrementSeconds, Inserted = DateTime.UtcNow }; db.RTCCs1.AddObject(rtccRecord); //var callCDR = (from cdr in db.CDRs where cdr.ID == cdrID select cdr).SingleOrDefault(); //if (callCDR == null) //{ // logger.Debug("The initial reservation for " + accountCode + " and " + reservationCost.ToString("0.#####") + " failed due to the no matching CDR for " + cdrID + "."); // return false; //} //else if (callCDR.HungupTime != null) //{ // logger.Debug("The initial reservation for " + accountCode + " and " + reservationCost.ToString("0.#####") + " failed due to the CDR already being hungup."); // return false; //} // The credit is available deduct it from the customer account balance and place it on the CDR. customerAccount.Credit = customerAccount.Credit - reservationCost; // Set the fields on the CDR. //callCDR.Rate = rate; //callCDR.SecondsReserved = seconds; //callCDR.AccountCode = accountCode; //callCDR.Cost = reservationCost; //db.CDRs.AddObject(cdr); db.SaveChanges(); trans.Complete(); logger.Debug("The initial reservation for " + accountCode + ", duration " + initialSeconds + "s and " + reservationCost.ToString("0.#####") + " was successful."); return reservationCost; } } } } catch (Exception excp) { logger.Error("Exception ReserveInitialCredit. " + excp); throw; } }
public Rate ToRate() { Rate rate = new Rate() { Owner = String.Empty, ID = ID, Description = Description, Prefix = Prefix, RateCode = RateCode, Rate1 = Rate, SetupCost = SetupCost, IncrementSeconds = IncrementSeconds }; return rate; }