How to use multi threading in a For loop

How to use multi threading in a For loop
class Program
{

    static int workingCounter = 0;
    static int workingLimit = 10;
    static int processedCounter = 0;

    static void Main(string[] args)
    {
        string[] files = Directory.GetFiles("C:\\Temp");
        int checkCount = files.Length;
        foreach (string file in files)
        {
            //wait for free limit...
            while (workingCounter >= workingLimit)
            {
                Thread.Sleep(100);
            }
            workingCounter += 1;
            ParameterizedThreadStart pts = new ParameterizedThreadStart(ProcessFile);
            Thread th = new Thread(pts);
            th.Start(file);
        }
        //wait for all threads to complete...
        while (processedCounter< checkCount)
        {
            Thread.Sleep(100);
        }
        Console.WriteLine("Work completed!");
    }

    static void ProcessFile(object file)
    {
        try
        {
            Console.WriteLine(DateTime.Now.ToString() + " recieved: " + file + " thread count is: " + workingCounter.ToString());
            //make some sleep for demo...
            Thread.Sleep(2000);
        }
        catch (Exception ex)
        {
            //handle your exception...
            string exMsg = ex.Message;
        }
        finally
        {
            Interlocked.Decrement(ref workingCounter);
            Interlocked.Increment(ref processedCounter);
        }
    }
}

User Registration And Login Form With E-Mail Notification In MVC

User Registration And Login Form With E-Mail Notification In MVC

In this article, we will cover the User Registration and login form. Also, we will send an email notification for user verification and password recovery functionality with OTP. 

For this, we will cover the given topics in this article.
  • Registration form
  • Password Encryption
  • Email notification
  • Generate User verification link
  • Login form
  • Forget Password
  • Generate OTP
  • Change Password

So let's do it with a database table script as below.

Step 1

Create a User Registration table.

  1. CREATE TABLE [dbo].[UserM](  
  2.     [UserId] [int] IDENTITY(1,1) NOT NULL,  
  3.     [FirstName] [varchar](50) NOT NULL,  
  4.     [LastName] [varchar](50) NOT NULL,  
  5.     [Email] [nvarchar](50) NOT NULL,  
  6.     [Password] [nvarchar](250) NOT NULL,  
  7.     [EmailVerification] [bitNULL,  
  8.     [ActivetionCode] [uniqueidentifier] NULL,  
  9.     [OTP] [nvarchar](4) NULL,  
  10.  CONSTRAINT [PK_UserM] PRIMARY KEY CLUSTERED   
  11. (  
  12.     [UserId] ASC  
  13. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  14. ON [PRIMARY]  
  15.   
  16. GO 

Step 2

Now, open Visual Studio and create an empty project.
 
User Registration And Login Form With E-Mail Notification In MVC

Step 3

Add a folder in the project and after that, add an Entity Data Model as below.
 
User Registration And Login Form With E-Mail Notification In MVC

Step 4

Set up the database connection now.
 
User Registration And Login Form With E-Mail Notification In MVC

Step 5

Now, add a table as below.
 
User Registration And Login Form With E-Mail Notification In MVC

Now, click on the Finish button.

The generated model will look like below.

User Registration And Login Form With E-Mail Notification In MVC

Note
If Entity framework is not found in your project, you can download it from the NuGet Package Manager.

User Registration And Login Form With E-Mail Notification In MVC

After that, we will add a class for User Registration to the Models folder.

User Registration And Login Form With E-Mail Notification In MVC

Select and name the class as below.

User Registration And Login Form With E-Mail Notification In MVC

After this, we will set up a property for registration.

  1. namespace UserRegistration.Models  
  2. {  
  3.     public class UserRegistration  
  4.     {  
  5.         public string FirstName { getset; }          
  6.         public string LastName { getset; }  
  7.         public string Email { getset; }  
  8.         public string Password { getset; }  
  9.         public string ConfirmPassword { getset; }  
  10.     }  
  11. }   

Here, we wish to use the server side validation. So, we'll require System.ComponentModel.DataAnnotations.

User Registration And Login Form With E-Mail Notification In MVC

Now, let us set up the Validation property as below.

  1. public class UserRegistration    
  2. {       
  3.     [Required(AllowEmptyStrings = false, ErrorMessage = "First Name is requierd")]    
  4.     public string FirstName { getset; }    
  5.     [Required(AllowEmptyStrings = false, ErrorMessage = "Last Name is requierd")]    
  6.     public string LastName { getset; }    
  7.     [Required(AllowEmptyStrings = false, ErrorMessage = "Email ID is requierd")]    
  8.     public string Email { getset; }    
  9.     [Required(AllowEmptyStrings = false, ErrorMessage = "Password is requierd")]    
  10.     [DataType(DataType.Password)]    
  11.     [MinLength(6, ErrorMessage = "Need min 6 character")]    
  12.     public string Password { getset; }    
  13.     [Required(AllowEmptyStrings = false, ErrorMessage = "Confirm Password is requierd")]    
  14.     [DataType(DataType.Password)]    
  15.     [Compare("Password", ErrorMessage = "Confirm Password should match with Password")]    
  16.     public string ConfirmPassword { getset; }  
  17. } 

Confirm the password parameters shown here. These should be just for password confirmation which we will not save in the database.

Encrypt Password

For security, the password is always saved in an encrypted format. So, we'll add a class which will change the password into encryption format. Add this class in the Models folder.

 Select and name the class as below. 

User Registration And Login Form With E-Mail Notification In MVC

The class will look like this.

User Registration And Login Form With E-Mail Notification In MVC

We will add a return static method to make this class static.

Code snippet

  1. namespace UserRegistration.Models  
  2. {  
  3.     public static class encryptPassword  
  4.     {  
  5.         public static string textToEncrypt(string paasWord)  
  6.         {  
  7.             return Convert.ToBase64String(System.Security.Cryptography.SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(paasWord)));  
  8.         }  
  9.     }  
  10. }  

Now, we will add a controller for registration.

User Registration And Login Form With E-Mail Notification In MVC

Select and add an empty controller as below.

User Registration And Login Form With E-Mail Notification In MVC

Name the controlled and click on the "Add" button.

User Registration And Login Form With E-Mail Notification In MVC

The added controller will look like below.

User Registration And Login Form With E-Mail Notification In MVC

After this, use a model class for this controller and add a View.

User Registration And Login Form With E-Mail Notification In MVC

When clicking on the Add View, you will see the following dialog box.

User Registration And Login Form With E-Mail Notification In MVC

Select "Create" for the template field. After that, select the Model class as below.

User Registration And Login Form With E-Mail Notification In MVC 

Code snippet: User Registration

  1. @model UserRegistration.Models.UserRegistration  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>User Registration</h2>  
  8.   
  9. @using (Html.BeginForm())   
  10. {  
  11.     @Html.AntiForgeryToken()  
  12.       
  13.     <div class="form-horizontal">  
  14.   
  15.         <hr />  
  16.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  17.         <div class="form-group">  
  18.             @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })  
  19.             <div class="col-md-10">  
  20.                 @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })  
  21.                 @Html.ValidationMessageFor(model => model.FirstName, ""new { @class = "text-danger" })  
  22.             </div>  
  23.         </div>  
  24.   
  25.         <div class="form-group">  
  26.             @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })  
  27.             <div class="col-md-10">  
  28.                 @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })  
  29.                 @Html.ValidationMessageFor(model => model.LastName, ""new { @class = "text-danger" })  
  30.             </div>  
  31.         </div>  
  32.   
  33.         <div class="form-group">  
  34.             @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })  
  35.             <div class="col-md-10">  
  36.                 @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })  
  37.                 @Html.ValidationMessageFor(model => model.Email, ""new { @class = "text-danger" })  
  38.             </div>  
  39.         </div>  
  40.   
  41.        <div class="form-group">  
  42.             @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })  
  43.             <div class="col-md-10">  
  44.                 @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })  
  45.                 @Html.ValidationMessageFor(model => model.Password, ""new { @class = "text-danger" })  
  46.             </div>  
  47.         </div>  
  48.   
  49.         <div class="form-group">  
  50.             @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })  
  51.             <div class="col-md-10">  
  52.                 @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })  
  53.                 @Html.ValidationMessageFor(model => model.ConfirmPassword, ""new { @class = "text-danger" })  
  54.             </div>  
  55.         </div>  
  56.   
  57.         <div class="form-group">  
  58.             <div class="col-md-offset-2 col-md-10">  
  59.                 <input type="submit" value="Create" class="btn btn-default" />  
  60.             </div>  
  61.         </div>  
  62.     </div>  
  63. }  
  64. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  65. <script src="~/Scripts/jquery.validate.min.js"></script>  
  66. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  

