Ejemplo n.º 1
0
        public ActionResult ForgotPassword(AuthForgottenPasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var user = FindUser(model.Email);

            if (user == null)
            {
                ModelState.AddModelError("", "The e-mail address you entered does not match any accounts on record.");
                return(View());
            }

            var resetToken    = user.GenerateResetToken(TimeSpan.FromHours(24));
            var emailTemplate = _emailTemplatesRepository.GetTemplateByName(Utilities.ToDescriptionString(EmailTemplateCode.ForgotPassword));

            model.ResetPasswordUrl = $"{Request.Url.Authority}/auth/resetpassword?email={model.Email}&resettoken={resetToken}";

            emailTemplate = EmailTemplateFactory.ParseTemplate(emailTemplate, model);
            var mailMessage = MailMessageMapper.ConvertToMailMessage(emailTemplate);

            var sent = EmailServiceFactory.GetEmailService().SendMail(mailMessage);

            return(RedirectToAction("forgotpasswordemail"));
        }
Ejemplo n.º 2
0
    /*public static string GetAccountCreationHTML(string customerUID, string verificationCode,string html)
    {
        string url = HttpContext.Current.Request.Url.ToString();
        string[] paths = url.Split('/');
        url = url.Replace(paths[paths.Length - 1], "VerifyEmail.aspx");
        url += "?" + WebConstants.Request.USER_UID + "=" + customerUID;
        url += "&" + WebConstants.Request.VERIFICATION_CODE + "=" + Utility.GetMd5Sum(verificationCode);
        EmailTemplateFactory.Instance.Paramters.Add("##URL##", url);
        EmailTemplates.EmailTemplateEntityRow emailTemplate = EmailTemplateFactory.Instance.GetEmailContents(WebConstants.TemplateNames.ACTIVATION);
        if (emailTemplate != null)
        {
            html = emailTemplate.html.Replace(
            html = ReplaceAttributes(html);
        }
        else
        {
            html = "Thank you for registering with Simplicity4Business. <br/> <br/>"
                        + " Please click the following URL to activate your account. <br/><br/>"
                        + " <a href='" + url + "'>" + url + "</a>";
        }
        return html;
    }

    public static string GetAccountCreationHTML(string password, string html)
    {
        string url = HttpContext.Current.Request.Url.ToString();
        string[] paths = url.Split('/');
        url = url.Replace(paths[paths.Length - 1], "VerifyEmail.aspx");
        url += "?" + WebConstants.Request.USER_UID + "=" + customerUID;
        url += "&" + WebConstants.Request.VERIFICATION_CODE + "=" + Utility.GetMd5Sum(verificationCode);
        html = html.Replace("##URL##", url);
        html = ReplaceAttributes(html);
        return html;
    }*/
    public static void SendAccountCreationEmail(string emailAddress,string customerUID,string verificationCode)
    {
        MailMessage message = new MailMessage();
        message.To.Add(new MailAddress(emailAddress));
        string url = HttpContext.Current.Request.Url.ToString();
        string[] paths = url.Split('/');
        url = url.Replace(paths[paths.Length - 1], "VerifyEmail.aspx");
        url += "?" + WebConstants.Request.USER_UID + "=" + customerUID;
        url += "&" + WebConstants.Request.VERIFICATION_CODE + "=" + Utility.GetMd5Sum(verificationCode);
        EmailTemplateFactory templateFactory = new EmailTemplateFactory();
        templateFactory.Paramters.Add("##URL##", url);
        EmailTemplates.EmailTemplateEntityRow emailTemplate = templateFactory.GetEmailContents(WebConstants.TemplateNames.ACTIVATION);
        if (emailTemplate != null)
        {
            message.Body = emailTemplate.html;
            message.Subject = emailTemplate.subject;
        }
        else
        {
            message.Body = "Thank you for registering with Simplicity4Business. <br/> <br/>"
                        + " Please click the following URL to activate your account. <br/><br/>"
                        + " <a href=' " + url + "'>" + url + "</a>";
            message.Subject = "Activation Code for Simplicity for Business";
        }
        message.IsBodyHtml = true;
        SendEmail(message);
    }
