Esempio n. 1
0
        /// <summary>
        /// Report a post
        /// </summary>
        /// <param name="report"></param>
        public void PostReport(Report report)
        {
            var sb = new StringBuilder();
            var email = new Email();

            sb.AppendFormat("<p>{2}: <a href=\"{0}\">{1}</a></p>", string.Concat(_settingsService.GetSettings().ForumUrl, report.Reporter.NiceUrl), 
                report.Reporter.UserName,
                _localizationService.GetResourceString("Report.Reporter"));

            sb.AppendFormat("<p>{2}: <a href=\"{0}\">{1}</a></p>", string.Concat(_settingsService.GetSettings().ForumUrl, 
                report.ReportedPost.Topic.NiceUrl), report.ReportedPost.Topic.Name,
                _localizationService.GetResourceString("Report.PostReported"));

            sb.AppendFormat("<p>{0}:</p>", _localizationService.GetResourceString("Report.Reason"));
            sb.AppendFormat("<p>{0}</p>", report.Reason);

            email.EmailFrom = _settingsService.GetSettings().NotificationReplyEmail;
            email.EmailTo = _settingsService.GetSettings().AdminEmailAddress;
            email.Subject = _localizationService.GetResourceString("Report.PostReport");
            email.NameTo = _localizationService.GetResourceString("Report.Admin");

            email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());

            _emailService.SendMail(email);
        }
        public ActionResult Create(Guid to)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var viewModel = new CreatePrivateMessageViewModel
                {
                    To = to
                };

                try
                {
                    var permissions = RoleService.GetPermissions(null, UsersRole);
                    var settings = SettingsService.GetSettings();
                    // Check if private messages are enabled
                    if (!settings.EnablePrivateMessages || LoggedOnReadOnlyUser.DisablePrivateMessages == true)
                    {
                        return Content(LocalizationService.GetResourceString("Errors.GenericMessage"));
                    }

                    // Check outbox size of logged in user
                    var senderCount = _privateMessageService.GetAllSentByUser(LoggedOnReadOnlyUser.Id).Count;
                    if (senderCount > settings.MaxPrivateMessagesPerMember)
                    {
                        return Content(LocalizationService.GetResourceString("PM.SentItemsOverCapcity"));
                    }
                    if (senderCount > (settings.MaxPrivateMessagesPerMember - SiteConstants.PrivateMessageWarningAmountLessThanAllowedSize))
                    {
                        // Send user a warning they are about to exceed
                        var sb = new StringBuilder();
                        sb.AppendFormat("<p>{0}</p>", LocalizationService.GetResourceString("PM.AboutToExceedInboxSizeBody"));
                        var email = new Email
                        {
                            EmailTo = LoggedOnReadOnlyUser.Email,
                            NameTo = LoggedOnReadOnlyUser.UserName,
                            Subject = LocalizationService.GetResourceString("PM.AboutToExceedInboxSizeSubject")
                        };
                        email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());
                        _emailService.SendMail(email);
                    }

                    // Set editor permissions
                    ViewBag.ImageUploadType = permissions[AppConstants.PermissionInsertEditorImages].IsTicked ? "forumimageinsert" : "image";

                    unitOfWork.Commit();

                }
                catch (Exception ex)
                {
                    unitOfWork.Rollback();
                    LoggingService.Error(ex);
                }

                return PartialView(viewModel);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Report a post
        /// </summary>
        /// <param name="report"></param>
        public void PostReport(Report report)
        {
            var sb = new StringBuilder();
            var email = new Email();

            sb.AppendFormat("<p>{2}: <a href=\"{0}\">{1}</a></p>", string.Concat(_settingsService.GetSettings().ForumUrl.TrimEnd('/'), report.Reporter.NiceUrl), 
                report.Reporter.UserName,
                _localizationService.GetResourceString("Report.Reporter"));

            var urlOfPost =$"{_settingsService.GetSettings().ForumUrl.TrimEnd('/')}{report.ReportedPost.Topic.NiceUrl}?order=all#comment-{report.ReportedPost.Id}";
            sb.AppendFormat("<p>{2}: <a href=\"{0}\">{1}</a></p>", urlOfPost, report.ReportedPost.Topic.Name, _localizationService.GetResourceString("Report.PostReported"));

            sb.AppendFormat("<p>{0}:</p>", _localizationService.GetResourceString("Report.Reason"));
            sb.AppendFormat("<p>{0}</p>", report.Reason);

            email.EmailTo = _settingsService.GetSettings().AdminEmailAddress;
            email.Subject = _localizationService.GetResourceString("Report.PostReport");
            email.NameTo = _localizationService.GetResourceString("Report.Admin");

            email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());

            _emailService.SendMail(email);
        }
Esempio n. 4
0
        private void SendEmailConfirmationEmail(MembershipUser userToSave)
        {
            var manuallyAuthoriseMembers = SettingsService.GetSettings().ManuallyAuthoriseNewMembers;
            var memberEmailAuthorisationNeeded = SettingsService.GetSettings().NewMemberEmailConfirmation ?? false;
            if (manuallyAuthoriseMembers == false && memberEmailAuthorisationNeeded)
            {
                if (!string.IsNullOrEmpty(userToSave.Email))
                {
                    // SEND AUTHORISATION EMAIL
                    var sb = new StringBuilder();
                    var confirmationLink = string.Concat(StringUtils.ReturnCurrentDomain(), Url.Action("EmailConfirmation", new { id = userToSave.Id }));
                    sb.AppendFormat("<p>{0}</p>", string.Format(LocalizationService.GetResourceString("Members.MemberEmailAuthorisation.EmailBody"),
                                                SettingsService.GetSettings().ForumName,
                                                string.Format("<p><a href=\"{0}\">{0}</a></p>", confirmationLink)));
                    var email = new Email
                    {
                        EmailTo = userToSave.Email,
                        NameTo = userToSave.UserName,
                        Subject = LocalizationService.GetResourceString("Members.MemberEmailAuthorisation.Subject")
                    };
                    email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());
                    _emailService.SendMail(email);

                    // ADD COOKIE
                    // We add a cookie for 7 days, which will display the resend email confirmation button
                    // This cookie is removed when they click the confirmation link
                    var myCookie = new HttpCookie(AppConstants.MemberEmailConfirmationCookieName)
                    {
                        Value = string.Format("{0}#{1}", userToSave.Email, userToSave.UserName),
                        Expires = DateTime.UtcNow.AddDays(7)
                    };
                    // Add the cookie.
                    Response.Cookies.Add(myCookie);
                }
            }
        }
