public ActionResult ChangePass(string id, string newPassword, string confirmPassword)
        {


            Account_ChangePass viewChangePass = new Account_ChangePass();
            viewChangePass.ShowFieldSet = true;

            if (String.IsNullOrEmpty(id))
            {
                ViewData.ModelState.AddModelError("*", "There was an error processing this request.  Please refresh your browser and try again. If the problem persists, please go to the Forgot Password page and request another password reset.");
                viewChangePass.ShowFieldSet = false;
            }

            if (newPassword == null || newPassword.Length < Provider.MinRequiredPasswordLength)
            {
                ViewData.ModelState.AddModelError("newPassword", String.Format(CultureInfo.InvariantCulture,
                         "You must specify a new password of {0} or more characters.",
                         Provider.MinRequiredPasswordLength));
               
            }
            if (!String.Equals(newPassword, confirmPassword, StringComparison.Ordinal))
            {
                ViewData.ModelState.AddModelError("newPassword", "The new password and confirmation password do not match.");
               
            }

            if (ViewData.ModelState.IsValid)
            {

                
                var db = new UsersDataContext();
                var result = db.S1_Users_ForgotPassword_GetUserName(id).SingleOrDefault();

                if (result != null)
                {
                    // Attempt to change password
                    MembershipUser currentUser = Provider.GetUser(result.ForgotPasswordUserName, false);
                    bool changeSuccessful = false;
                    try
                    {
                        changeSuccessful =  currentUser.ChangePassword(currentUser.ResetPassword(result.ForgotPasswordAnswer), newPassword);
                    }
                    catch
                    {
                        // An exception is thrown if the new password does not meet the provider's requirements
                    }

                    if (changeSuccessful)
                    {
                           var db1 = new UsersDataContext();
                           var result1 = db1.S1_Users_ForgotPassword_RemoveGUID(id);

                           if (result1 != 0)
                           {
                               //log the error and notify admins
                           }
                           
                        string em = currentUser.Email;
                        string subject = ConfigurationManager.AppSettings["CompanyName"] + " Billing: Change Password Request";
                        int sUserID = 0;
                        string clientname = null;
                        string clientstate = null;
                        string clientzipcode = null;

                       var db2 = new UsersDataContext();
                       var q2 = from o in db.Users
                               where o.aspnet_User.UserName == result.ForgotPasswordUserName
                               select new
                               {
                                   sUID = o.UserID
                               };

                       if (q2.Count() > 0)
                       {

                            sUserID = q2.SingleOrDefault().sUID;

                            var db3 = new UsersDataContext();
                            var result3 = db3.S1_Users_GetClientContactForEmail(sUserID).SingleOrDefault();

                            if (result3 == null)
                            {

                                //todo;
                            }
                            else
                            {
                                clientname = result3.ClientName;
                                clientstate = result3.ContactState;
                                clientzipcode = result3.ContactZipCode;
                            }

                        }

                        Dictionary<string, string> messagevalues = new Dictionary<string, string>();
                        messagevalues.Add("[[COMPANYNAME]]", clientname);
                        messagevalues.Add("[[USERNAME]]", result.ForgotPasswordUserName);
                        messagevalues.Add("[[CORPORATENAME]]", System.Configuration.ConfigurationManager.AppSettings["CompanyName"]);

                        MailGun.SendEmailToUserFromTemplate(12, 0, "Change Password", 0, sUserID, 0, subject, messagevalues);

                        viewChangePass.sUserName = result.ForgotPasswordUserName;
                        return RedirectToAction("ChangePasswordSuccess", "Account", new { portal = ViewData["portal"], ClientID = ViewData["ClientID"] });

                        /* var messageRecord = Messages.GetMessageTemplateRecord(0, "Change Password", messagevalues);

                          string messagebody = messageRecord != null ? messageRecord.MessageText : null;

                          if (messagebody != null)
                          {
                              int messageActionType = messageRecord.MessageActionTypeID.GetValueOrDefault();
                              int? MessageIDOutput = new int?();
                              Guid? MessageActionGuidOutput = new Guid?();
                              Messages.CreateMessageWithAction(messageActionType, subject, messagebody, sUserID, 1, 0, 3, "", System.DateTime.Now, null, "HTML", ref MessageIDOutput, ref MessageActionGuidOutput);
                              Messages.UpdateMessageAndMarkForSending(MessageIDOutput.Value, subject, messagebody);
                              viewChangePass.sUserName = result.ForgotPasswordUserName;
                              return RedirectToAction("ChangePasswordSuccess", "Account", new { portal = ViewData["portal"], ClientID = ViewData["ClientID"] });
                          }
                          else
                          {
                              //todoo: future error logging
                          }*/
                    }
                }
                else
                {
                    ViewData.ModelState.AddModelError("*", "There was an error while trying to reset your password. Please refresh your browser and try again.");
                    
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["Title"] = "Change Password";

            return View("ConfirmedChangePass", "~/Views/Shared/Site.Master", viewChangePass);

        }
        public JsonResult ResetUserPasswordJSON(string OldUserName, int UserID, string UserNameEmail, bool Inactive)
        {
            //Check to see if the old and new names are the same
            if (OldUserName != UserNameEmail)
            {
                return(new JsonResult {
                    Data = new { success = false, error = "You must first save the changed username before sending email." }
                });
            }

            if (Inactive)
            {
                return(new JsonResult {
                    Data = new { success = false, error = "Please activate the user and save the change before attempting to reset the password." }
                });
            }

            Regex emailregex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,7}$");

            Match m = emailregex.Match(UserNameEmail);

            if (m.Success == false)
            {
                return(new JsonResult {
                    Data = new { success = false, error = "Invalid Email Format." }
                });
            }


            if (ViewData.ModelState.IsValid)
            {
                var db3     = new UsersDataContext();
                var result3 = db3.S1_Users_GetClientContactForEmail(UserID).SingleOrDefault();

                string ReturnURL       = "/Security/ChangePassword";
                string contactpassword = result3.ContactLastName.Substring(0, 3) + result3.ContactZipCode.Substring(0, 3) + result3.ContactState;

                MembershipUser mu = Provider.GetUser(result3.UserName, false);
                Provider.ChangePasswordQuestionAndAnswer(result3.UserName, contactpassword, "What is your Company's zipcode?", result3.ContactZipCode);
                Provider.UpdateUser(mu);


                string oldpassword = mu.ResetPassword();
                Provider.ChangePassword(result3.UserName, oldpassword, contactpassword);
                Provider.UpdateUser(mu);

                string subject = ConfigurationManager.AppSettings["CompanyName"] + " Billing: Account for " + result3.ContactFirstName + " " + result3.ContactLastName + " - " + result3.ClientName;


                var db1 = new UsersDataContext();
                //The following line is creating a message with a null status on purpose. Due to the actionGUID being used in the emails following. Note also this is S1_Users instead of S1_Messages
                var results1 = db1.S1_Users_CreateMessageWithAction(1, subject, result3.UserID, 1, 0, 3, HttpUtility.UrlDecode(ReturnURL), System.DateTime.Now, null).SingleOrDefault();

                if (results1.ActionGUID != null)
                {
                    Dictionary <string, string> messagevalues = new Dictionary <string, string>();
                    messagevalues.Add("[[USER_EMAIL]]", result3.Email);
                    messagevalues.Add("[[USERNAME]]", result3.UserName);
                    messagevalues.Add("[[COMPANYNAME]]", result3.ClientName);
                    messagevalues.Add("[[PASSWORD]]", contactpassword);
                    messagevalues.Add("[[GUIDURL]]", System.Configuration.ConfigurationManager.AppSettings["DefaultPath"] + "/Account/ConfirmEmail/" + results1.ActionGUID.ToString() + "?portal=client");
                    messagevalues.Add("[[CORPORATENAME]]", System.Configuration.ConfigurationManager.AppSettings["CompanyName"]);

                    MailGun.SendEmailToUserFromTemplate(10, 0, "Create Client Account", 0, result3.UserID, 0, subject, messagevalues);

                    subject = ConfigurationManager.AppSettings["CompanyName"] + " Billing: " + result3.ContactFirstName + " " + result3.ContactLastName + " - " + result3.ClientName;

                    MailGun.SendEmailToUserFromTemplate(11, 0, "Create Client Password", 0, result3.UserID, 0, subject, messagevalues);

                    return(new JsonResult {
                        Data = new { success = true, error = "Password has been resent and emailed to the user." }
                    });

                    /* var messageRecord = Messages.GetMessageTemplateRecord(0, "Create Client Account", messagevalues);
                     *
                     * string messagebody = messageRecord != null ? messageRecord.MessageText : null;
                     *
                     * if (messagebody != null)
                     * {
                     *   int messageActionType = messageRecord.MessageActionTypeID.GetValueOrDefault();
                     *   int? MessageIDOutput = new int?();
                     *   Guid? MessageActionGuidOutput = new Guid?();
                     *
                     *   //Send email with UserName
                     *   Messages.CreateMessageWithAction(messageActionType, subject, messagebody, result3.UserID, 1, 0, 3, HttpUtility.UrlDecode(ReturnURL), System.DateTime.Now, null, "HTML", ref MessageIDOutput, ref MessageActionGuidOutput);
                     *   Messages.UpdateMessageAndMarkForSending(MessageIDOutput.Value, subject, messagebody);
                     *
                     *   subject = ConfigurationManager.AppSettings["CompanyName"] + " Billing: " + result3.ContactFirstName + " " + result3.ContactLastName + " - " + result3.ClientName;
                     *
                     *   messageRecord = Messages.GetMessageTemplateRecord(0, "Create Client Password", messagevalues);
                     *
                     *   messagebody = messageRecord != null ? messageRecord.MessageText : null;
                     *
                     *   if (messagebody != null)
                     *   {
                     *       messageActionType = messageRecord.MessageActionTypeID.GetValueOrDefault();
                     *       MessageIDOutput = new int?();
                     *       MessageActionGuidOutput = new Guid?();
                     *
                     *       //Send email with Password
                     *       Messages.CreateMessageWithAction(messageActionType, subject, messagebody, result3.UserID, 1, 0, 3, HttpUtility.UrlDecode(ReturnURL), System.DateTime.Now, null, "HTML", ref MessageIDOutput, ref MessageActionGuidOutput);
                     *       Messages.UpdateMessageAndMarkForSending(MessageIDOutput.Value, subject, messagebody);
                     *   }
                     *
                     *   return new JsonResult { Data = new { success = true, error = "Password has been resent and emailed to the user." } };
                     *
                     * }
                     * else
                     * {
                     *   return new JsonResult { Data = new { success = false, error = "Unable to reset the password at this time. Please retry." } };
                     *
                     * }*/
                }
                else
                {
                    return(new JsonResult {
                        Data = new { success = false, error = "Unable to reset the password at this time. Please retry." }
                    });
                }
            }
            return(new JsonResult {
                Data = new { success = false, error = "Unable to reset the password at this time. Please retry." }
            });
        }