Ejemplo n.º 3
0
        private static void Flyweight()
        {
            for (int i = 0; i < 2; i++)
            {
                string receiver = $"kehu{i}@qq.com";
                //通过简单工厂维护的对象池获取已经封装好的内部状态的对象。
                var email = EmailTemplateFactory.GetTemplate("阿里云漏洞修复");
                //修改外部状态
                email.Receiver = receiver;
                SendEmail(email);
            }

            Console.ReadLine();
        }
Ejemplo n.º 4
0
        public ActionResult SignUp(string plan, SignUpModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    PlanSignUpRequest request = new PlanSignUpRequest
                    {
                        PlanName    = Request.QueryString["plan"],
                        SignUpModel = model
                    };
                    PlanSignUpResponse response = _planService.PlanSignUp(request);

                    if (response.HasError && response.ErrorCode == ErrorCode.PlanNotFound)
                    {
                        return(RedirectToAction("Pricing", "Plans"));
                    }

                    if (response.HasError && response.ErrorCode == ErrorCode.DomainAlreadyExists)
                    {
                        ModelState.AddModelError("Domain", "Domain already exists");
                    }

                    var domainURL     = "https://" + $"{model.Domain}{ConfigurationManager.AppSettings["HostnameBase"]}";
                    var emailTemplate = _emailTemplatesRepository.GetTemplateByName(Common.Helpers.Utilities.ToDescriptionString(EmailTemplateCode.SignUpGreeting));

                    model.PlanName = plan;
                    emailTemplate  = EmailTemplateFactory.ParseTemplate(emailTemplate, model);
                    var mailMessage = MailMessageMapper.ConvertToMailMessage(emailTemplate);

                    EmailServiceFactory.GetEmailService().SendMail(mailMessage);

                    TempData["Domain"] = domainURL;
                    return(RedirectToAction("thank-you"));
                }
                catch (Exception ex)
                {
                    var errMsg = ex.Message;
                    if (ex.InnerException != null && !string.IsNullOrWhiteSpace(ex.InnerException.Message))
                    {
                        errMsg += ", " + ex.InnerException.Message;
                    }

                    LoggingFactory.GetLogger().Log(errMsg, EventLogSeverity.Error);
                    ModelState.AddModelError("", errMsg);
                }
            }
            return(View(model));
        }
        public Task Consume(ConsumeContext <ISendEmailUserCommand> context)
        {
            var emailData = context.Message;
            var template  = EmailTemplateFactory.GetEmailTemplate(_emailMessageService, emailData);

            var message = new EmailMessageModel
            {
                To             = emailData.To,
                Subject        = template.Subject,
                Body           = template.Body,
                EmailMediaType = EmailMediaType.Html
            };

            _sendEmailService.SendEmail(message);

            return(Task.FromResult(context.Message));
        }
Ejemplo n.º 6
0
        public ActionResult ContactUs(ContactModel model)
        {
            if (ModelState.IsValid)
            {
                model.MailTo = ConfigurationManager.AppSettings["SendEmailTo"];

                var emailTemplate = _emailTemplatesRepository.GetTemplateByName(Utilities.ToDescriptionString(EmailTemplateCode.ContactRequest));
                emailTemplate = EmailTemplateFactory.ParseTemplate(emailTemplate, model);

                var mailMessage = MailMessageMapper.ConvertToMailMessage(emailTemplate);

                var sent = EmailServiceFactory.GetEmailService().SendMail(mailMessage);

                return(PartialView("_ContactUsSuccess"));
            }

            return(PartialView("_ContactUs", model));
        }
