We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Thursday, July 19, 2018

Today, in this article, I will explain how to send an activation link on the email id after user registration using MVC and Web API. In real time, often, we see that after registration by the user, it will send a code to the registered email id and when we click this link, then it will activate our email id. Actually, what happens behind this is when we register our details, the system will send an activation code on email id and also saves the same link or code in our database and when we activate our email id, then it will check and match that with our database entry. If matched, it will activate the profile, otherwise it doesn't.
So now, let us see the required steps. I will explain in the next article how to successfully activate the email Id.
Step 1
We need to create two tables - one for RegistrationDetails and a second for Department.
Step2
Now, we need to create an MVC application but we will create two projects here - First for Web API project for the creation of service and the second is MVC project for consuming that service. So now, let us add the first MVC project.
Open Visual Studio and go to File->New ->Web application ->select MVC ->OK.
Step 3
Now, add tables in Web API project using Entity Framework. For this, go to Models folder ->right-click -> Add -> New item -> ADO.NET Entity Data Model -> click Add -> select database first approach->click Next.
Select "New Connection" and give the connection details, then select database -> click OK.
Choose tables and click OK.
Step 4
Now, we will write the logic for binding the department so, I create a folder, Business Logic, and take a class RegLogic.cs to write the logic for binding.
But before that, we add a folder in the Models folder. l will create a partial class of RegDetail.cs and add some properties for finding the address of the local URL.
 namespace EmailActivationAPI.Models
{
    public partial class RegDetail
    {
        public string scheme { get; set; }
        public string host { get; set; }
        public string port { get; set; }
    }
}
After that, we will write the logic.
public List<Department> BindDept()
{
    EmployeeDBEntities objEntity = new EmployeeDBEntities();
    return objEntity.Departments.ToList();

}
Again, we will write the logic for inserting the user details in RegLogic.cs class.
public string RegisterUser(RegDetail objReg)
{
    objReg.EmailIVeryFied = false;
    objReg.ActivateionCode = Guid.NewGuid();
    EmployeeDBEntities objEntity = new EmployeeDBEntities();
    objEntity.RegDetails.Add(objReg);
    int i = objEntity.SaveChanges();

    if (i > 0)
    {
        SendVerificationLinkEmail(objReg.EmailId, objReg.ActivateionCode.ToString(), objReg.scheme, objReg.host, objReg.port);
        return "Registration has been done,And Account activation link" + "has been sent your eamil id:" + objReg.EmailId;
    }
    else
    {
        return "Registration has been Failed";
    }

}
After that, we will write code for sending the activation code on email id.
private void SendVerificationLinkEmail(string emailId, string activationcode, string scheme, string host, string port)
{
    var varifyUrl = scheme + "://" + host + ":" + port + "/JobSeeker/ActivateAccount/" + activationcode;
    var fromMail = new MailAddress("your email id", "welcome mithilesh");
    var toMail = new MailAddress(emailId);
    var frontEmailPassowrd = "your password";
    string subject = "Your account is successfull created";
    string body = "<br/><br/>We are excited to tell you that your account is" +
" successfully created. Please click on the below link to verify your account" +
" <br/><br/><a href='" + varifyUrl + "'>" + varifyUrl + "</a> ";

    var smtp = new SmtpClient
    {
        Host = "smtp.gmail.com",
        Port = 587,
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential(fromMail.Address, frontEmailPassowrd)

    };
    using (var message = new MailMessage(fromMail, toMail)
    {
        Subject = subject,
        Body = body,
        IsBodyHtml = true
    })
        smtp.Send(message);

}
Step5
After that, we will add an API Controller in Web API project.

Now, we can see the our Web API project architecture.
Now, we have to write the WebAPI code.
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Net.Http;  
using System.Web.Http; 
using EmailActivationAPI.Models; 
using EmailActivationAPI.BusinessLogic; 
 
namespace EmailActivationAPI.Controllers
{
    [RoutePrefix("api/UserReg")]
    public class RegAPIController : ApiController
    {
        RegLogic objReg = new RegLogic();

        [HttpPost]
        [Route("RegUser")]
        public string RegisterUser(RegDetail data)
        {
            string strObj;
            try
            {
                strObj = objReg.RegisterUser(data);
            }
            catch (ApplicationException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });
            }

