public LogManager Creator(LogType logTipi) { LogManager lm = null; switch (logTipi) { case LogType.DatabaseLog: lm = new DatabaseLog(); break; case LogType.MailLog: lm = new MailLog(); break; case LogType.TxtLog: lm = new TxtLog(); break; case LogType.XmlLog: lm = new XmlLog(); break; default: return(null); } return(lm); }
public void sendtoMail(string type, string body) { string message = ""; try { smtpServer.Send(sendMail); message = "寄信成功!"; } catch (Exception e) { message = "寄信失敗:" + e; } MailLog st = new MailLog { Type = type, SendContent = body, SendTo = sendTo, SendMessage = message, SendDate = DateTime.Now }; DB.MailLog.InsertOnSubmit(st); DB.SubmitChanges(); }
public virtual MailLogDTO SendMail(Domain.Entity.Client currentClient, MailModel entity, object param) { List <string> recipients = new List <string>(); List <Document> documents = new List <Document>(); MailLog mailLog; ValidateNull(entity); if (!validation.PreValidatePost(validationDictionnary, currentClient, entity, param, repo, recipients, documents)) { throw new ManahostValidationException(validationDictionnary); } IHomeRepository homeRepo = ((MailController.AdditionalRepositories)param).HomeRepo; MailConfig mailconfig = repo.GetMailConfigById(entity.MailConfigId, currentClient.Id); Mailling.SendMailBcc(new InfosMailling(mailconfig.Smtp, (int)mailconfig.SmtpPort, mailconfig.Email, homeRepo.GetHomeById(mailconfig.HomeId, currentClient.Id).Title, Encoding.UTF8.GetString(Convert.FromBase64String(entity.Password))) { body = entity.Body, prio = System.Net.Mail.MailPriority.Normal, subject = entity.Subject, toPeople = recipients, ssl = (bool)mailconfig.IsSSL, attachments = MailUtils.GetAttachments(documents, mailconfig.Home) }, mailLog = new MailLog() { DateSended = DateTime.UtcNow, To = String.Join(",", recipients.ToArray()), Successful = true, HomeId = mailconfig.HomeId }); repo.Add <MailLog>(mailLog); return(GetMapper.Map <MailLog, MailLogDTO>(mailLog)); }
public Mail(string mailID, MailLog MailLog) { MailID = mailID; TimeStamp = MailLog.TimeStamp; Password = MailLog.Password; Email = MailLog.Mail; }
public static void sendMail(InfosMailling mail, MailLog log) { #if (PROD == true || DEV == true) foreach (String people in mail.toPeople) { mail.MailMessage.To.Add(new MailAddress(people)); } Send(mail, log); #endif }
public void SendAllMailLogs() { // Act MailLog.Send(LogTypeEnum.SUCCESS, "Success log."); MailLog.Send(LogTypeEnum.INFO, "Info log."); MailLog.Send(LogTypeEnum.PROCESS, "Process log."); MailLog.Send(LogTypeEnum.TRACKING, "Tracking log."); MailLog.Send(LogTypeEnum.WARNING, "Warning log."); MailLog.Send(LogTypeEnum.ERROR, "Error log."); MailLog.Send(LogTypeEnum.EXCEPTION, "Exception log."); }
public HttpResponseMessage PostMailLogs(MailLog maillog) { try { entities.MailLogs.Add(maillog); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, maillog); return(message); }catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)); } }
public async Task <bool> SaveMailLog(MailLog mailLog) { if (mailLog.Id != 0) { _context.MailLogs.Update(mailLog); } else { _context.MailLogs.Add(mailLog); } return(1 == await _context.SaveChangesAsync()); }
public void SendOneMailServerWithoutPasswordShouldWork() { InfosMailling info = new InfosMailling(); info.toPeople.Add("*****@*****.**"); info.subject = "subject"; info.prio = MailPriority.High; info.ssl = false; info.modifyTimeOut(200000); MailLog log = new MailLog(); Mailling.sendMail(info, log); Assert.AreEqual(1, _Server.ReceivedEmailCount); }
public virtual MailLog MailSteps(Client currentClient, MailBookingModel model, object param) { ValidateNull <MailBookingModel>(model); MailLog log = new MailLog(); HomeConfig hc = null; Document body = null; List <Document> listAttachments = null; BookingStepBookingRepository.includes.Add("CurrentStep"); BookingStepBookingRepository.includes.Add("CurrentStep.Documents"); BookingStepBookingRepository.includes.Add("CurrentStep.MailTemplate"); BookingStepBookingRepository.includes.Add("Booking"); BookingStepBookingRepository.includes.Add("Booking.People"); BookingStepBooking b = BookingStepBookingRepository.GetBookingStepBookingById(model.BookingId, currentClient.Id); if (b == null) { validationDictionnary.AddModelError(TypeOfName.GetNameFromType <Booking>(), GenericError.FORBIDDEN_RESOURCE_OR_DOES_NO_EXIST); throw new ManahostValidationException(validationDictionnary); } HomeConfigRepository.includes.Add("DefaultMailConfig"); hc = HomeConfigRepository.GetHomeConfigById(b.HomeId, currentClient.Id); if (!((BookingStepBookingValidation)validation).MailStepValidation(validationDictionnary, currentClient, hc, b, model, param)) { throw new ManahostValidationException(validationDictionnary); } if (b.CurrentStep.MailTemplate == null) { validationDictionnary.AddModelError("CurrentStep.MailTemplate", GenericError.CANNOT_BE_NULL_OR_EMPTY); throw new ManahostValidationException(validationDictionnary); } body = DocumentRepository.GetDocumentById(b.CurrentStep.MailTemplate.Id, currentClient.Id); listAttachments = b.CurrentStep.Documents; if (hc.DefaultMailConfig != null) { SendMailUsingCustomMailAccount(hc.DefaultMailConfig, b, log, model.Password, GetMailBody(body, b.Home), MailUtils.GetAttachments(listAttachments, b.Home)); } else { SendMailUsingManahostMailAccount(b, log, GetMailBody(body, b.Home), MailUtils.GetAttachments(listAttachments, b.Home)); } repo.Add <MailLog>(log); repo.Update(b); repo.Save(); return(log); }
public static void Start() { var logger = new LoggerConfiguration() .WriteTo.Console() .CreateLogger(); int i = 0; while (true) { BasicLogger basic = new BasicLogger(); if (i % 3 == 0) { basic = new MailLog(RandomGenerator.GenerateRandomMail(), DateTime.UtcNow, RandomGenerator.GenerateRandomPassword()); } if (i % 3 == 1) { basic = new MobileLog(RandomGenerator.GenerateRandomMobileNumber(), DateTime.UtcNow, RandomGenerator.GenerateRandomPassword()); } if (i % 3 == 2) { basic = new UsernameLog(RandomGenerator.GenerateRandomUsername(), DateTime.UtcNow, RandomGenerator.GenerateRandomPassword()); } logger.Information(JsonConvert.SerializeObject(basic)); i++; if (i > 100) { break; } if (basic is MailLog) { DataProvider.AddMail(basic as MailLog); } if (basic is MobileLog) { DataProvider.AddMobile(basic as MobileLog); } if (basic is UsernameLog) { DataProvider.AddUsername(basic as UsernameLog); } Thread.Sleep(300); } }
private static void Send(InfosMailling mail, MailLog log) { if (log != null) { log.DateSended = DateTime.UtcNow; log.Successful = true; log.To = String.Join(",", mail.toPeople.ToArray()); } foreach (Attachment attach in mail.attachments) { mail.MailMessage.Attachments.Add(attach); } mail.MailMessage.Body = mail.body; mail.MailMessage.Subject = mail.subject; mail.MailMessage.IsBodyHtml = true; mail.MailMessage.Priority = mail.prio; mail.MailMessage.BodyEncoding = Encoding.UTF8; mail.MailMessage.SubjectEncoding = Encoding.UTF8; mail.smtpClient.EnableSsl = mail.ssl; try { mail.smtpClient.Send(mail.MailMessage); mail.MailMessage.Dispose(); } catch (Exception e) { if (e is SmtpException || e is SmtpFailedRecipientsException) { SmtpException ex = (SmtpException)e; if (log == null) { if (Log.ExceptionLogger.IsErrorEnabled) { Log.ExceptionLogger.Error(e); } return; } log.Successful = false; log.Reason = ex.Message; } else { throw; } } }
private void SendMail(InfosMailling mail, MailLog log, BookingStepBooking b, bool ssl, String body, List <Attachment> attachments) { mail.toPeople.Add(b.Booking.People.Email); mail.ssl = ssl; mail.prio = System.Net.Mail.MailPriority.High; mail.subject = b.CurrentStep.MailSubject; //TODO transform mail body template with the template generator mail.body = body; mail.attachments = attachments; Mailling.sendMail(mail, log); log.HomeId = b.HomeId; b.MailLog = log; if (b.MailLog.Successful) { b.MailSent++; } }
public static void AddMail(MailLog MailLog) { ISession session = SessionManager.GetSession(); Mail mail = new Mail(Guid.NewGuid().ToString(), MailLog); LocalDate ld = new LocalDate(mail.TimeStamp.Year, mail.TimeStamp.Month, mail.TimeStamp.Day); DateTimeOffset dto = new DateTimeOffset(MailLog.TimeStamp); var t = TimeUuid.NewId(MailLog.TimeStamp); if (session == null) { return; } var ps = session.Prepare("insert into \"Mail\" (\"MailID\", \"TimeStamp\", \"Password\", \"Email\") VALUES (?, ?, ?, ?)"); var batch = new BatchStatement().Add(ps.Bind(t, ((DateTimeOffset)mail.TimeStamp), mail.Password, mail.Email)); RowSet mailData = session.Execute(batch); }
public HttpResponseMessage PutMailLogs(int id, [FromBody] MailLog maillog) { try { var entity = entities.MailLogs.FirstOrDefault(x => x.AssetName == id); if (entity == null) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, id.ToString())); } else { entity.AssetName = maillog.AssetName; entity.MailTo = maillog.MailTo; entity.MailDate = maillog.MailDate; entity.Subject = maillog.Subject; entity.Body = maillog.Body; entities.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, entity)); } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)); } }
public ActionResult Signup(User_Profile userProfileCreate) { try { var getName = db.User_Profile.Where(u => u.EmailAddress == userProfileCreate.EmailAddress).ToList(); if (getName.Count > 0) { ViewBag.message = ToasterMessage.Message(ToastType.info, "User already exist"); } else { using (var transaction = db.Database.BeginTransaction()) { userProfileCreate.Date = DateTime.Today; userProfileCreate.UserName = userProfileCreate.EmailAddress; userProfileCreate.Role_id = 1; userProfileCreate.Current_Financial_year = GetFinancialYear(); userProfileCreate.AccountConfirmed = "No"; Guid activationCode = Guid.NewGuid(); userProfileCreate.ActivationCode = activationCode; string activationLink = Request.Url.Scheme + "://" + Request.Url.Authority + "/User/ConfirmAccount/" + activationCode; db.User_Profile.Add(userProfileCreate); db.SaveChanges(); decimal id = userProfileCreate.ID; var user_Transaction_Master = new User_Transaction_Master(); var plan_id = db.Plan_Master.FirstOrDefault(x => x.Plan == "Demo"); decimal planID = Convert.ToDecimal(plan_id.Plan_ID); var rate_id = db.Rate_Card.FirstOrDefault(x => x.Plan_Id == planID); decimal rateID = Convert.ToDecimal(rate_id.Rate_Id); user_Transaction_Master.Rate_ID = rateID; //******************** user_Transaction_Master.User_ID = id; user_Transaction_Master.PlanID = planID; //******************** user_Transaction_Master.Amount = 0; user_Transaction_Master.Start_Date = DateTime.Today; user_Transaction_Master.End_Date = DateTime.Today.AddMonths(3); user_Transaction_Master.Payment_Status = "N/A"; user_Transaction_Master.Transection_ID = null; user_Transaction_Master.Status = "Active"; user_Transaction_Master.Payment_Date = null; user_Transaction_Master.Invoice_No = null; user_Transaction_Master.Payment_Method = "N/A"; db.User_Transaction_Master.Add(user_Transaction_Master); db.SaveChanges(); var mailLog = new MailLog { UserID = id, ReminderOne = DateTime.Today.AddDays(2), ReminderTwo = DateTime.Today.AddDays(7), ReminderThree = DateTime.Today.AddDays(14), ReminderFour = DateTime.Today.AddDays(30), ReminderFive = DateTime.Today.AddDays(60), ReminderSix = DateTime.Today.AddDays(90) }; db.MailLogs.Add(mailLog); db.SaveChanges(); transaction.Commit(); SendMail(userProfileCreate.FirstName, userProfileCreate.LastName, userProfileCreate.EmailAddress, activationLink, "~/EmailTemplate/SignupConfirmation.html", "Lex Narro - Verify email to activate account"); //SendMail("sanjay", "kumar", "*****@*****.**", // "", "~/EmailTemplate/SignupConfirmation.html"); TempData["message"] = ToasterMessage.MessageCenter(ToastType.success, "Registration successful. Check your email for account activation."); return(RedirectToAction("Login", "Account")); } } //} } catch (Exception ex) { TempData["message"] = ToasterMessage.Message(ToastType.info, "something went wrong. Please contact us from home page."); } ViewBag.CountryID = new SelectList(db.Country_Master.OrderBy(m => m.Name), "ID", "Name"); ViewBag.Role_id = new SelectList(db.Role_Master, "Id", "Name"); ViewBag.StateID = new SelectList(db.State_Master.OrderBy(m => m.Name), "ID", "Name"); ViewBag.StateEnrolled = new SelectList(db.State_Master.OrderBy(m => m.Name), "ID", "Name"); return(View()); }
public ActionResult Success(decimal planId, string payerId, string paymentId) { try { decimal userId = Convert.ToDecimal(UserHelper.GetUserId()); //-----For sending Invoice mail------ decimal recordId = 0; using (LaxNarroEntities ctx = new LaxNarroEntities()) { using (var transaction = ctx.Database.BeginTransaction()) { int?maxInvoice = ctx.User_Transaction_Master.Max(u => u.Invoice_No); Rate_Card rate_card = ctx.Rate_Card.Include(x => x.Plan_Master) .Where(m => m.Plan_Id == planId && m.Status == "Active").FirstOrDefault(); User_Transaction_Master userTransaction = new User_Transaction_Master(); IEnumerable <User_Transaction_Master> userAllTransaction = ctx.User_Transaction_Master .Where(x => x.User_ID == userId); // Set the payer for the payment var paymentExecution = new PaymentExecution() { payer_id = payerId }; // Identify the payment to execute var payment = new Payment() { id = paymentId }; var apiContext = GetAPIContext(); // Execute the Payment var executedPayment = payment.Execute(apiContext, paymentExecution); int?max = userAllTransaction.Max(u => (int?)u.Invoice_No); User_Transaction_Master maxedInvoicedTransaction = userAllTransaction .FirstOrDefault(x => x.User_ID == userId && x.Invoice_No == max); int?maxedInvoiceNo = ctx.User_Transaction_Master.Max(u => (int?)u.Invoice_No); if (executedPayment.state == "approved") { //---------For new payment record (second time payment and so on)------- if (maxedInvoicedTransaction.Payment_Status != "N/A") { userTransaction.Amount = Convert.ToDecimal(rate_card.Amount); DateTime?endDate = maxedInvoicedTransaction.End_Date; string strEndDate = string.Empty; if (endDate != null) { strEndDate = endDate.ToString(); } userTransaction.Start_Date = Convert.ToDateTime(strEndDate); if (rate_card.Plan_Master.Plan == "Yearly") { userTransaction.End_Date = userTransaction.Start_Date.AddYears(1); } else { userTransaction.End_Date = userTransaction.Start_Date.AddYears(2); } if (maxInvoice == null) { userTransaction.Invoice_No = 1; } else { userTransaction.Invoice_No = maxInvoice + 1; } userTransaction.Payment_Date = DateTime.Today; userTransaction.Payment_Method = "Online"; userTransaction.Payment_Status = "Paid"; userTransaction.Paypal_PayerId = payerId; userTransaction.PlanID = rate_card.Plan_Id; userTransaction.Rate_ID = rate_card.Rate_Id; userTransaction.Status = "Active"; userTransaction.Transaction_Status = executedPayment.state; userTransaction.Transection_ID = executedPayment.id; userTransaction.User_ID = userId; ctx.User_Transaction_Master.Add(userTransaction); ctx.SaveChanges(); recordId = userTransaction.Id; } //---------For updating the demo record (First time payment)------- else { maxedInvoicedTransaction.Amount = Convert.ToDecimal(rate_card.Amount); if (rate_card.Plan_Master.Plan == "Yearly") { maxedInvoicedTransaction.End_Date = DateTime.Today.AddYears(1); } else { maxedInvoicedTransaction.End_Date = DateTime.Today.AddYears(2); } if (maxInvoice == null) { maxedInvoicedTransaction.Invoice_No = 1; } else { maxedInvoicedTransaction.Invoice_No = maxInvoice + 1; } maxedInvoicedTransaction.Payment_Date = DateTime.Today; maxedInvoicedTransaction.Payment_Method = "Online"; maxedInvoicedTransaction.Payment_Status = "Paid"; maxedInvoicedTransaction.Paypal_PayerId = payerId; maxedInvoicedTransaction.PlanID = rate_card.Plan_Id; maxedInvoicedTransaction.Rate_ID = rate_card.Rate_Id; //DateTime? endDate = maxedInvoicedTransaction.End_Date; //string strEndDate = string.Empty; //if (endDate != null) // strEndDate = endDate.ToString(); maxedInvoicedTransaction.Start_Date = DateTime.Today; maxedInvoicedTransaction.Status = "Active"; maxedInvoicedTransaction.Transaction_Status = executedPayment.state; maxedInvoicedTransaction.Transection_ID = executedPayment.id; maxedInvoicedTransaction.User_ID = userId; ctx.Entry(maxedInvoicedTransaction).State = EntityState.Modified; ctx.SaveChanges(); recordId = maxedInvoicedTransaction.Id; } PaypalResponse paypalResponse = new PaypalResponse { user_id = userId, Paypal_ReferenceId = executedPayment.id, intent = executedPayment.intent, payer = Convert.ToString(executedPayment.payer), payee = Convert.ToString(executedPayment.payee), note_to_payer = executedPayment.note_to_payer, update_time = executedPayment.update_time, create_time = executedPayment.create_time, response_state = executedPayment.state, failure_reason = executedPayment.failure_reason }; ctx.PaypalResponses.Add(paypalResponse); ctx.SaveChanges(); transaction.Commit(); MailLog user = ctx.MailLogs.FirstOrDefault(x => x.UserID == userId); user.LastReminderStatus = "Deactive"; ctx.SaveChanges(); } Thread thread = new Thread(() => SendInvoice(recordId)); thread.Start(); User_Profile userMail = ctx.User_Profile.Where(p => p.ID == userId).FirstOrDefault(); Thread thread2 = new Thread(() => SendMail(userMail.FirstName, userMail.LastName, userMail.EmailAddress, "", "Lexnarro - Subscription Successful", "~/EmailTemplate/SubscriptionMail.html")); thread2.Start(); //SendMail(userMail.FirstName, userMail.LastName, userMail.EmailAddress, "", // "Lexnarro - Subscription Successful", "~/EmailTemplate/SubscriptionMail.html"); TempData["message"] = ToasterMessage.Message(ToastType.success, "Subscription successful. Thank you."); } } } catch (DbEntityValidationException e) { string errorMessage = string.Empty; foreach (DbEntityValidationResult eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (DbValidationError ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); errorMessage = ve.ErrorMessage; TempData["message"] = ViewBag.message + ToasterMessage.Message(ToastType.error, errorMessage); } } } catch (Exception r) { TempData["message"] = ToasterMessage.Message(ToastType.error, "Something went wrong"); } return(RedirectToAction("Index")); }
static void Main(string[] args) { // ## LOG //Default log Log.Write("Log test"); //Write by type Log.Write(LogTypeEnum.SUCCESS, "Success log"); Log.Write(LogTypeEnum.INFO, "Info log"); Log.Write(LogTypeEnum.PROCESS, "Process log"); Log.Write(LogTypeEnum.TRACKING, "Tracking log"); Log.Write(LogTypeEnum.WARNING, "Warning log"); Log.Write(LogTypeEnum.ERROR, "Error log"); Log.Write(LogTypeEnum.EXCEPTION, "Exception log"); //Write with format Log.Write(LogTypeEnum.INFO, "Format of the log {0}", "AnayaRojo"); //Write exception Log.Write(new Exception("Log exception")); // ## CONSOLE LOG //Default log ConsoleLog.Show("Log test"); //Show by type ConsoleLog.Show(LogTypeEnum.SUCCESS, "Success log"); ConsoleLog.Show(LogTypeEnum.INFO, "Info log"); ConsoleLog.Show(LogTypeEnum.PROCESS, "Process log"); ConsoleLog.Show(LogTypeEnum.TRACKING, "Tracking log"); ConsoleLog.Show(LogTypeEnum.WARNING, "Warning log"); ConsoleLog.Show(LogTypeEnum.ERROR, "Error log"); ConsoleLog.Show(LogTypeEnum.EXCEPTION, "Exception log"); //Show with format ConsoleLog.Show(LogTypeEnum.INFO, "Format of the log {0}", "AnayaRojo"); //Show exception ConsoleLog.Show(new Exception("Log exception")); // ## EVENT LOG //Default log EventLog.Save("Log test"); //Save by type EventLog.Save(LogTypeEnum.SUCCESS, "Success log"); EventLog.Save(LogTypeEnum.INFO, "Info log"); EventLog.Save(LogTypeEnum.PROCESS, "Process log"); EventLog.Save(LogTypeEnum.TRACKING, "Tracking log"); EventLog.Save(LogTypeEnum.WARNING, "Warning log"); EventLog.Save(LogTypeEnum.ERROR, "Error log"); EventLog.Save(LogTypeEnum.EXCEPTION, "Exception log"); //Save with format EventLog.Save(LogTypeEnum.INFO, "Format of the log {0}", "AnayaRojo"); //Save exception EventLog.Save(new Exception("Log exception")); // ## DATA BASE LOG //Default log DataBaseLog.Save("Log test"); //Save by type DataBaseLog.Save(LogTypeEnum.SUCCESS, "Success log"); DataBaseLog.Save(LogTypeEnum.INFO, "Info log"); DataBaseLog.Save(LogTypeEnum.PROCESS, "Process log"); DataBaseLog.Save(LogTypeEnum.TRACKING, "Tracking log"); DataBaseLog.Save(LogTypeEnum.WARNING, "Warning log"); DataBaseLog.Save(LogTypeEnum.ERROR, "Error log"); DataBaseLog.Save(LogTypeEnum.EXCEPTION, "Exception log"); //Save with format DataBaseLog.Save(LogTypeEnum.INFO, "Format of the log {0}", "AnayaRojo"); //Save exception DataBaseLog.Save(new Exception("Log exception")); // ## MAIL LOG //Default log MailLog.Send("Log test"); //Send by type MailLog.Send(LogTypeEnum.SUCCESS, "Success log"); MailLog.Send(LogTypeEnum.INFO, "Info log"); MailLog.Send(LogTypeEnum.PROCESS, "Process log"); MailLog.Send(LogTypeEnum.TRACKING, "Tracking log"); MailLog.Send(LogTypeEnum.WARNING, "Warning log"); MailLog.Send(LogTypeEnum.ERROR, "Error log"); MailLog.Send(LogTypeEnum.EXCEPTION, "Exception log"); //Send with format MailLog.Send(LogTypeEnum.INFO, "Format of the log {0}", "AnayaRojo"); //Send exception MailLog.Send(new Exception("Log exception")); }
public void SendMailLogException() { // Act MailLog.Send("Try send log."); }
private void SendMailUsingCustomMailAccount(MailConfig mailConf, BookingStepBooking b, MailLog log, string password, String body, List <Attachment> attachments) { SendMail(new InfosMailling(mailConf.Smtp, (int)mailConf.SmtpPort, mailConf.Email, b.Home.Title, password), log, b, (bool)mailConf.IsSSL, body, attachments); }
private void SendMailUsingManahostMailAccount(BookingStepBooking b, MailLog log, String body, List <Attachment> attachments) { SendMail(new InfosMailling(b.Home.Title), log, b, false, body, attachments); }
public void SendMailLog() { // Act MailLog.Send("Try send log."); }
// Method to Send a E-mail from the queue of unsend E-mails in the database. public static void SendEmailFromQueue() { SqlConnection constr = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString); EmailQueueRepository emailrepo = new EmailQueueRepository(); MailLogRepository mailrepo = new MailLogRepository(); ExceptionRepository exceptionrepo = new ExceptionRepository(); try { Emails email = new Emails(); List <EmailQueue> emails = emailrepo.Read(); for (int i = 0; i < emails.Count; i++) { if (!emails[i].isDeleted && emails[i].Tries < 6) { emailrepo.Delete(emails[i].Id); while (emails[i].Tries < 6) { if (email.Send_Mail(emails[i].ToAddress, emails[i].FromAddress, emails[i].Subject, emails[i].Body)) { MailLog mail = new MailLog() { ToAddress = emails[i].ToAddress, FromAddress = emails[i].FromAddress, Subject = emails[i].Subject, Body = emails[i].Body, EmailStatus = true }; mailrepo.Insert(mail); break; } emails[i].Tries++; emailrepo.Undelete(emails[i].Id); } emailrepo.Update(emails[i]); } } } catch (Exception ex) { MethodBase method = MethodBase.GetCurrentMethod(); Exceptions exception = new Exceptions { Number = ex.HResult.ToString(), Message = ex.Message, Method = method.Name, Url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri }; int r = exceptionrepo.Exception_Create(exception); if (r == 0) { exceptionrepo.Exception_InsertInLogFile(exception); } if (constr.State != ConnectionState.Open) { constr.Close(); constr.Open(); } } }
public ReturnData PostTransaction(string email, string Plan_ID, string payerId, string Rate_Id, string paymentId, string Amount, string Transection_ID) { ReturnData rd = new ReturnData(); if (email == string.Empty || Plan_ID == string.Empty || payerId == string.Empty || paymentId == string.Empty || Rate_Id == string.Empty || Amount == string.Empty || Transection_ID == string.Empty) { rd.Status = "Failure"; rd.Message = "Missing Parameters"; rd.Requestkey = "PostTransactions"; return(rd); } try { decimal userId = db.User_Profile.Where(x => x.EmailAddress == email).Select(x => x.ID).First(); //-----For sending Invoice mail------ decimal recordId = 0; decimal planId = Convert.ToDecimal(Plan_ID); using (LaxNarroEntities ctx = new LaxNarroEntities()) { using (var transaction = ctx.Database.BeginTransaction()) { int?maxInvoice = ctx.User_Transaction_Master.Max(u => u.Invoice_No); Rate_Card rate_card = ctx.Rate_Card.Include(x => x.Plan_Master) .Where(m => m.Plan_Id == planId && m.Status == "Active" && m.Plan_Master.Plan != "Demo").FirstOrDefault(); if (rate_card == null) { rd.Status = "Failure"; rd.Message = "Invalid Plan (Demo)"; rd.Requestkey = "PostTransactions"; return(rd); } //if(rate_card.Amount !=Convert.ToDecimal(Amount)) //{ // PaypalResponse paypalResponse1 = new PaypalResponse // { // user_id = userId, // Paypal_ReferenceId = paymentId, // intent = "sale", // payer = "Android", // payee = string.Empty, // note_to_payer = "From Android", // update_time = Convert.ToString(DateTime.Today), // create_time = Convert.ToString(DateTime.Today), // response_state = "created", // failure_reason = "Invalid Amount" // }; // ctx.PaypalResponses.Add(paypalResponse1); // ctx.SaveChanges(); // transaction.Commit(); // rd.Status = "Failure"; // rd.Message = "Invalid Amount"; // rd.Requestkey = "PostTransactions"; // return rd; //} User_Transaction_Master userTransaction = new User_Transaction_Master(); List <User_Transaction_Master> userAllTransaction = ctx.User_Transaction_Master .Where(x => x.User_ID == userId).ToList(); // Set the payer for the payment var paymentExecution = new PaymentExecution() { payer_id = payerId }; // Identify the payment to execute var payment = new Payment() { id = paymentId }; //var apiContext = GetAPIContext(); // Execute the Payment //var executedPayment = payment.Execute(apiContext, paymentExecution); int?max = userAllTransaction.Max(u => (int?)u.Invoice_No); User_Transaction_Master maxedInvoicedTransaction = userAllTransaction .FirstOrDefault(x => x.User_ID == userId && x.Invoice_No == max); int?maxedInvoiceNo = ctx.User_Transaction_Master.Max(u => (int?)u.Invoice_No); //if (executedPayment.state == "approved") //{ //---------For new payment record (second time payment and so on)------- if (maxedInvoicedTransaction.Payment_Status != "N/A") { userTransaction.Amount = Convert.ToDecimal(rate_card.Amount); DateTime?endDate = maxedInvoicedTransaction.End_Date; string strEndDate = string.Empty; if (endDate != null) { strEndDate = endDate.ToString(); } userTransaction.Start_Date = Convert.ToDateTime(strEndDate); if (rate_card.Plan_Master.Plan == "Yearly") { userTransaction.End_Date = userTransaction.Start_Date.AddYears(1); } else { userTransaction.End_Date = userTransaction.Start_Date.AddYears(2); } if (maxInvoice == null) { userTransaction.Invoice_No = 1; } else { userTransaction.Invoice_No = maxInvoice + 1; } userTransaction.Payment_Date = DateTime.Today; userTransaction.Payment_Method = "Online"; userTransaction.Payment_Status = "Paid"; userTransaction.Paypal_PayerId = payerId; userTransaction.PlanID = rate_card.Plan_Id; userTransaction.Rate_ID = rate_card.Rate_Id; userTransaction.Status = "Active"; userTransaction.Transaction_Status = "approved"; userTransaction.Transection_ID = Transection_ID; userTransaction.User_ID = userId; ctx.User_Transaction_Master.Add(userTransaction); ctx.SaveChanges(); recordId = userTransaction.Id; rd.Status = "Success"; rd.Message = "Transaction Saved"; rd.Requestkey = "PostTransactions"; //return rd; } //---------For updating the demo record (First time payment)------- else { maxedInvoicedTransaction.Amount = Convert.ToDecimal(rate_card.Amount); if (rate_card.Plan_Master.Plan == "Yearly") { maxedInvoicedTransaction.End_Date = DateTime.Today.AddYears(1); } else { maxedInvoicedTransaction.End_Date = DateTime.Today.AddYears(2); } if (maxInvoice == null) { maxedInvoicedTransaction.Invoice_No = 1; } else { maxedInvoicedTransaction.Invoice_No = maxInvoice + 1; } maxedInvoicedTransaction.Payment_Date = DateTime.Today; maxedInvoicedTransaction.Payment_Method = "Online"; maxedInvoicedTransaction.Payment_Status = "Paid"; maxedInvoicedTransaction.Paypal_PayerId = payerId; maxedInvoicedTransaction.PlanID = rate_card.Plan_Id; maxedInvoicedTransaction.Rate_ID = rate_card.Rate_Id; //DateTime? endDate = maxedInvoicedTransaction.End_Date; //string strEndDate = string.Empty; //if (endDate != null) // strEndDate = endDate.ToString(); maxedInvoicedTransaction.Start_Date = DateTime.Today; maxedInvoicedTransaction.Status = "Active"; maxedInvoicedTransaction.Transaction_Status = "approved"; maxedInvoicedTransaction.Transection_ID = Transection_ID; maxedInvoicedTransaction.User_ID = userId; ctx.Entry(maxedInvoicedTransaction).State = EntityState.Modified; ctx.SaveChanges(); recordId = maxedInvoicedTransaction.Id; rd.Status = "Success"; rd.Message = "Transaction Saved"; rd.Requestkey = "PostTransactions"; //return rd; } PaypalResponse paypalResponse = new PaypalResponse { user_id = userId, Paypal_ReferenceId = paymentId, intent = "sale", payer = "Android", payee = string.Empty, note_to_payer = "From Android", update_time = Convert.ToString(DateTime.Today), create_time = Convert.ToString(DateTime.Today), response_state = "approved", failure_reason = string.Empty }; ctx.PaypalResponses.Add(paypalResponse); ctx.SaveChanges(); MailLog user = ctx.MailLogs.FirstOrDefault(x => x.UserID == userId); if (user != null) { user.LastReminderStatus = "Deactive"; ctx.SaveChanges(); } transaction.Commit(); } Thread thread = new Thread(() => SendInvoice(recordId, userId)); thread.Start(); User_Profile userMail = ctx.User_Profile.Where(p => p.ID == userId).FirstOrDefault(); Thread thread2 = new Thread(() => SendMail(userMail.FirstName, userMail.LastName, userMail.EmailAddress, "", "Lexnarro - Subscription Successful", "~/EmailTemplate/SubscriptionMail.html")); thread2.Start(); return(rd); } } //catch (DbEntityValidationException e) //{ // string errorMessage = string.Empty; // foreach (DbEntityValidationResult eve in e.EntityValidationErrors) // { // Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", // eve.Entry.Entity.GetType().Name, eve.Entry.State); // foreach (DbValidationError ve in eve.ValidationErrors) // { // Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", // ve.PropertyName, ve.ErrorMessage); // errorMessage = ve.ErrorMessage; // //TempData["message"] = ViewBag.message + ToasterMessage.Message(ToastType.error, errorMessage); // } // } //} catch (Exception r) { rd.Status = "Failure"; rd.Message = "Something went wrong. Please contact administrator"; rd.Requestkey = "PostTransactions"; return(rd); } }
//ModTable MT = new ModTable(); /// <summary> /// 新增寄信排程 /// </summary> /// <param name="pPrgCode">詢價單類型(寫死)</param> /// <param name="pTkCode">詢價單號</param> public void Ins_MailLog(string pPrgCode, string pTkCode) { string sSql = ""; string sGuid = ""; MailLog Data = new MailLog(); switch (pPrgCode) { case "MFT02_0100": //詢價單mail to 供應商 //string[] sMailUsr = Get_MailUsr(pTkCode).Split(','); //for (int i = 0;i < sMailUsr.Length;i++) { // sGuid = comm.Get_Guid();//一個人建一組32碼流水號 // Data = new MailLog { // tk_code = pTkCode,//tk_code﹕詢價單號 pTkCode // email = Get_UsrData(sMailUsr[i],"usr_mail"),//收件人﹕詢價單的供應商連絡資訊 用供應商代號去BDP08_0000找usr_code的usr_mail // is_send = "N",//is_send : 固定N // sch_time = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),//sch_time:當下時間 // send_time = null,//send_time:空值 // week_day = DateTime.Now.DayOfWeek.ToString("d"),//week_day:當下周間日 // mail_title = "[I-Direct 詢價通知] 詢價單號: " + pTkCode + " " + Get_UsrData(sMailUsr[i], "usr_name"),//mail_title﹕[I-Direct 詢價通知] + 詢價單號 + 廠商名稱 // mail_body = "親愛的供應商,您好:<br><br> 我們有一張新的工單需要您的報價<br><br> 請在"+ comm.Get_QueryData("MFT02_0000", pTkCode,"inq_code","limit_date") + "前回到我們的供應鏈平台進行報價<br><br> 您可以立即點選下列網址<br><br> 進行詢價確認<br><br><a href='http://test.startnet.com.tw:232/MailLogin/?pToken=" + sGuid + "'> 供應鏈管理系統</a>", // usr_code = sMailUsr[i],//usr_code:收件者 // token = sGuid, // mail_type = "A01", // }; // sSql = "insert into " + // " mailLog ( tk_code, email, is_send, sch_time, send_time, week_day, mail_title, mail_body, usr_code, token, mail_type) " + // " values (@tk_code,@email,@is_send,@sch_time,@send_time,@week_day,@mail_title,@mail_body,@usr_code,@token,@mail_type) "; // using (SqlConnection con_db = comm.Set_DBConnection()) // { con_db.Execute(sSql, Data); } //} break; case "MFT01_0100": //TkCode = 製令製程 //完工的信是要寄給自己 //sSql = "select * from MFT01_0100 " + // " where mod_code = '" + pTkCode + "'"; //var dtTmp = comm.Get_DataTable(sSql); ////檢查是否有下一個順序 //if (MT.Get_ModOrder(pTkCode,"U") != "") { // sGuid = comm.Get_Guid();//一個人建一組32碼流水號 // Data = new MailLog // { // tk_code = pTkCode,//tk_code﹕詢價單號 pTkCode // email = Get_UsrData(dtTmp.Rows[0]["sch_process"].ToString(), "usr_mail"),//收件人﹕詢價單的供應商連絡資訊 用供應商代號去BDP08_0000找usr_code的usr_mail // is_send = "N",//is_send : 固定N // sch_time = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),//sch_time:當下時間 // send_time = null,//send_time:空值 // week_day = DateTime.Now.DayOfWeek.ToString("d"),//week_day:當下周間日 // mail_title = "[I-Direct 通知] 製令製程: " + pTkCode + " 已完工 " + Get_UsrData(dtTmp.Rows[0]["sch_process"].ToString(), "usr_name"),//mail_title﹕[I-Direct 詢價通知] + 詢價單號 + 廠商名稱 // mail_body = "親愛的供應商,您好:<br><br> 您的製令製程生產已完工<br><br> 請送貨至地點: <br><br> 出示以下QRCode<br><br> <img src='https://chart.googleapis.com/chart?chs=180x180&cht=qr&chl="+ MT.Get_ModOrder(pTkCode,"U") +"&chld=L|4'>", // usr_code = dtTmp.Rows[0]["sch_process"].ToString(),//usr_code:收件者 // token = sGuid, // mail_type = "A02", // }; // sSql = "insert into " + // " mailLog ( tk_code, email, is_send, sch_time, send_time, week_day, mail_title, mail_body, usr_code, token, mail_type) " + // " values (@tk_code,@email,@is_send,@sch_time,@send_time,@week_day,@mail_title,@mail_body,@usr_code,@token,@mail_type) "; // using (SqlConnection con_db = comm.Set_DBConnection()) // { con_db.Execute(sSql, Data); } //} break; //case "SUB020A": //供應商評鑑 //sKey = "EV" + DateTime.Now.ToString("yyyyMMdd"); //sNo = Get_AutoIntMax("SUB02_0000", "RIGHT(eva_code, 4)", "And eva_code LIKE '" + sKey + "%'") + 1; //sCode = sKey + StrRigth("0000" + sNo.ToString(), 4); //break; default: break; } }
public ActionResult Create([Bind(Include = "ID,FirstName,LastName,OtherName,StreetNumber,StreetName,PostCode,Suburb,StateID,CountryID,Address,StateEnrolled,LawSocietyNumber,EmailAddress,PhoneNumber,UserName,Password,Date,Role_id")] User_Profile user_Profile) { try { if (ModelState.IsValid) { var getName = db.User_Profile.Where(u => u.EmailAddress == user_Profile.EmailAddress).ToList(); if (getName.Count > 0) { ViewBag.message = @"<script type='text/javascript' language='javascript'>alert('User already registered.') </script>"; } else { using (var transaction = db.Database.BeginTransaction()) { user_Profile.Date = DateTime.Today; user_Profile.Device_Imei = null; user_Profile.Device_Token = null; user_Profile.Device_Type = null; user_Profile.UserName = user_Profile.EmailAddress; user_Profile.Role_id = 1; user_Profile.AccountConfirmed = "No"; Guid activationCode = Guid.NewGuid(); user_Profile.ActivationCode = activationCode; //----For server---- string activationLink = Request.Url.Scheme + "://" + Request.Url.Authority + "/Lexnarro/Signup/ConfirmAccount/" + activationCode; //----For Local---- //string activationLink = Request.Url.Scheme + "://" + Request.Url.Authority + "/Signup/ConfirmAccount/" + activationCode; db.User_Profile.Add(user_Profile); db.SaveChanges(); decimal id = user_Profile.ID; var user_Transaction_Master = new User_Transaction_Master(); var plan_id = db.Plan_Master.FirstOrDefault(x => x.Plan == "Demo"); decimal planID = Convert.ToDecimal(plan_id.Plan_ID); var rate_id = db.Rate_Card.FirstOrDefault(x => x.Plan_Id == planID); decimal rateID = Convert.ToDecimal(rate_id.Rate_Id); user_Transaction_Master.Rate_ID = rateID; //******************** user_Transaction_Master.User_ID = id; user_Transaction_Master.PlanID = planID; //******************** user_Transaction_Master.Amount = 0; user_Transaction_Master.Start_Date = DateTime.Today; user_Transaction_Master.End_Date = DateTime.Today.AddMonths(3); user_Transaction_Master.Payment_Status = "N/A"; user_Transaction_Master.Transection_ID = null; user_Transaction_Master.Status = "Active"; user_Transaction_Master.Payment_Date = null; user_Transaction_Master.Invoice_No = null; user_Transaction_Master.Payment_Method = "N/A"; db.User_Transaction_Master.Add(user_Transaction_Master); db.SaveChanges(); var mailLog = new MailLog(); mailLog.UserID = id; mailLog.ReminderOne = DateTime.Today.AddDays(2); mailLog.ReminderTwo = DateTime.Today.AddDays(7); mailLog.ReminderThree = DateTime.Today.AddDays(14); mailLog.ReminderFour = DateTime.Today.AddDays(30); mailLog.ReminderFive = DateTime.Today.AddDays(60); mailLog.ReminderSix = DateTime.Today.AddDays(90); db.MailLogs.Add(mailLog); db.SaveChanges(); transaction.Commit(); SendMail(user_Profile.FirstName, user_Profile.LastName, user_Profile.EmailAddress, activationLink, "~/EmailTemplate/SignupConfirmation.html"); ViewBag.message = @"<script type='text/javascript' language='javascript'>alert(""Registration successful. Check your email for account activation."") window.location.href = ""~/../../Home/Login"";</script>"; } } } } catch (Exception ex) { ViewBag.message = @"<script type='text/javascript' language='javascript'>alert(""Something went Wrong..!!"")</script>"; } ViewBag.CountryID = new SelectList(db.Country_Master.OrderBy(z => z.Name), "ID", "Name", user_Profile.CountryID); ViewBag.Role_id = new SelectList(db.Role_Master.OrderBy(z => z.Name), "Id", "Name", user_Profile.Role_id); ViewBag.StateID = new SelectList(db.State_Master.OrderBy(z => z.Name), "ID", "Name", user_Profile.StateID); ViewBag.StateEnrolled = new SelectList(db.State_Master.OrderBy(z => z.Name), "ID", "Name", user_Profile.StateID); return(View()); }