Ejemplo n.º 7
0
        public ActionResult SendRequest(ContactUsSupportModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    model.MailTo = ConfigurationManager.AppSettings["SendEmailTo"];

                    var emailTemplate = _emailTemplatesRepository.GetTemplateByName(Utilities.ToDescriptionString(EmailTemplateCode.SupportContactUs));
                    emailTemplate = EmailTemplateFactory.ParseTemplate(emailTemplate, model);

                    var mailMessage = MailMessageMapper.ConvertToMailMessage(emailTemplate);

                    var sent = EmailServiceFactory.GetEmailService().SendMail(mailMessage);

                    if (sent == true)
                    {
                        return(Json(new { success = true }));
                    }
                    else
                    {
                        return(Json(new { success = false }));
                    }
                }
                catch (Exception ex)
                {
                    var errMsg = ex.Message;
                    if (ex.InnerException != null && !string.IsNullOrWhiteSpace(ex.InnerException.Message))
                    {
                        errMsg += ", " + ex.InnerException.Message;
                    }

                    LoggingFactory.GetLogger().Log(errMsg, EventLogSeverity.Error);
                    return(Json(new { success = false }));
                }
            }

            return(Json(new { success = false }));
        }
Ejemplo n.º 8
0
        public ActionResult Index(string plan, ContactModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    // send email
                    EmailTemplate emailTemplate = _emailTemplatesRepository.GetTemplateByName(
                        SaaSPro.Common.Helpers.Utilities.ToDescriptionString(EmailTemplateCode.ContactRequest));

                    model.MailTo = ConfigurationManager.AppSettings["MailTo"];

                    emailTemplate = EmailTemplateFactory.ParseTemplate(emailTemplate, model);
                    MailMessage mailMessage = MailMessageMapper.ConvertToMailMessage(emailTemplate);
                    bool        emailResult = EmailServiceFactory.GetEmailService().SendMail(mailMessage);

                    if (emailResult)
                    {
                        return(RedirectToAction("thank-you"));
                    }

                    ModelState.AddModelError("", "There was a problem ");
                }
                catch (Exception ex)
                {
                    var errMsg = ex.Message;
                    if (ex.InnerException != null && !string.IsNullOrWhiteSpace(ex.InnerException.Message))
                    {
                        errMsg += ", " + ex.InnerException.Message;
                    }

                    LoggingFactory.GetLogger().Log(errMsg, EventLogSeverity.Error);
                    ModelState.AddModelError("", errMsg);
                }
            }
            return(View(model));
        }