Now, run the project.

User Registration And Login Form With E-Mail Notification In MVC

Here, you will find a registration form with validation. Now, we will see how it will insert records in the database.

First, set up the database entity connection.

User Registration And Login Form With E-Mail Notification In MVC

Then, add a POST method as below and add an object that will pass the data inside this method. Add a return static method which converts the password into an encrypted format.

  1. #region Registration post method for data save    
  2. [HttpPost]    
  3. public ActionResult Index(UserM objUsr)    
  4. {    
  5.     // email not verified on registration time    
  6.     objUsr.EmailVerification = false;    
  7.     //it generate unique code       
  8.     objUsr.ActivetionCode = Guid.NewGuid();    
  9.     //password convert    
  10.     objUsr.Password = UserRegistration.Models.encryptPassword.textToEncrypt(objUsr.Password);    
  11.     objCon.UserMs.Add(objUsr);    
  12.     objCon.SaveChanges();    
  13.     return View();    
  14. }    
  15. #endregion 

Live debugging screen

User Registration And Login Form With E-Mail Notification In MVC
 
User Registration And Login Form With E-Mail Notification In MVC

Here, you can see that the activation code is generating and password conversion is also found.

Below is the record that we have set.

User Registration And Login Form With E-Mail Notification In MVC

Check If Email Exists Or Not

    When we have created the registration form with e-mail ID, the email id must be unique. So, whenever we are registering, it is necessary to check whether e-mail id is there in our database or not.

    For that, we will use the below code.

    1. #region Check Email Exists or not in DB    
    2. public bool IsEmailExists(string eMail)    
    3. {                
    4.         var IsCheck = objCon.UserMs.Where(email => email.Email == eMail).FirstOrDefault();    
    5.         return IsCheck != null;                
    6. }    
    7. #endregion 

    Then, this method is put in the Action method as follows so can check before saving the data,

    User Registration And Login Form With E-Mail Notification In MVC

    If getting an e-mail, you will have to make a few changes in the VIEW to give information as follows,

    User Registration And Login Form With E-Mail Notification In MVC
    1. @Html.ValidationMessage("EmailExists"new { @class = "text-danger" })  

    Now the e-mail ID is already registered so try to re-register,

    User Registration And Login Form With E-Mail Notification In MVC

    Live debugging screen,

    User Registration And Login Form With E-Mail Notification In MVC

    Here, you get the message that you are trying to register an e-mail id that is already registered.

    User Registration And Login Form With E-Mail Notification In MVC

    Email Notification

      Now, we will see how to send an email after it is registered. When we mail, we will send a verification link with the email. Adjust the method.

      Code: SendEmailToUser

      1. public void SendEmailToUser(string emailId, string activationCode)    
      2. {    
      3.     var GenarateUserVerificationLink = "/Register/UserVerification/" + activationCode;    
      4.     var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, GenarateUserVerificationLink);    
      5.   
      6.     var fromMail = new MailAddress("rakeshchavda404@gmail.com""Rakesh"); // set your email    
      7.     var fromEmailpassword = "*******"// Set your password     
      8.     var toEmail = new MailAddress(emailId);    
      9.   
      10.     var smtp = new SmtpClient();    
      11.     smtp.Host = "smtp.gmail.com";    
      12.     smtp.Port = 587;    
      13.     smtp.EnableSsl = true;    
      14.     smtp.DeliveryMethod = SmtpDeliveryMethod.Network;    
      15.     smtp.UseDefaultCredentials = false;    
      16.     smtp.Credentials = new NetworkCredential(fromMail.Address, fromEmailpassword);    
      17.   
      18.     var Message = new MailMessage(fromMail, toEmail);    
      19.     Message.Subject = "Registration Completed-Demo";    
      20.     Message.Body = "<br/> Your registration completed succesfully." +    
      21.                    "<br/> please click on the below link for account verification" +    
      22.                    "<br/><br/><a href=" + link + ">" + link + "</a>";    
      23.     Message.IsBodyHtml = true;    
      24.     smtp.Send(Message);    
      25. } 

      After the data is saved, call this method.

      User Registration And Login Form With E-Mail Notification In MVC

      Then, add a Registration View to display the message.

      User Registration And Login Form With E-Mail Notification In MVC
       
      User Registration And Login Form With E-Mail Notification In MVC

      The message can be shown as below after adding the View.

      User Registration And Login Form With E-Mail Notification In MVC

      Code snippet

      1. @{  
      2.     ViewBag.Title = "Registration";  
      3. }  
      4.   
      5. <h2>Registration Complete</h2>  
      6.   
      7. <div class="alert-success">  
      8.    <strong>Message: </strong> @ViewBag.Message  
      9. </div>  

      After the registration is successful, the message will appear like this.

      User Registration And Login Form With E-Mail Notification In MVC
      After successful registration, the email with a verification link is sent.
       
      User Registration And Login Form With E-Mail Notification In MVC

      The code for verification is mentioned below.

      Code: UserVerification

      1. #region Verification from Email Account.    
      2. public ActionResult UserVerification(string id)    
      3. {    
      4.     bool Status = false;    
      5.   
      6.     objCon.Configuration.ValidateOnSaveEnabled = false// Ignor to password confirmation     
      7.     var IsVerify = objCon.UserMs.Where(u => u.ActivetionCode == new Guid(id)).FirstOrDefault();    
      8.   
      9.     if (IsVerify != null)    
      10.     {    
      11.         IsVerify.EmailVerification = true;    
      12.         objCon.SaveChanges();    
      13.         ViewBag.Message = "Email Verification completed";    
      14.         Status = true;    
      15.     }    
      16.     else    
      17.     {    
      18.         ViewBag.Message = "Invalid Request...Email not verify";    
      19.         ViewBag.Status = false;    
      20.     }    
      21.   
      22.     return View();    
      23. }    
      24. #endregion 

      Now, add the HTML view for controller.

      1. @{  
      2.     ViewBag.Title = "UserVerification";  
      3. }  
      4.   
      5. <h2>User Verification Process</h2>  
      6.   
      7.     <div class="danger alert-danger">  
      8.         <strong>Message..!!</strong>  @ViewBag.Message,  please click here to Login @Html.ActionLink("Login""Login""Register")  
      9.     </div>   

      It will be redirected to the browser when clicking on the verification link.

      Live debug

      User Registration And Login Form With E-Mail Notification In MVC
       
      User Registration And Login Form With E-Mail Notification In MVC

      In the table, see the verification flag has changed after verification,

      User Registration And Login Form With E-Mail Notification In MVC

      User Login Form

      Now, let's get a user login process.

      Add a class for the login process and set the property of the login.

      Set Class properties

      1. using System;  
      2. using System.Collections.Generic;  
      3. using System.ComponentModel.DataAnnotations;  
      4. using System.Linq;  
      5. using System.Web;  
      6.   
      7. namespace UserRegistration.Models  
      8. {  
      9.     public class UserLogin  
      10.     {  
      11.         [Display(Name = "User Email ID")]  
      12.         [Required(AllowEmptyStrings = false, ErrorMessage = "User Email Id Required")]  
      13.           
      14.         public string EmailId { getset; }  
      15.         [Display(Name = "Password")]  
      16.         [DataType(DataType.Password)]  
      17.         [Required(AllowEmptyStrings = false, ErrorMessage = "Password Required")]  
      18.         public string Password { getset; }  
      19.   
      20.         [Display(Name = "Remember Me")]  
      21.         public bool Rememberme { getset; }  
      22.     }  
      23. }   

      Now, add an HTML View for users to login. Select "Create" for the template.

      Then, select a Model class for user login and click on the Add button.

      User Registration And Login Form With E-Mail Notification In MVC

      Login View code snippet

      1. @model UserRegistration.Models.UserLogin  
      2.   
      3. @{  
      4.     ViewBag.Title = "Login";  
      5. }  
      6.   
      7. <h2>Login</h2>
      8. @using (Html.BeginForm())   
      9. {  
      10.     @Html.AntiForgeryToken()  
      11.       
      12.     <div class="form-horizontal">  
      13.         <hr />  
      14.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
      15.         <div class="form-group">  
      16.             @Html.LabelFor(model => model.EmailId, htmlAttributes: new { @class = "control-label col-md-2" })  
      17.             <div class="col-md-10">  
      18.                 @Html.EditorFor(model => model.EmailId, new { htmlAttributes = new { @class = "form-control" } })  
      19.                 @Html.ValidationMessageFor(model => model.EmailId, ""new { @class = "text-danger" })  
      20.             </div>  
      21.         </div>  
      22.   
      23.         <div class="form-group">  
      24.             @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })  
      25.             <div class="col-md-10">  
      26.                 @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })  
      27.                 @Html.ValidationMessageFor(model => model.Password, ""new { @class = "text-danger" })  
      28.             </div>  
      29.         </div>  
      30.   
      31.         <div class="form-group">  
      32.             @Html.LabelFor(model => model.Rememberme, htmlAttributes: new { @class = "control-label col-md-2" })  
      33.             <div class="col-md-10">  
      34.                 <div class="checkbox">  
      35.                     @Html.EditorFor(model => model.Rememberme)  
      36.                     @Html.ValidationMessageFor(model => model.Rememberme, ""new { @class = "text-danger" })  
      37.                 </div>  
      38.             </div>  
      39.         </div>  
      40.   
      41.         <div class="form-group">  
      42.             <div class="col-md-offset-2 col-md-10">  
      43.                 <input type="submit" value="Create" class="btn btn-default" />  
      44.             </div>  
      45.         </div>  
      46.     </div>  
      47. }  
      48.   
      49. <div>  
      50.     @Html.ActionLink("Back to List""Index")  
      51. </div>  
      52.   
      53. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
      54. <script src="~/Scripts/jquery.validate.min.js"></script>  
      55. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  

      Now, run the code and check it.

      User Registration And Login Form With E-Mail Notification In MVC

      Here, you can see that the login form works nicely with validation.

      Now, we will add a login POST method. Inside this method, we will check whether the user is appropriate or not; and generate a cookie for checkbox- Remember Me.

      Login Code Snippet

      1. [HttpPost]    
      2. public ActionResult Login(UserLogin LgnUsr)    
      3. {    
      4.     var _passWord = UserRegistration.Models.encryptPassword.textToEncrypt(LgnUsr.Password);    
      5.     bool Isvalid = objCon.UserMs.Any(x => x.Email == LgnUsr.EmailId && x.EmailVerification == true &&    
      6.     x.Password == _passWord);    
      7.     if (Isvalid)    
      8.     {    
      9.         int timeout = LgnUsr.Rememberme ? 60 : 5; // Timeout in minutes, 60 = 1 hour.    
      10.         var ticket = new FormsAuthenticationTicket(LgnUsr.EmailId, false, timeout);    
      11.         string encrypted = FormsAuthentication.Encrypt(ticket);    
      12.         var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);    
      13.         cookie.Expires = System.DateTime.Now.AddMinutes(timeout);    
      14.         cookie.HttpOnly = true;     
      15.         Response.Cookies.Add(cookie);    
      16.         return RedirectToAction("Index""UserDash");    
      17.     }    
      18.     else    
      19.     {    
      20.         ModelState.AddModelError("""Invalid Information... Please try again!");    
      21.     }    
      22.     return View();    
      23. } 

      The authorized user should be redirected to the homepage after successfully logged in.

      So, we will add the user Home Controller as follows,

      User Registration And Login Form With E-Mail Notification In MVC

      Here, we will use the Authorize attribute for security purposes.

      User Registration And Login Form With E-Mail Notification In MVC

      Now, we will add an empty View.

      User Registration And Login Form With E-Mail Notification In MVC

      Add a logout button to the View.

      View Code snippet

      1. @{  
      2.     ViewBag.Title = "Index";  
      3. }  

      Hello, @HttpContext.Current.User.Identity.Name

      1. <h2>Welcome....</h2>  
      2.   
      3. @if (Request.IsAuthenticated)  
      4. {   
      5.     <a href='@Url.Action("LogOut", "Register")' onclick='navigate(this.href);'>  
      6.         <input style="float: right;" type="button" value='Logout' />  
      7.     </a>  
      8. }  

      Check it now with the browser.

      User Registration And Login Form With E-Mail Notification In MVC

      Live debug screen: for cookie generation.

      User Registration And Login Form With E-Mail Notification In MVC

      You can see here that the user has been successfully logged in and the cookie generated is found in the browser.

      User Registration And Login Form With E-Mail Notification In MVC
       
      User Registration And Login Form With E-Mail Notification In MVC

      Now, we need a logout code for application log out. For logout, add a logout method in the controller, as shown below.

      Logout code

      1. [Authorize]  
      2. public ActionResult LogOut()  
      3. {  
      4.     FormsAuthentication.SignOut();  
      5.     return RedirectToAction("Login""Register");  
      6. }  

      For a login process, we use a form authentication mode, so need few changes as below in web.config. Here you can see set an authentication mode and set default login URL. 

      User Registration And Login Form With E-Mail Notification In MVC 
      1. <authentication mode="Forms">  
      2.       <forms cookieless="UseCookies" loginUrl="Register/Login"></forms>  
      3. </authentication>  

      Forget Password

      Now, let's see how to develop a method for "Forgot Password" functionality.

      First, add a class.

      User Registration And Login Form With E-Mail Notification In MVC

      Then, set the e-mail property for password recovery.

      Code snippet

      1. using System.ComponentModel.DataAnnotations;  
      2. namespace UserRegistration.Models  
      3. {  
      4.     public class ForgetPassword  
      5.     {  
      6.         [Display(Name = "User Email ID")]  
      7.         [Required(AllowEmptyStrings = false, ErrorMessage = "User Email Id Required")]  
      8.         public string EmailId { getset; }  
      9.     }  
      10. }  

      Then, add a method for the "forget password" functionality.

      Code snippet

      1. public ActionResult ForgetPassword()  
      2. {  
      3.     return View();  
      4. }  

      Then, create the HTML view using the above method.

      User Registration And Login Form With E-Mail Notification In MVC

      VIEW Code Snippet

      1. @model UserRegistration.Models.ForgetPassword  
      2.   
      3. @{  
      4.     ViewBag.Title = "ForgetPassword";  
      5. }  
      6.   
      7. <h2>ForgetPassword</h2>  
      8.   
      9. @using (Html.BeginForm())   
      10. {  
      11.     @Html.AntiForgeryToken()      
      12.     <div class="form-horizontal">  
      13.         <hr />  
      14.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
      15.         <div class="form-group">  
      16.             @Html.LabelFor(model => model.EmailId, htmlAttributes: new { @class = "control-label col-md-2" })  
      17.             <div class="col-md-10">  
      18.                 @Html.EditorFor(model => model.EmailId, new { htmlAttributes = new { @class = "form-control" } })  
      19.                 @Html.ValidationMessageFor(model => model.EmailId, ""new { @class = "text-danger" })  
      20. @Html.ValidationMessage("EmailNotExists"new { @class = "text-danger" })  
      21.             </div>  
      22.         </div>  
      23.   
      24.         <div class="form-group">  
      25.             <div class="col-md-offset-2 col-md-10">  
      26.                 <input type="submit" value="Create" class="btn btn-default" />  
      27.             </div>  
      28.         </div>  
      29.     </div>  
      30. }  
      31.   
      32. <div>  
      33.     @Html.ActionLink("Back to List""Index")  
      34. </div>  
      35.   
      36. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
      37. <script src="~/Scripts/jquery.validate.min.js"></script>  
      38. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  

      Now, we will add a POST method to set the "forget password". Using this method, we will generate the OTP and then send an email to the user with password change URL. Inside this method, we will also check whether the user's mail id is correct or not.

      Adjust first post method,

      Code snippet

      1. [HttpPost]    
      2. public ActionResult ForgetPassword(ForgetPassword pass)    
      3. {    
      4.     var IsExists = IsEmailExists(pass.EmailId);    
      5.     if (!IsExists)    
      6.     {    
      7.         ModelState.AddModelError("EmailNotExists""This email is not exists");    
      8.         return View();    
      9.     }    
      10.     var objUsr = objCon.UserMs.Where(x => x.Email == pass.EmailId).FirstOrDefault();    
      11.   
      12.     // Genrate OTP     
      13.     string OTP = GeneratePassword();    
      14.   
      15.     objUsr.ActivetionCode = Guid.NewGuid();    
      16.     objUsr.OTP = OTP;    
      17.     objCon.Entry(objUsr).State = System.Data.Entity.EntityState.Modified;    
      18.     objCon.SaveChanges();    
      19.   
      20.     ForgetPasswordEmailToUser(objUsr.Email, objUsr.ActivetionCode.ToString(), objUsr.OTP);    
      21.     return View();    
      22. } 

      The following methods are used to generate OTP.

      Code snippet

      1. public string GeneratePassword()    
      2. {    
      3.     string OTPLength = "4";    
      4.     string OTP = string.Empty;    
      5.   
      6.     string Chars = string.Empty;    
      7.     Chars = "1,2,3,4,5,6,7,8,9,0";    
      8.   
      9.     char[] seplitChar = { ',' };    
      10.     string[] arr = Chars.Split(seplitChar);    
      11.     string NewOTP = "";    
      12.     string temp = "";    
      13.     Random rand = new Random();    
      14.     for (int i = 0; i < Convert.ToInt32(OTPLength); i++)    
      15.     {    
      16.         temp = arr[rand.Next(0, arr.Length)];    
      17.         NewOTP += temp;    
      18.         OTP = NewOTP;    
      19.     }    
      20.     return OTP;    
      21. } 

      The following methods are used to mail with OTP and change URL.

      User Registration And Login Form With E-Mail Notification In MVC

      In the login.cshtml page, make a small change for page redirection.

      User Registration And Login Form With E-Mail Notification In MVC
      1. @Html.ActionLink("Registration""Index") ||  
      2.        @Html.ActionLink("Reset Passward""ForgetPassword")  

      Let’s execute the project and check.

      User Registration And Login Form With E-Mail Notification In MVC

      Now, click "Reset Password".

      User Registration And Login Form With E-Mail Notification In MVC

      Then click on the Reset button.

       After that, check the email.

      User Registration And Login Form With E-Mail Notification In MVC

      Thus, you can see the URL and OTP in the mail.

      Change Password

      Add a class and then set the "change password" property for password recovery.

      User Registration And Login Form With E-Mail Notification In MVC 

      Code snippet

      1. using System.ComponentModel.DataAnnotations;  
      2. namespace UserRegistration.Models  
      3. {  
      4.     public class ChangePassword  
      5.     {  
      6.         [Required(AllowEmptyStrings = false, ErrorMessage = "OTP is requierd")]  
      7.         public string OTP { getset; }  
      8.   
      9.         [Required(AllowEmptyStrings = false, ErrorMessage = "Password is requierd")]  
      10.         [DataType(DataType.Password)]  
      11.         [MinLength(6, ErrorMessage = "Need min 6 char")]  
      12.         public string Password { getset; }  
      13.   
      14.         [Required(AllowEmptyStrings = false, ErrorMessage = "Confirm Password is requierd")]  
      15.         [DataType(DataType.Password)]  
      16.         [Compare("Password", ErrorMessage = "Confirm Password should match with Password")]  
      17.         public string ConfirmPassword { getset; }  
      18.     }  
      19. }  

      Now, add a method inside the controller for "change password" and for using this method, add an HTML view.

      User Registration And Login Form With E-Mail Notification In MVC
      1. @model UserRegistration.Models.ChangePassword  
      2.   
      3. @{  
      4.     ViewBag.Title = "ChangePassword";  
      5. }  
      6.   
      7. <h2>ChangePassword</h2>  
      8. @using (Html.BeginForm())   
      9. {  
      10.     @Html.AntiForgeryToken()  
      11.       
      12.     <div class="form-horizontal">  
      13.         <h4>ChangePassword</h4>  
      14.         <hr />  
      15.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
      16.         <div class="form-group">  
      17.             @Html.LabelFor(model => model.OTP, htmlAttributes: new { @class = "control-label col-md-2" })  
      18.             <div class="col-md-10">  
      19.                 @Html.EditorFor(model => model.OTP, new { htmlAttributes = new { @class = "form-control" } })  
      20.                 @Html.ValidationMessageFor(model => model.OTP, ""new { @class = "text-danger" })  
      21.             </div>  
      22.         </div>  
      23.   
      24.         <div class="form-group">  
      25.             @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })  
      26.             <div class="col-md-10">  
      27.                 @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })  
      28.                 @Html.ValidationMessageFor(model => model.Password, ""new { @class = "text-danger" })  
      29.             </div>  
      30.         </div>  
      31.   
      32.         <div class="form-group">  
      33.             @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })  
      34.             <div class="col-md-10">  
      35.                 @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })  
      36.                 @Html.ValidationMessageFor(model => model.ConfirmPassword, ""new { @class = "text-danger" })  
      37.             </div>  
      38.         </div>  
      39.   
      40.         <div class="form-group">  
      41.             <div class="col-md-offset-2 col-md-10">  
      42.                 <input type="submit" value="Change Password" class="btn btn-default" />  
      43.             </div>  
      44.         </div>  
      45.     </div>  
      46. }  
      47.   
      48. <div>  
      49.     @Html.ActionLink("Login""Login")  
      50. </div>  
      51.   
      52. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
      53. <script src="~/Scripts/jquery.validate.min.js"></script>  
      54. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  

      Now, click on the change password URL to open the mail. 

      So, the following screen will open.

      User Registration And Login Form With E-Mail Notification In MVC

      Now, change your password here by setting up the OTP found in the mail.