            return strObj;
        }
        [HttpGet]
        [Route("BindDepartment")]
        public List<Department> DeptBind()
        {
            List<Department> objDept = new List<Department>();
            try
            {
                objDept = objReg.BindDept();
            }
            catch (ApplicationException ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });
            }

            return objDept;
        }
    }
}
Step 6
Now, let's go to the MVC project and add a Controller.
This is our MVC project architecture.
After that, create an action method and right click and add a View and View page.
public async Task<ActionResult> RegisterDetails()
{
    await DepartmentData();
    return View();

}
Now, we have to add the Model class. So here, I added two classes, the first Department.cs  and second Register.cs
Department.cs
public class Department
{
    public int DeptId { get; set; }
    public string DeptName { get; set; }
    public string Location { get; set; }

}
Register.cs
public class Register
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
    public string EmailId { get; set; }
    public string Password { get; set; }
    public string MobileNo { get; set; }
    public string PineCode { get; set; }
    public string Address { get; set; }
    public int DeptID { get; set; }
    public string scheme { get; set; }
    public string host { get; set; }
    public string port { get; set; }

}
Here, we will add a separate class for writing the logic for consuming the API service. So right-click on the Models folder and add a class RestClient.cs and write logic
public class RestClient
{
    private HttpClient client;
    public const string ApiUri = "http://localhost:49619/";
    public const string MediaTypeJson = "application/json";
    public const string RequestMsg = "Request has not been processed";
    public static string ReasonPhrase { get; set; }
    public RestClient()
    {
        this.client = new HttpClient();
        this.client.BaseAddress = new Uri(ApiUri);
        this.client.DefaultRequestHeaders.Accept.Clear();
        this.client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeJson));
    }
    public async Task<List<U>> RunAsyncGetAll<T, U>(dynamic uri)
    {
        HttpResponseMessage response = await this.client.GetAsync(uri);
        if (response.IsSuccessStatusCode)
        {
            return await response.Content.ReadAsAsync<List<U>>();
        }
        else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
        {
            throw new ApplicationException(response.ReasonPhrase);
        }
        else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway)
        {
            throw new Exception(response.ReasonPhrase);
        }

        throw new Exception(RequestMsg);
    }
    public async Task<U> RunAsyncPost<T, U>(string uri, T entity)
    {
        HttpResponseMessage response = client.PostAsJsonAsync(uri, entity).Result;
        ReasonPhrase = response.ReasonPhrase;
        if (response.IsSuccessStatusCode)
        {
            return await response.Content.ReadAsAsync<U>();
        }
        else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
        {
            throw new ApplicationException(response.ReasonPhrase);
        }
        else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway)
        {
            throw new Exception(response.ReasonPhrase);
        }
        throw new Exception(RequestMsg);

    }  
Now we will write two methods, the first for the binding department and the second for inserting the user details
private RestClient restClient = new RestClient();
public async Task DepartmentData()
{
    var value = await this.restClient.RunAsyncGetAll<Department, Department>("api/UserReg/BindDepartment");

    List<Department> lstDept = new List<Department>();

    ViewBag.DeptDetails = new SelectList(value, "DeptId", "DeptName");


}
[HttpPost]
public async Task<ActionResult> RegisterDetails(Register objReg)
{
    await DepartmentData();
    objReg.scheme = Request.Url.Scheme;
    objReg.host = Request.Url.Host;
    objReg.port = Request.Url.Port.ToString();
    var value = await this.restClient.RunAsyncPost<Register, string>("api/UserReg/RegUser", objReg);
    TempData["Message"] = value;
    return RedirectToAction("SendLink");
}
At last, we will create an action method in RegsterUser Controller
public ActionResult SendLink()
{
    ViewBag.Message = TempData["Message"].ToString();
    return View();

}
Let us run the project. We have to run both projects at the same time so we have to set some changes.
Right-click on the solution project and go to properties. There, check the "Multiple startup projects" option and click "Apply".
Now, finally, run the project and insert the user details.
When clicking the create button it displays the user-friendly message.


After this, we will check the user email id.

And also, we will check our database.

Conclusion
In this article, I explained how to send an activation link on email id after the registration of the user details. In the next article, I will explain how to activate the activation code after sending the link on the email id.




No comments: