} // Application_AuthenticateRequest protected void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); Log.Debug("++++++++++++++++++++++++++++"); Log.Error("Exception - \n" + ex); Log.Error("An error occurred", ex); Log.Error("Requested url: {0}", Request.RawUrl); Log.Debug("++++++++++++++++++++++++++++"); } // Application_Error
} // GetInstance public static Configuration GetInstance(ASafeLog oLog = null) { lock (typeof(Configuration)) { if (ms_oConfiguration != null) { return(ms_oConfiguration); } var oPaths = new List <string>(); oLog = oLog.Safe(); foreach (System.Environment.SpecialFolder nFld in new [] { System.Environment.SpecialFolder.ApplicationData, System.Environment.SpecialFolder.CommonProgramFiles, System.Environment.SpecialFolder.CommonProgramFilesX86, System.Environment.SpecialFolder.ProgramFiles, System.Environment.SpecialFolder.ProgramFilesX86 }) { // ReSharper disable EmptyGeneralCatchClause try { oPaths.Add(Path.Combine(System.Environment.GetFolderPath(nFld), CompanyName)); } catch (Exception) { // silently ignore } // try // ReSharper restore EmptyGeneralCatchClause } foreach (var sDir in oPaths) { string sFileContent; try { var sFilePath = Path.Combine(sDir, EnvNameFile); oLog.Debug("Trying to load Channel Grabber configuration from {0}", sFilePath); if (!File.Exists(sFilePath)) { continue; } sFileContent = File.ReadAllText(sFilePath); } catch (Exception e) { oLog.Error("Failed to read Channel Grabber configuration: {0}", e.Message); continue; } // try ms_oConfiguration = new Configuration(sFileContent, oLog); return(ms_oConfiguration); } // for each } // lock throw new ConfigException("Failed to load Channel Grabber configuration."); } // GetInstance
} // SendMail public static void SendMail(MailAddress oFrom, string fromPassword, string subject, string mailBody, string toAddress, ExcelPackage wb = null, ASafeLog oLog = null, int retries = 5) { string body = mailBody; var ostream = new MemoryStream(); var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(oFrom.Address, fromPassword) }; using (var message = new MailMessage()) { message.From = oFrom; message.Subject = subject; message.Body = body; message.IsBodyHtml = true; foreach (string sAddr in toAddress.Split(',')) { message.To.Add(sAddr); } if (wb != null) { message.Attachments.Clear(); wb.SaveAs(ostream); ostream.Position = 0; var attachment = new Attachment(ostream, subject + ".xlsx", "Application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); message.Attachments.Add(attachment); } // if workbook is not null int tryCounter = 0; while (tryCounter < retries) { try { smtp.Send(message); tryCounter = retries; } catch (Exception e) { oLog.Error(string.Format("Error sending mail: {0}", e)); ++tryCounter; if (tryCounter < retries) { oLog.Info("Will wait 5 seconds and retry to send the mail"); Thread.Sleep(TimeSpan.FromSeconds(5)); } // if } // try } // while retries left } // using ostream.Close(); } // SendMail
public static void SendMail( MailAddress oFrom, string fromPassword, string subject, string mailBody, string toAddress, ASafeLog oLog, int retries = 5 ) { var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(oFrom.Address, fromPassword) }; using (var message = new MailMessage()) { message.From = oFrom; message.Subject = subject; message.Body = mailBody; message.IsBodyHtml = true; foreach (string sAddr in toAddress.Split(',')) { message.To.Add(sAddr); } int tryCounter = 0; while (tryCounter < retries) { try { smtp.Send(message); tryCounter = retries; } catch (Exception e) { oLog.Error(string.Format("Error sending mail: {0}", e)); ++tryCounter; if (tryCounter < retries) { oLog.Info("Will wait 5 seconds and retry to send the mail"); Thread.Sleep(TimeSpan.FromSeconds(5)); } // if } // try } // while retries left } // using } // SendMail
public void TestMailbee() { _cfg = new Conf(_log); _cfg.Init(); try { Global.LicenseKey = _cfg.MailBeeLicenseKey; } catch (MailBeeLicenseException e) { _log.Error("License key is invalid: {0}", e); //Mailer.Mailer.SendMail(_cfg.TestAddress, _cfg.TestPassword, "EzAutoresonder Error", e.ToString(), "*****@*****.**"); } // try _imap = new Imap { SslMode = MailBee.Security.SslStartupMode.OnConnect }; // Connect to IMAP server _imap.Connect(_cfg.Server, _cfg.Port); _log.Info("Connected to the server"); // Log into IMAP account _imap.Login("", ""); //todo enter a login _log.Info("Logged into the server"); // Select Inbox folder _imap.ExamineFolder("Inbox"); var uids = (UidCollection)_imap.Search(true, "UNSEEN", null); if (uids.Count > 0) { // Download all the messages found by Search method MailMessageCollection msgs = _imap.DownloadMessageHeaders(uids.ToString(), true); // Iterate througn the messages collection and display info about them foreach (MailMessage msg in msgs) { Console.WriteLine("Message #" + msg.IndexOnServer.ToString(CultureInfo.InvariantCulture) + " has subject: " + msg.Subject + " from: " + msg.From.Email + " received on: " + msg.DateReceived); } } }
/*private static void TestGetSubscribers() { * Campaigns.InitCampaignsList(); * * foreach (Campaign campaign in Campaigns.CampaignsList) { * List<Subscriber> subscriberList = DbCommands.GetSubscriberList(campaign.CampaignType); * PrintSubscribersList(campaign.Title, subscriberList); * } * } * * static void Tests() * { * //ms_oLog.Debug((MailChimpApiControler.GetLists())[0].id); * //MailChimpApiControler.testSegment(); * //MailChimpApiControler.printListMergeVars(Constants.LastStepCustomers_ListID); * //MailChimpApiControler.testSegment(); * //MailChimpApiControler.UnsubscribeList((MailChimpApiControler.GetLists())[0].id); * //MailChimpApiControler.ListBatchSubscribe((MailChimpApiControler.GetLists())[0].id, MailChimpApiControler.GetTestSubscriberList()); * * //Campaigns.InitCampaignsList(); * //foreach (Campaign campaign in Campaigns.CampaignsList) * //{ * // //MailChimpApiControler.Unsubscribe(campaign.ListId, "*****@*****.**"); * // //MailChimpApiControler.Unsubscribe(campaign.ListId, "*****@*****.**"); * // //MailChimpApiControler.ListBatchSubscribe(campaign.ListId, MailChimpApiControler.GetTestSubscriberList()); * // foreach (Day day in campaign.DayList) * // { * // //MailChimpApiControler.testSegment(campaign.ListId, day.TemplateId, day.Condition, campaign.Subject, campaign.Title); * // string campaignId = MailChimpApiControler.CreateSegmentedCampaign(campaign.ListId, day.TemplateId, day.Condition, campaign.Subject, campaign.Title); * // MailChimpApiControler.SendCampaign(campaignId); * // } * // MailChimpApiControler.Unsubscribe(campaign.ListId, "*****@*****.**"); * // MailChimpApiControler.Unsubscribe(campaign.ListId, "*****@*****.**"); * // MailChimpApiControler.Unsubscribe(campaign.ListId, "*****@*****.**"); * //} * * //FileStream fs = new FileStream("log.txt", FileMode.OpenOrCreate); * //StreamWriter sw = new StreamWriter(fs); * //Logger.Debug.SetOut(sw); * //Logger.Debug.WriteLine(DateTime.Now); * * // MailChimpApiControler.GetLists(); * // MailChimpApiControler.ListBatchSubscribe("0715376399", MailChimpApiControler.GetTestSubscriberList()); * // MailChimpApiControler.GetGroups(Constants.EzbobCustomersListId); * // Logger.Debug.WriteLine(Constants.CampaignsType.DidntTakeLoan.ToString()); * //MailChimpApiControler.CreateSegmentedCampaign("0715376399", 32429, "DAYAFTER", "subjrxt", "titlre"); * //MailChimpApiControler.SendCampaign("5f506652c9"); * * //sw.AutoFlush = true; * //sw.Close(); * }*/ public static void TestAlibaba(MailChimpApiControler oMailChimpApiControler) { Campaigns.InitCampaignsList(); foreach (Campaign campaign in Campaigns.CampaignsList) { if (campaign.CampaignType == Constants.CampaignsType.DidntTakeLoanAlibaba) { var subscriberList = new List <Subscriber>() { new Subscriber() { Email = "*****@*****.**", DayAfter = DateTime.Today, FirstName = "Stas", Group = Constants.CampaignsType.DidntTakeLoanAlibaba.ToString(), LastName = "Dulman", LoanOffer = 1000, Month = DateTime.Today, TwoWeeks = DateTime.Today, Week = DateTime.Today } }; if (subscriberList.Count == 0) { ms_oLog.Debug("subscriberList is empty {0}", campaign); continue; } // if ms_oLog.Debug("subscriberList has {0} customers", subscriberList.Count); PrintSubscribersList(campaign.Title, subscriberList); oMailChimpApiControler.ListBatchSubscribe(campaign.ListId, subscriberList); foreach (Day day in campaign.DayList) { if (day == null) { continue; } ms_oLog.Debug("CreateSegmentedCampaign listId:{0}, templateId:{1}, condition:{2}, subject:{3}, title:{4}, type:{5}", campaign.ListId, day.TemplateId, day.Condition, day.Subject, campaign.Title, campaign.CampaignType.ToString()); string campaignId = oMailChimpApiControler.CreateSegmentedCampaign(campaign.ListId, day.TemplateId, day.Condition, day.Subject, campaign.Title, campaign.CampaignType.ToString()); if (!string.IsNullOrEmpty(campaignId)) { ms_oLog.Debug("Sending campaign {0}, {1} {2}", campaignId, campaign.Title, day.Condition); //oMailChimpApiControler.SendCampaign(campaignId); } // fi else { ms_oLog.Error("Failed to CreateSegmentedCampaign"); } } // for each day } } // for each campaign }
public static LogicalGlueResult FromInference(Inference inference, int customerID, ASafeLog log, AConnection db) { if (inference == null) { return(new LogicalGlueResult { Error = "No Logical Glue data found.", }); } // if decimal?minScore = 0; decimal?maxScore = 0; try { if (inference.Bucket != null) { List <I_Grade> allGrades = db.Fill <I_Grade>("SELECT * FROM I_Grade", CommandSpecies.Text); int gradeID = inference.Bucket.Value; maxScore = allGrades.First(x => x.GradeID == gradeID).UpperBound; if (gradeID > 1) { minScore = allGrades.First(x => x.GradeID == (gradeID - 1)).UpperBound; } } // if } catch (Exception ex) { log.Error(ex, "Failed to retrieve min max grade scores for bucket {0}", inference.Bucket); } // try try { var result = new LogicalGlueResult { Error = inference.Error.Message, Date = inference.ReceivedTime, Bucket = inference.Bucket, BucketStr = inference.Bucket != null ? inference.Bucket.Name : string.Empty, MonthlyRepayment = inference.MonthlyRepayment, UniqueID = inference.UniqueID, FLScore = inference.ModelOutputs.ContainsKey(ModelNames.FuzzyLogic) ? inference.ModelOutputs[ModelNames.FuzzyLogic].Grade.Score : null, NNScore = inference.Score, IsTryout = inference.IsTryOut, }; var b = (maxScore - minScore) ?? 0; var a = (result.NNScore - minScore) ?? 0; result.BucketPercent = b == 0 ? 0 : a / b; result.IsHardReject = (inference.Etl != null) && (inference.Etl.Code != null) && inference.Etl.Code.IsHardReject; result.ScoreIsReliable = !inference.ModelOutputs.ContainsKey(ModelNames.NeuralNetwork) || inference.ModelOutputs[ModelNames.NeuralNetwork].Error.IsEmpty; return(result); } catch (Exception ex) { log.Warn(ex, "Failed loading lg data for customer {0}", customerID); return(new LogicalGlueResult { Error = "Failed loading logical glue data", }); } // try } // FromInference
public JsonResult ChangeCreditLine( long id, int productID, int productTypeID, int productSubTypeID, int loanType, int loanSource, double amount, decimal interestRate, int repaymentPeriod, string offerStart, string offerValidUntil, bool allowSendingEmail, int discountPlan, decimal?brokerSetupFeePercent, decimal?manualSetupFeePercent, bool isCustomerRepaymentPeriodSelectionAllowed, int isLoanTypeSelectionAllowed, bool spreadSetupFee, bool feesManuallyUpdated ) { CashRequest cr = this.cashRequestsRepository.Get(id); if (cr.Id <= 0) { log.Error("No cash request found"); return(Json(true)); } // if new Transactional(() => { LoanType loanT = this.loanTypes.Get(loanType); LoanSource source = this.loanSources.Get(loanSource); cr.LoanType = loanT; int step = CurrentValues.Instance.GetCashSliderStep; int sum = (int)Math.Round(amount / step, MidpointRounding.AwayFromZero) * step; cr.ManagerApprovedSum = sum; cr.LoanSource = source; cr.InterestRate = interestRate; cr.RepaymentPeriod = repaymentPeriod; cr.ApprovedRepaymentPeriod = cr.RepaymentPeriod; cr.OfferStart = FormattingUtils.ParseDateWithCurrentTime(offerStart); cr.OfferValidUntil = FormattingUtils.ParseDateWithCurrentTime(offerValidUntil); cr.BrokerSetupFeePercent = brokerSetupFeePercent; cr.ManualSetupFeePercent = manualSetupFeePercent; cr.UwUpdatedFees = feesManuallyUpdated; cr.EmailSendingBanned = !allowSendingEmail; cr.LoanTemplate = null; cr.IsLoanTypeSelectionAllowed = isLoanTypeSelectionAllowed; cr.IsCustomerRepaymentPeriodSelectionAllowed = isCustomerRepaymentPeriodSelectionAllowed; cr.DiscountPlan = this.discounts.Get(discountPlan); cr.SpreadSetupFee = spreadSetupFee; cr.ProductSubTypeID = productSubTypeID; Customer c = cr.Customer; c.OfferStart = cr.OfferStart; c.OfferValidUntil = cr.OfferValidUntil; c.ManagerApprovedSum = sum; this.cashRequestsRepository.SaveOrUpdate(cr); this.customerRepository.SaveOrUpdate(c); }).Execute(); var decision = this.serviceClient.Instance.AddDecision(this.context.UserId, cr.Customer.Id, new NL_Decisions { UserID = this.context.UserId, DecisionTime = DateTime.UtcNow, DecisionNameID = (int)DecisionActions.Waiting, Notes = "Waiting; oldCashRequest: " + cr.Id }, cr.Id, null); // TODO: save feesManuallyUpdated in new loan structure (EZ-4829) log.Info("NL decisionID: {0}, oldCashRequestID: {1}, Error: {2}", decision.Value, cr.Id, decision.Error); NL_OfferFees offerFee = new NL_OfferFees() { LoanFeeTypeID = (int)NLFeeTypes.SetupFee, Percent = manualSetupFeePercent ?? 0, OneTimePartPercent = 1, DistributedPartPercent = 0 }; if (cr.SpreadSetupFee != null && cr.SpreadSetupFee == true) { offerFee.LoanFeeTypeID = (int)NLFeeTypes.ServicingFee; offerFee.OneTimePartPercent = 0; offerFee.DistributedPartPercent = 1; } NL_OfferFees[] ofeerFees = { offerFee }; var offer = this.serviceClient.Instance.AddOffer(this.context.UserId, cr.Customer.Id, new NL_Offers { DecisionID = decision.Value, LoanTypeID = loanType, RepaymentIntervalTypeID = (int)DbConstants.RepaymentIntervalTypes.Month, LoanSourceID = loanSource, StartTime = FormattingUtils.ParseDateWithCurrentTime(offerStart), EndTime = FormattingUtils.ParseDateWithCurrentTime(offerValidUntil), RepaymentCount = repaymentPeriod, Amount = (decimal)amount, MonthlyInterestRate = interestRate, CreatedTime = DateTime.UtcNow, BrokerSetupFeePercent = brokerSetupFeePercent ?? 0, Notes = "offer from ChangeCreditLine, ApplicationInfoController", DiscountPlanID = discountPlan, IsLoanTypeSelectionAllowed = isLoanTypeSelectionAllowed == 1, IsRepaymentPeriodSelectionAllowed = isCustomerRepaymentPeriodSelectionAllowed, SendEmailNotification = allowSendingEmail, ProductSubTypeID = productSubTypeID // SetupFeeAddedToLoan = 0 // default 0 TODO EZ-3515 // InterestOnlyRepaymentCount = //IsAmountSelectionAllowed = 1 default 1 always allowed }, ofeerFees); log.Info("NL--- offerID: {0}, decisionID: {1} oldCashRequestID: {2}, Error: {3}", offer.Value, decision.Value, cr.Id, offer.Error); log.Debug("update offer for customer {0} all the offer is changed", cr.Customer.Id); return(Json(true)); } // ChangeCreditLine
public bool TestMedalCalculation() { var passed = true; var numChecked = 0; var numPassed = 0; var numFailed = 0; var dbHelper = new DbHelper(new SqlConnection(Log), Log); List <MedalComparisonModel> testMedalData = dbHelper.GetMedalTestData(); foreach (var medalComparisonModel in testMedalData) { IMedalCalulator calulator; switch (medalComparisonModel.MedalType) { case MedalType.Limited: calulator = new OfflineLImitedMedalCalculator(DB, Log); break; case MedalType.OnlineLimited: calulator = new OnlineLImitedMedalCalculator(DB, Log); break; case MedalType.NonLimited: calulator = new NonLimitedMedalCalculator(DB, Log); break; case MedalType.SoleTrader: calulator = new SoleTraderMedalCalculator(DB, Log); break; default: Log.Debug("Skipping medal calc for {0} NoMedal", medalComparisonModel.CustomerId); continue; } numChecked++; DateTime companyDate; DateTime regDate; DateTime calcTime = medalComparisonModel.CalculationTime; int businessSeniority; decimal ezbobSeniority; if ( !DateTime.TryParseExact(medalComparisonModel.BusinessSeniority.Value, new[] { "yyyy-MM-dd HH:mm:ss" }, null, DateTimeStyles.AdjustToUniversal, out companyDate)) { businessSeniority = 0; } else { businessSeniority = (int)(calcTime - companyDate).TotalDays / 365; } if ( !DateTime.TryParseExact(medalComparisonModel.EzbobSeniority.Value, new[] { "yyyy-MM-dd HH:mm:ss" }, null, DateTimeStyles.AdjustToUniversal, out regDate)) { ezbobSeniority = 0; } else { ezbobSeniority = (decimal)(calcTime - regDate).TotalDays / (365.0M / 12.0M); } var model = new MedalInputModel { AnnualTurnover = decimal.Parse(medalComparisonModel.AnnualTurnover.Value), TangibleEquity = decimal.Parse(medalComparisonModel.TangibleEquity.Value), BusinessScore = int.Parse(medalComparisonModel.BusinessScore.Value), FirstRepaymentDatePassed = medalComparisonModel.FirstRepaymentDatePassed, BusinessSeniority = businessSeniority, MaritalStatus = (MaritalStatus)Enum.Parse(typeof(MaritalStatus), medalComparisonModel.MaritalStatus.Value), EzbobSeniority = ezbobSeniority, NetWorth = decimal.Parse(medalComparisonModel.NetWorth.Value), NumOfEarlyPayments = int.Parse(medalComparisonModel.NumOfEarlyRepayments.Value), NumOfLatePayments = int.Parse(medalComparisonModel.NumOfLateRepayments.Value), NumOfOnTimeLoans = int.Parse(medalComparisonModel.NumOfLoans.Value), NumOfStores = int.Parse(medalComparisonModel.NumOfStores.Value), PositiveFeedbacks = int.Parse(medalComparisonModel.PositiveFeedbacks.Value), FreeCashFlow = decimal.Parse(medalComparisonModel.FreeCashFlow.Value), ConsumerScore = int.Parse(medalComparisonModel.ConsumerScore.Value), HasHmrc = medalComparisonModel.NumOfHmrcMps > 0 }; var medal = calulator.CalculateMedal(model); if (Math.Abs(medal.NormalizedScore - medalComparisonModel.TotalScoreNormalized) > 0.009M) { Log.Debug("{0}", medal); if (medal.Medal != medalComparisonModel.Medal) { passed = false; Log.Error("Medal Mismatch for customerid {0} 1st {1} 2nd {2}", medalComparisonModel.CustomerId, medalComparisonModel.Medal, medal.Medal); } numFailed++; passed = false; Log.Error("Medal Normalized Score Mismatch for customerid {0} 1st {1} 2nd {2}", medalComparisonModel.CustomerId, medalComparisonModel.TotalScoreNormalized, medal.NormalizedScore); PrintComparisonMedal(medalComparisonModel); } else { numPassed++; } } Log.Debug("Test run on {0}, passed: {1}, failed: {2}", numChecked, numPassed, numFailed); return(passed); }
} // IsAdmin protected void Page_Load(object sender, EventArgs e) { if (Log == null) { Log = (ASafeLog)Application["log"]; Log = new FileLog("EzReportsWeb", bUtcTimeInName: true, bAppend: true, sPath: @"C:\temp\EzReportsWeb\"); } if (oDB == null) { oDB = new SqlConnection(Log); } if (!IsPostBack) { reportHandler = new WebReportHandler(oDB, Log); if (reportHandler.ReportList.Count == 0) { divFilter.Visible = false; return; } // if ddlReportTypes.DataTextField = "Title"; ddlReportTypes.DataValueField = "Title"; ddlReportTypes.DataSource = reportHandler.ReportList.Values.OrderBy(x => x.Title); ddlReportTypes.DataBind(); } // if if (Session["IsAdmin"] == null) { Session["IsAdmin"] = false; try { Session["IsAdmin"] = oDB.ExecuteScalar <bool>( "SELECT IsAdmin FROM ReportUsers WHERE UserName = @uname", CommandSpecies.Text, new QueryParameter("@uname", HttpContext.Current.User.Identity.Name) ); } catch (Exception ex) { Log.Error("Failed to retrieve is admin \n{0}", ex); } } bIsAdmin = (bool)Session["IsAdmin"]; chkIsAdmin.Checked = bIsAdmin; if (bIsAdmin) { InitAdminArea(oDB, IsPostBack); } divAdminMsg.InnerText = string.Empty; DateTime fDate, tDate; bool isDaily; GetDates(out fDate, out tDate, out isDaily); fromDate.Attributes.Add("max", DateTime.Today.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); toDate.Attributes.Add("max", DateTime.Today.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); fromDate.Value = fDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); toDate.Value = tDate.AddDays(-1).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); } // Page_Load