Esempio n. 5
0
        public ActionResult ForgotPassword(ForgotPasswordViewModel forgotPasswordViewModel)
        {
            if (!ModelState.IsValid)
            {
                return View(forgotPasswordViewModel);
            }

            MembershipUser user;
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                user = MembershipService.GetUserByEmail(forgotPasswordViewModel.EmailAddress);

                // If the email address is not registered then display the 'email sent' confirmation the same as if 
                // the email address was registered. There is no harm in doing this and it avoids exposing registered 
                // email addresses which could be a privacy issue if the forum is of a sensitive nature. */
                if (user == null)
                {
                    return RedirectToAction("PasswordResetSent", "Members");
                }

                try
                {
                    // If the user is registered then create a security token and a timestamp that will allow a change of password
                    MembershipService.UpdatePasswordResetToken(user);
                    unitOfWork.Commit();
                }
                catch (Exception ex)
                {
                    unitOfWork.Rollback();
                    LoggingService.Error(ex);
                    ModelState.AddModelError("", LocalizationService.GetResourceString("Members.ResetPassword.Error"));
                    return View(forgotPasswordViewModel);
                }
            }


            // At this point the email address is registered and a security token has been created
            // so send an email with instructions on how to change the password
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                var settings = SettingsService.GetSettings();
                var url = new Uri(string.Concat(settings.ForumUrl.TrimEnd('/'), Url.Action("ResetPassword", "Members", new { user.Id, token = user.PasswordResetToken })));

                var sb = new StringBuilder();
                sb.AppendFormat("<p>{0}</p>", string.Format(LocalizationService.GetResourceString("Members.ResetPassword.EmailText"), settings.ForumName));
                sb.AppendFormat("<p><a href=\"{0}\">{0}</a></p>", url);

                var email = new Email
                {
                    EmailTo = user.Email,
                    NameTo = user.UserName,
                    Subject = LocalizationService.GetResourceString("Members.ForgotPassword.Subject")
                };
                email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());
                _emailService.SendMail(email);

                try
                {
                    unitOfWork.Commit();
                }
                catch (Exception ex)
                {
                    unitOfWork.Rollback();
                    LoggingService.Error(ex);
                    ModelState.AddModelError("", LocalizationService.GetResourceString("Members.ResetPassword.Error"));
                    return View(forgotPasswordViewModel);
                }
            }

            return RedirectToAction("PasswordResetSent", "Members");
        }
        public void Execute(IJobExecutionContext context)
        {
            using (var unitOfWork = _unitOfWorkManager.NewUnitOfWork())
            {
                try
                {
                    var settings = _settingsService.GetSettings(false);
                    var timeFrame = settings.MarkAsSolutionReminderTimeFrame ?? 0;
                    if (timeFrame > 0 && settings.EnableMarkAsSolution)
                    {


                        var remindersToSend = _topicService.GetMarkAsSolutionReminderList(timeFrame);
                        if (remindersToSend.Any())
                        {
                            var amount = remindersToSend.Count;

                            // Use settings days amount and also mark topics as reminded
                            // Only send if markassolution is enabled and day is not 0

                            foreach (var markAsSolutionReminder in remindersToSend)
                            {
                                // Topic Link
                                var topicLink = $"<a href=\"{settings.ForumUrl.TrimEnd('/')}{markAsSolutionReminder.Topic.NiceUrl}\">{markAsSolutionReminder.Topic.Name}</a>";

                                // Create the email
                                var sb = new StringBuilder();
                                sb.AppendFormat("<p>{0}</p>", string.Format(_localizationService.GetResourceString("Tasks.MarkAsSolutionReminderJob.EmailBody"),
                                                                topicLink,
                                                                settings.ForumName, markAsSolutionReminder.PostCount));

                                // create the emails and only send them to people who have not had notifications disabled

                                var user = markAsSolutionReminder.Topic.User;

                                var email = new Email
                                {
                                    Body = _emailService.EmailTemplate(user.UserName, sb.ToString(), settings),
                                    EmailTo = user.Email,
                                    NameTo = user.UserName,
                                    Subject = string.Format(
                                        _localizationService.GetResourceString("Tasks.MarkAsSolutionReminderJob.Subject"),
                                        settings.ForumName)
                                };


                                // and now pass the emails in to be sent
                                // We have to pass the current settings to SendMail when it's within a task
                                _emailService.SendMail(email, settings);

                                // And now mark the topic as reminder sent
                                markAsSolutionReminder.Topic.SolvedReminderSent = true;
                            }

                            unitOfWork.Commit();
                            _loggingService.Error($"{amount} Mark as solution reminder emails sent");

                        }
                    }
                }
                catch (Exception ex)
                {
                    unitOfWork.Rollback();
                    _loggingService.Error(ex);
                }
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Create new user
        /// </summary>
        /// <param name="newUser"></param>
        /// <returns></returns>
        public MembershipCreateStatus CreateUser(MembershipUser newUser)
        {
            newUser = SanitizeUser(newUser);
            var settings = _settingsService.GetSettings(false);


            var status = MembershipCreateStatus.Success;

            var e = new RegisterUserEventArgs { User = newUser };
            EventManager.Instance.FireBeforeRegisterUser(this, e);

            if (e.Cancel)
            {
                status = e.CreateStatus;
            }
            else
            {
                if (string.IsNullOrEmpty(newUser.UserName))
                {
                    status = MembershipCreateStatus.InvalidUserName;
                }

                // get by username
                if (GetUser(newUser.UserName, true) != null)
                {
                    status = MembershipCreateStatus.DuplicateUserName;
                }

                // Add get by email address
                if (GetUserByEmail(newUser.Email, true) != null)
                {
                    status = MembershipCreateStatus.DuplicateEmail;
                }

                if (string.IsNullOrEmpty(newUser.Password))
                {
                    status = MembershipCreateStatus.InvalidPassword;
                }

                if (status == MembershipCreateStatus.Success)
                {
                    // Hash the password
                    var salt = StringUtils.CreateSalt(AppConstants.SaltSize);
                    var hash = StringUtils.GenerateSaltedHash(newUser.Password, salt);
                    newUser.Password = hash;
                    newUser.PasswordSalt = salt;

                    newUser.Roles = new List<MembershipRole> { settings.NewMemberStartingRole };

                    // Set dates
                    newUser.CreateDate = newUser.LastPasswordChangedDate = DateTime.UtcNow;
                    newUser.LastLockoutDate = (DateTime)SqlDateTime.MinValue;
                    newUser.LastLoginDate = DateTime.UtcNow;
                    newUser.IsLockedOut = false;

                    var manuallyAuthoriseMembers = settings.ManuallyAuthoriseNewMembers;
                    var memberEmailAuthorisationNeeded = settings.NewMemberEmailConfirmation == true;
                    if (manuallyAuthoriseMembers || memberEmailAuthorisationNeeded)
                    {
                        newUser.IsApproved = false;
                    }
                    else
                    {
                        newUser.IsApproved = true;
                    }

                    // url generator
                    newUser.Slug = ServiceHelpers.GenerateSlug(newUser.UserName, GetUserBySlugLike(ServiceHelpers.CreateUrl(newUser.UserName)), null);

                    try
                    {
                        Add(newUser);

                        if (settings.EmailAdminOnNewMemberSignUp)
                        {
                            var sb = new StringBuilder();
                            sb.AppendFormat("<p>{0}</p>", string.Format(_localizationService.GetResourceString("Members.NewMemberRegistered"), settings.ForumName, settings.ForumUrl));
                            sb.AppendFormat("<p>{0} - {1}</p>", newUser.UserName, newUser.Email);
                            var email = new Email
                                            {
                                                EmailTo = settings.AdminEmailAddress,
                                                NameTo = _localizationService.GetResourceString("Members.Admin"),
                                                Subject = _localizationService.GetResourceString("Members.NewMemberSubject")
                                            };
                            email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());
                            _emailService.SendMail(email);
                        }

                        _activityService.MemberJoined(newUser);
                        EventManager.Instance.FireAfterRegisterUser(this,
                                                                    new RegisterUserEventArgs { User = newUser });
                    }
                    catch (Exception)
                    {
                        status = MembershipCreateStatus.UserRejected;
                    }
                }
            }

            return status;
        }
Esempio n. 8
0
        public ActionResult SendTestEmail()
        {
            var sb = new StringBuilder();
            sb.AppendFormat("<p>{0}</p>", string.Concat("This is a test email from ", SettingsService.GetSettings().ForumName));
            var email = new Email
                {
                    EmailFrom = SettingsService.GetSettings().AdminEmailAddress,
                    EmailTo = SettingsService.GetSettings().AdminEmailAddress,
                    NameTo = "Email Test Admin",
                    Subject = string.Concat("Email Test From ", SettingsService.GetSettings().ForumName)
                };
            email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());
            _emailService.SendMail(email);

            TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
            {
                Message = "Test Email Sent",
                MessageType = GenericMessages.success
            };
            return RedirectToAction("TestEmail");
        }
        public ActionResult Create(CreatePrivateMessageViewModel createPrivateMessageViewModel)
        {
            if (!SettingsService.GetSettings().EnablePrivateMessages || LoggedOnUser.DisablePrivateMessages == true)
            {
                return ErrorToHomePage(LocalizationService.GetResourceString("Errors.GenericMessage"));
            }
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                if (ModelState.IsValid)
                {
                    var userTo = createPrivateMessageViewModel.UserToUsername;

                    // first check they are not trying to message themself!
                    if (userTo.ToLower() != LoggedOnUser.UserName.ToLower())
                    {
                        // Map the view model to message
                        var privateMessage = new PrivateMessage
                                                 {
                                                     UserFrom = LoggedOnUser,
                                                     Subject = createPrivateMessageViewModel.Subject,
                                                     Message = createPrivateMessageViewModel.Message,
                                                 };
                        // now get the user its being sent to
                        var memberTo = MembershipService.GetUser(userTo);

                        // check the member
                        if (memberTo != null)
                        {

                            // Check in box size
                            // First check sender
                            var receiverCount = _privateMessageService.GetAllReceivedByUser(memberTo.Id).Count;
                            if (receiverCount > SettingsService.GetSettings().MaxPrivateMessagesPerMember)
                            {
                                ModelState.AddModelError(string.Empty, string.Format(LocalizationService.GetResourceString("PM.ReceivedItemsOverCapcity"), memberTo.UserName));
                            }
                            else
                            {
                                // Good to go send the message!
                                privateMessage.UserTo = memberTo;
                                _privateMessageService.Add(privateMessage);

                                try
                                {
                                    TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                    {
                                        Message = LocalizationService.GetResourceString("PM.MessageSent"),
                                        MessageType = GenericMessages.success
                                    };

                                    unitOfWork.Commit();

                                    // Finally send an email to the user so they know they have a new private message
                                    // As long as they have not had notifications disabled
                                    if (memberTo.DisableEmailNotifications != true)
                                    {
                                        var email = new Email
                                        {
                                            EmailFrom = SettingsService.GetSettings().NotificationReplyEmail,
                                            EmailTo = memberTo.Email,
                                            Subject = LocalizationService.GetResourceString("PM.NewPrivateMessageSubject"),
                                            NameTo = memberTo.UserName
                                        };

                                        var sb = new StringBuilder();
                                        sb.AppendFormat("<p>{0}</p>", string.Format(LocalizationService.GetResourceString("PM.NewPrivateMessageBody"), LoggedOnUser.UserName));
                                        email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());
                                        _emailService.SendMail(email);
                                    }

                                    return RedirectToAction("Index");
                                }
                                catch (Exception ex)
                                {
                                    unitOfWork.Rollback();
                                    LoggingService.Error(ex);
                                    ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.GenericMessage"));
                                }
                            }
                        }
                        else
                        {
                            // Error send back to user
                            ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("PM.UnableFindMember"));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("PM.TalkToSelf"));
                    }
                }
                TempData[AppConstants.MessageViewBagName] = null;
                return View(createPrivateMessageViewModel);
            }
        }