Ejemplo n.º 9
0
 public static void SendPasswordEmail(string emailAddress, string password)
 {
     MailMessage message = new MailMessage();
     message.To.Add(new MailAddress(emailAddress));
     EmailTemplateFactory templateFactory = new EmailTemplateFactory();
     templateFactory.Paramters.Add("##PASSWORD##", password);
     EmailTemplates.EmailTemplateEntityRow emailTemplate = templateFactory.GetEmailContents(WebConstants.TemplateNames.PASSWORD);
     if (emailTemplate != null)
     {
         message.Body = emailTemplate.html;
         message.Subject = emailTemplate.subject;
     }
     else
     {
         message.Subject = "Simplicity Account Password";
         message.Body = "Your password is " + password;
     }
     message.IsBodyHtml = true;
     //+ " Or click on the following link: <br/>" + url;
     SendEmail(message);
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Sign up a user to a plan
        /// </summary>
        /// <param name="request">Sign up request</param>
        public PlanSignUpResponse PlanSignUp(PlanSignUpRequest request)
        {
            try
            {
                // Begin transaction
                _unitOfWork.Begin("PlanSignUp");

                var response = new PlanSignUpResponse();
                var dbPlan   = _planRepository.Query().FirstOrDefault(p => p.PlanCode.ToLower() == request.PlanName.ToLower());
                if (dbPlan == null)
                {
                    response.HasError  = true;
                    response.ErrorCode = ErrorCode.PlanNotFound;
                    return(response);
                }

                if (request.SignUpModel.Domain != null)
                {
                    if (
                        _customerRepository.Query().Any(
                            t => t.Hostname.ToLower() == request.SignUpModel.Domain.ToLower()))
                    {
                        response.ErrorCode = ErrorCode.DomainAlreadyExists;
                        response.HasError  = true;
                        return(response);
                    }
                }

                // Customer
                var customer = new Customer(request.SignUpModel.FullName, request.SignUpModel.Domain,
                                            request.SignUpModel.Company);
                _customerRepository.Add(customer);

                // Role
                var role = new Role(customer, "Administrator", true, UserType.SystemUser);
                _roleRepository.Add(role);

                // Setup the User
                var user = new User(customer, request.SignUpModel.Email, request.SignUpModel.FirstName,
                                    request.SignUpModel.LastName, request.SignUpModel.Password);
                _userRepository.Add(user);

                role.AddUser(user);

                customer.UpdateAdminUser(user);

                // Security questions
                var referenceList = _referenceListRepository.Query().FirstOrDefault(l => l.SystemName == "Security Questions");
                if (referenceList == null)
                {
                    throw new NullReferenceException("Security questions reference list is null");
                }

                foreach (var securityQuestion in SecurityQuestions.Questions)
                {
                    referenceList.AddItem(customer, securityQuestion);
                }

                // User security questions
                user.AddSecurityQuestion("a", "a");
                user.AddSecurityQuestion("b", "b");
                user.AddSecurityQuestion("c", "c");

                // Create customer in stripe
                var stripeCustomer = StripeFactory.GetStripeService().CreateCustomer(request.SignUpModel.FullName,
                                                                                     request.SignUpModel.Email);
                customer.PaymentCustomerId = stripeCustomer.Id;

                // Associate plan
                var result = StripeFactory.GetStripeService().AssignCustomerPlan(customer.PaymentCustomerId,
                                                                                 dbPlan.PlanCode,
                                                                                 request.SignUpModel.CardNumber,
                                                                                 request.SignUpModel.SecurityCode,
                                                                                 int.Parse(
                                                                                     request.SignUpModel.Expiration.
                                                                                     Substring(0, 2)),
                                                                                 int.Parse(
                                                                                     request.SignUpModel.Expiration.
                                                                                     Substring(3, 2)));

                if (result != "active")
                {
                    throw new Exception($"Incorrect assigning plan result for Customer {customer.FullName}");
                }

                customer.UpdatePlan(dbPlan);
                _customerRepository.Update(customer);

                // End transaction
                _unitOfWork.End();

                // Send email
                var emailTemplate =
                    _emailTemplatesRepository.GetTemplateByName(
                        EmailTemplateCode.SignUpGreeting.ToDescriptionString());

                emailTemplate = EmailTemplateFactory.ParseTemplate(emailTemplate, customer);
                var mailMessage = MailMessageMapper.ConvertToMailMessage(emailTemplate);
                var emailResult = EmailServiceFactory.GetEmailService().SendMail(mailMessage);

                if (!emailResult)
                {
                    throw new Exception("Problem sending email");
                }

                return(response);
            }
            catch (StripeException ex)
            {
                LoggingFactory.GetLogger().LogError(ex);
                throw new Exception("Assigning customer plan error", ex);
            }
            catch (Exception ex)
            {
                LoggingFactory.GetLogger().LogError(ex);
                throw;
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Process the incoming Stripe Event
        /// </summary>
        public void ProcessEvent(string customerId, StripeEvent stripeEvent)
        {
            try
            {
                LoggingFactory.GetLogger().Log($"Start ProcessEvent(EventType={stripeEvent.Type})", EventLogSeverity.Debug);

                EmailTemplateCode emailTemplateCode = EmailTemplateCode.None;

                Customer customer = _customerRepository.Query().FirstOrDefault(p => p.PaymentCustomerId == customerId);
                if (customer == null)
                {
                    LoggingFactory.GetLogger().Log("Message.NotFindCustomerByPaymentCustomerId", EventLogSeverity.Error);
                    throw new Exception("Messages.NotFindCustomerByPaymentCustomerId" + customerId);
                }

                StripeSubscription subscription;

                switch (stripeEvent.Type)
                {
                case "charge.succeeded":
                    var charge = Mapper <StripeCharge> .MapFromJson(stripeEvent.Data.Object.ToString());

                    var payment = new CustomerPayment(customer.Id, charge.BalanceTransactionId, false, Convert.ToDecimal(charge.Amount / 100.0), charge.Created);

                    _customerPaymentRepository.Add(payment);

                    LoggingFactory.GetLogger().Log("Customer payment added", EventLogSeverity.Information);

                    emailTemplateCode = EmailTemplateCode.ChargeSuccessfull;

                    break;

                case "charge.refunded":
                    var refundedCharge = Mapper <StripeCharge> .MapFromJson(stripeEvent.Data.Object.ToString());

                    var stripeEventObject = JObject.Parse(stripeEvent.Data.Object.ToString());
                    var refundsData       = stripeEventObject.SelectToken("refunds.data");
                    StripeApplicationFeeRefund[] refunds = Mapper <StripeApplicationFeeRefund[]> .MapFromJson(refundsData.ToString());

                    StripeApplicationFeeRefund lastRefund = refunds[refunds.Length - 1];
                    var amountRefundedInDollars           = (decimal)(lastRefund.Amount / 100.0);

                    var refundPayment = new CustomerPaymentRefund(customer.Id, refundedCharge.BalanceTransactionId,
                                                                  refundedCharge.Id,
                                                                  amountRefundedInDollars, lastRefund.Created);

                    _customerPaymentRefundRepository.Add(refundPayment);

                    // TODO update refund field in payment record
                    //refundedCharge.Refunded
                    LoggingFactory.GetLogger().Log("Customer payment refunding", EventLogSeverity.Information);

                    emailTemplateCode = EmailTemplateCode.ChargeRefunded;

                    break;

                case "charge.failed":

                    // Update the DB

                    emailTemplateCode = EmailTemplateCode.ChargeFailed;
                    LoggingFactory.GetLogger().Log("Customer payment failed", EventLogSeverity.Information);

                    //TODO:

                    break;

                case "customer.subscription.deleted":

                    // look up user details from the Customer
                    subscription = Mapper <StripeSubscription> .MapFromJson(stripeEvent.ToString());

                    customer.PlanCanceledOn = subscription.CanceledAt ?? DateTime.Now;
                    _customerRepository.Update(customer);

                    //TODO:
                    //- Create log entry for Admins
                    emailTemplateCode = EmailTemplateCode.CustomerSubscriptionDeleted;
                    LoggingFactory.GetLogger().Log("Customer subscription deleted", EventLogSeverity.Information);

                    break;

                case "customer.subscription.updated":

                    // look up user details from the Customer
                    subscription = Mapper <StripeSubscription> .MapFromJson(stripeEvent.ToString());

                    customer.PlanUpdatedOn = subscription.Start ?? DateTime.Now;
                    _customerRepository.Update(customer);

                    //TODO:
                    //- Create log entry for Admins
                    emailTemplateCode = EmailTemplateCode.CustomerSubscriptionUpdated;
                    LoggingFactory.GetLogger().Log("Customer subsciption updated", EventLogSeverity.Information);

                    break;

                case "charge.created":
                    //TODO
                    return;
                }


                if (emailTemplateCode != EmailTemplateCode.None)
                {
                    EmailTemplate emailTemplate =
                        _emailTemplatesRepository.GetTemplateByName(
                            Common.Helpers.Utilities.ToDescriptionString(emailTemplateCode));

                    emailTemplate = EmailTemplateFactory.ParseTemplate(emailTemplate, customer);
                    MailMessage mailMessage = MailMessageMapper.ConvertToMailMessage(emailTemplate);
                    bool        result      = EmailServiceFactory.GetEmailService().SendMail(mailMessage);

                    if (result)
                    {
                        _unitOfWork.Commit();
                        LoggingFactory.GetLogger().Log("Payment information saved", EventLogSeverity.Information);
                    }
                    else
                    {
                        LoggingFactory.GetLogger().Log("There is an error creating Customer payment", EventLogSeverity.Fatal);
                        throw new Exception("There is an error creating Customer payment");
                    }
                }

                LoggingFactory.GetLogger().Log("End ProcessEvent({0})", EventLogSeverity.Debug);
            }
            catch (Exception ex)
            {
                LoggingFactory.GetLogger().Log(ex.InnerException + "  " + ex.Message, EventLogSeverity.Error);
            }
        }