public JsonResult CreateClientUserPost(Security_Users viewSecuritySetup, FormCollection fc)
        {
            int    newuserclientid = Convert.ToInt32(fc["primarycompany"]);
            string newuserrole     = fc["usertypelist"];

            // Basic parameter validation
            if (String.IsNullOrEmpty(viewSecuritySetup.firstname))
            {
                ViewData.ModelState.AddModelError("firstname", " ");
                ViewData.ModelState.AddModelError("*", "Please enter a firstname.");
            }

            if (String.IsNullOrEmpty(viewSecuritySetup.lastname))
            {
                ViewData.ModelState.AddModelError("lastname", " ");
                ViewData.ModelState.AddModelError("*", "Please enter a lastname.");
            }

            if (String.IsNullOrEmpty(viewSecuritySetup.username))
            {
                ViewData.ModelState.AddModelError("username", " ");
                ViewData.ModelState.AddModelError("*", "Please enter a username.");
            }

            if (String.IsNullOrEmpty(viewSecuritySetup.email))
            {
                ViewData.ModelState.AddModelError("email", " ");
                ViewData.ModelState.AddModelError("*", "Please enter an email address.");
            }
            else
            {
                Regex emailregex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,7}$");

                Match m = emailregex.Match(viewSecuritySetup.email);
                if (m.Success == false)
                {
                    ViewData.ModelState.AddModelError("email", " ");
                    ViewData.ModelState.AddModelError("*", "Invalid email format.");
                }
            }

            if (viewSecuritySetup.password == null || viewSecuritySetup.password.Length < Provider.MinRequiredPasswordLength)
            {
                ViewData.ModelState.AddModelError("password", " ");
                ViewData.ModelState.AddModelError("*", String.Format(CultureInfo.InvariantCulture,
                                                                     "A password of {0} or more characters is required.",
                                                                     Provider.MinRequiredPasswordLength));
            }

            if (!String.Equals(viewSecuritySetup.password, viewSecuritySetup.confirmPassword, StringComparison.Ordinal))
            {
                ViewData.ModelState.AddModelError("confirmPassword", " ");
                ViewData.ModelState.AddModelError("*", "The password and confirmation do not match.");
            }

            if (ViewData.ModelState.IsValid)
            {
                string subject       = ConfigurationManager.AppSettings["CompanyName"] + " Billing: New Account";
                string clientname    = null;
                string clientaddr1   = null;
                string clientaddr2   = null;
                string clientcity    = null;
                string clientstate   = null;
                string clientzipcode = null;

                // Attempt to register the user
                MembershipCreateStatus createStatus;
                MembershipUser         newUser = Provider.CreateUser(viewSecuritySetup.username, viewSecuritySetup.password, viewSecuritySetup.email,
                                                                     "client", "client", true, null, out createStatus);

                if (newUser != null)
                {
                    var db     = new UsersDataContext();
                    var result = db.S1_Users_CreateUser(viewSecuritySetup.username, newuserclientid, 1, viewSecuritySetup.firstname, viewSecuritySetup.lastname).SingleOrDefault();
                    if (result.UserID > 0)
                    {
                        Roles.AddUserToRole(viewSecuritySetup.username, newuserrole);

                        if (String.IsNullOrEmpty(HttpUtility.UrlDecode(viewSecuritySetup.ReturnUrl)))
                        {
                            viewSecuritySetup.ReturnUrl = "/Account/Logon?portal=admin";
                        }

                        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 = db.S1_Users_CreateMessageWithAction(1, subject, result.UserID, 1, 0, 3, HttpUtility.UrlDecode(viewSecuritySetup.ReturnUrl), System.DateTime.Now, null).SingleOrDefault();

                        if (results1.ActionGUID != null)
                        {
                            string ReturnURL = "/Account/ConfirmEmail";

                            var db3     = new ClientsDataContext();
                            var result3 = db3.S1_Clients_GetClientsFromUser(result.UserID).SingleOrDefault();

                            if (result3 == null)
                            {
                                //todo;
                            }
                            else
                            {
                                clientname    = result3.ClientName;
                                clientaddr1   = result3.Address1;
                                clientaddr2   = result3.Address2;
                                clientcity    = result3.City;
                                clientstate   = result3.State;
                                clientzipcode = result3.ZipCode;
                            }

                            Provider.ChangePasswordQuestionAndAnswer(viewSecuritySetup.username, viewSecuritySetup.password, "What is your Company's zipcode?", clientzipcode);

                            Dictionary <string, string> messagevalues = new Dictionary <string, string>();
                            messagevalues.Add("[[USER_FIRSTNAME]]", "");
                            messagevalues.Add("[[USER_MI]]", "");
                            messagevalues.Add("[[USER_LASTNAME]]", "");
                            messagevalues.Add("[[USER_TITLE]]", "");
                            messagevalues.Add("[[COMPANY_ADDRESS_LINE1]]", clientaddr1);
                            messagevalues.Add("[[COMPANY_ADDRESS_LINE2]]", clientaddr2);
                            messagevalues.Add("[[COMPANY_ADDRESS_CITY]]", clientcity);
                            messagevalues.Add("[[COMPANY_ADDRESS_STATE]]", clientstate);
                            messagevalues.Add("[[COMPANY_ADDRESS_ZIPCODE]]", clientzipcode);
                            messagevalues.Add("[[USER_EMAIL]]", viewSecuritySetup.email);
                            messagevalues.Add("[[USER_PHONE]]", "");
                            messagevalues.Add("[[USERNAME]]", viewSecuritySetup.username);
                            messagevalues.Add("[[COMPANYNAME]]", clientname);
                            messagevalues.Add("[[GUIDURL]]", System.Configuration.ConfigurationManager.AppSettings["DefaultPath"] + ReturnURL + "/" + results1.ActionGUID.ToString() + "?portal=client");
                            messagevalues.Add("[[CORPORATENAME]]", System.Configuration.ConfigurationManager.AppSettings["CompanyName"]);

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

                            return(new JsonResult {
                                Data = new { success = true }
                            });

                            /*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?();
                             *
                             *  Messages.CreateMessageWithAction(messageActionType, subject, messagebody, result.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 } };
                             * }
                             * else
                             * {
                             *  ModelState.AddModelError("*", "There was a problem sending the confirmation email.  Please re-create a new account.  We apologize for the inconvenience.");
                             *  HandleCreateClientUserErrors(viewSecuritySetup, fc);
                             *  return new JsonResult
                             *  {
                             *      Data = new
                             *      {
                             *          success = false,
                             *          view = RenderToString.RenderViewToString(this, "CreateClientUser", viewSecuritySetup)
                             *      }
                             *  };
                             * }*/
                        }

                        ModelState.AddModelError("*", "There was a problem sending the confirmation email.  Please re-create a new account.  We apologize for the inconvenience.");
                        HandleCreateClientUserErrors(viewSecuritySetup, fc);
                        return(new JsonResult
                        {
                            Data = new
                            {
                                success = false,
                                view = RenderToString.RenderViewToString(this, "CreateClientUser", viewSecuritySetup)
                            }
                        });
                    }
                    else
                    {
                        ModelState.AddModelError("*", ErrorHandler.ErrorCodeToString(createStatus));
                        HandleCreateClientUserErrors(viewSecuritySetup, fc);
                        return(new JsonResult
                        {
                            Data = new
                            {
                                success = false,
                                view = RenderToString.RenderViewToString(this, "CreateClientUser", viewSecuritySetup)
                            }
                        });
                    }
                }
                else
                {
                    ViewData.ModelState.AddModelError("*", ErrorHandler.ErrorCodeToString(createStatus));
                    HandleCreateClientUserErrors(viewSecuritySetup, fc);
                    return(new JsonResult
                    {
                        Data = new
                        {
                            success = false,
                            view = RenderToString.RenderViewToString(this, "CreateClientUser", viewSecuritySetup)
                        }
                    });
                }
            }
            return(new JsonResult
            {
                Data = new
                {
                    success = false,
                    view = RenderToString.RenderViewToString(this, "CreateClientUser", viewSecuritySetup)
                }
            });
            //return new JsonResult { Data = new { success = true } };
        }
        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." }
            });
        }