Esempio n. 10
0
 public void Delete(Email email)
 {
     _context.Email.Remove(email);
 }
Esempio n. 11
0
 public Email Add(Email email)
 {
     return _context.Email.Add(email);
 }
Esempio n. 12
0
 /// <summary>
 /// Send a single email
 /// </summary>
 /// <param name="email"></param>
 public void SendMail(Email email)
 {
     SendMail(new List<Email> { email });
 }
Esempio n. 13
0
 public void SendMail(Email email, Settings settings)
 {
     SendMail(new List<Email> { email }, settings);
 }
Esempio n. 14
0
        public ActionResult Create(CreatePrivateMessageViewModel createPrivateMessageViewModel)
        {
            if (!SettingsService.GetSettings().EnablePrivateMessages || LoggedOnUser.DisablePrivateMessages == true)
            {
                throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
            }
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                if (ModelState.IsValid)
                {
                    // Check flood control
                    var lastMessage = _privateMessageService.GetLastSentPrivateMessage(LoggedOnUser.Id);
                    if (lastMessage != null && DateUtils.TimeDifferenceInMinutes(DateTime.UtcNow, lastMessage.DateSent) < SettingsService.GetSettings().PrivateMessageFloodControl)
                    {
                        throw new Exception(LocalizationService.GetResourceString("PM.SendingToQuickly"));
                    }

                    var memberTo = MembershipService.GetUser(createPrivateMessageViewModel.To);

                    // first check they are not trying to message themself!
                    if (memberTo != null)
                    {
                        // Map the view model to message
                        var privateMessage = new PrivateMessage
                        {
                            UserFrom = LoggedOnUser,
                            Message = createPrivateMessageViewModel.Message,
                        };

                        // check the member
                        if (!String.Equals(memberTo.UserName, LoggedOnUser.UserName, StringComparison.CurrentCultureIgnoreCase))
                        {
                            // Check in box size for both
                            var receiverCount = _privateMessageService.GetAllReceivedByUser(memberTo.Id).Count;
                            if (receiverCount > SettingsService.GetSettings().MaxPrivateMessagesPerMember)
                            {
                                throw new Exception(string.Format(LocalizationService.GetResourceString("PM.ReceivedItemsOverCapcity"), memberTo.UserName));
                            }

                            // If the receiver is about to go over the allowance them let then know too
                            if (receiverCount > (SettingsService.GetSettings().MaxPrivateMessagesPerMember - SiteConstants.PrivateMessageWarningAmountLessThanAllowedSize))
                            {
                                // Send user a warning they are about to exceed
                                var sb = new StringBuilder();
                                sb.AppendFormat("<p>{0}</p>", LocalizationService.GetResourceString("PM.AboutToExceedInboxSizeBody"));
                                var email = new Email
                                {
                                    EmailTo = memberTo.Email,
                                    NameTo = memberTo.UserName,
                                    Subject = LocalizationService.GetResourceString("PM.AboutToExceedInboxSizeSubject")
                                };
                                email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());
                                _emailService.SendMail(email);
                            }

                            // Good to go send the message!
                            privateMessage.UserTo = memberTo;
                            _privateMessageService.Add(privateMessage);

                            try
                            {
                                // Finally send an email to the user so they know they have a new private message
                                // As long as they have not had notifications disabled
                                if (memberTo.DisableEmailNotifications != true)
                                {
                                    var email = new Email
                                    {
                                        EmailTo = memberTo.Email,
                                        Subject = LocalizationService.GetResourceString("PM.NewPrivateMessageSubject"),
                                        NameTo = memberTo.UserName
                                    };

                                    var sb = new StringBuilder();
                                    sb.AppendFormat("<p>{0}</p>", string.Format(LocalizationService.GetResourceString("PM.NewPrivateMessageBody"), LoggedOnUser.UserName));
                                    email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());
                                    _emailService.SendMail(email);
                                }

                                unitOfWork.Commit();

                                return PartialView("_PrivateMessage", privateMessage);
                            }
                            catch (Exception ex)
                            {
                                unitOfWork.Rollback();
                                LoggingService.Error(ex);
                                throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
                            }
                        }
                        else
                        {
                            throw new Exception(LocalizationService.GetResourceString("PM.TalkToSelf"));
                        }
                    }
                    else
                    {
                        // Error send back to user
                        throw new Exception(LocalizationService.GetResourceString("PM.UnableFindMember"));
                    }
                }
                throw new Exception(LocalizationService.GetResourceString("Errors.GenericMessage"));
            }
        }
Esempio n. 15
0
        public ActionResult SendTestEmail()
        {
            using (var uow = UnitOfWorkManager.NewUnitOfWork())
            {
                var sb = new StringBuilder();
                sb.AppendFormat("<p>{0}</p>",
                    string.Concat("This is a test email from ", SettingsService.GetSettings().ForumName));
                var email = new Email
                {
                    EmailTo = SettingsService.GetSettings().AdminEmailAddress,
                    NameTo = "Email Test Admin",
                    Subject = string.Concat("Email Test From ", SettingsService.GetSettings().ForumName)
                };
                email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());
                _emailService.SendMail(email);

                var message = new GenericMessageViewModel
                {
                    Message = "Test Email Sent",
                    MessageType = GenericMessages.success
                };

                try
                {
                    uow.Commit();
                }
                catch (Exception ex)
                {
                    uow.Rollback();
                    LoggingService.Error(ex);
                    message.Message = "Error sending email";
                    message.MessageType = GenericMessages.danger;
                }
                TempData[AppConstants.MessageViewBagName] = message;

                return RedirectToAction("Index");
            }
        }
Esempio n. 16
0
        public ActionResult ForgotPassword(ForgotPasswordViewModel forgotPasswordViewModel)
        {
            var changePasswordSucceeded = true;
            var currentUser = new MembershipUser();
            var newPassword = StringUtils.RandomString(8);

            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                if (ModelState.IsValid)
                {
                    currentUser = MembershipService.GetUserByEmail(forgotPasswordViewModel.EmailAddress);
                    if (currentUser != null)
                    {
                        changePasswordSucceeded = MembershipService.ResetPassword(currentUser, newPassword);

                        try
                        {
                            unitOfWork.Commit();
                        }
                        catch (Exception ex)
                        {
                            unitOfWork.Rollback();
                            LoggingService.Error(ex);
                            changePasswordSucceeded = false;
                        }
                    }
                    else
                    {
                        changePasswordSucceeded = false;
                    }
                }
            }

            // Success send newpassword to the user telling them password has been changed
            using (UnitOfWorkManager.NewUnitOfWork())
            {

                if (changePasswordSucceeded)
                {
                    var sb = new StringBuilder();
                    sb.AppendFormat("<p>{0}</p>", string.Format(LocalizationService.GetResourceString("Members.ForgotPassword.Email"), SettingsService.GetSettings().ForumName));
                    sb.AppendFormat("<p><b>{0}</b></p>", newPassword);
                    var email = new Email
                                    {
                                        EmailFrom = SettingsService.GetSettings().NotificationReplyEmail,
                                        EmailTo = currentUser.Email,
                                        NameTo = currentUser.UserName,
                                        Subject = LocalizationService.GetResourceString("Members.ForgotPassword.Subject")
                                    };
                    email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());
                    _emailService.SendMail(email);

                    // We use temp data because we are doing a redirect
                    TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                    {
                        Message = LocalizationService.GetResourceString("Members.ForgotPassword.SuccessMessage"),
                        MessageType = GenericMessages.success
                    };
                    return View();
                }

                ModelState.AddModelError("", LocalizationService.GetResourceString("Members.ForgotPassword.ErrorMessage"));
                return View(forgotPasswordViewModel);
            }
        }