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 activate links after sending an email of an activation link to the user using MVC and Web API. I have explained in the previous article how to send activation link in an email after user inputs their registration details in MVC. When we activate the link, then the activation code matches with the one in our database. If matched, it will activate the profile; otherwise, it doesn't.
You can check this link to the previous article  
Before we start this discussion, let us remember some points regarding email sending functionality.
  1. First, we check that our email id should not have a 2-step verification added.
  2. Enable less secure apps to access accounts.
    • -> Sign in to your Gmail account.
    • ->Click Security > Basic settings.
    • ->Under Less secure apps, select Go to settings for less secure apps.
    • ->In the sub-window, select the "Allow users to manage their access to less secure apps" radio button.
So now, let us see the required steps.
Step 1
First, see the activation link we have sent in the previous article.

Step 2 
When clicking this link, first, it will go our RegsterUser Controller in MVC project and also, it will send the Controller name, Action method and parameter value, i.e., Activation code. 
Finally, we can see our code and also, we will call RunAsyncGet method which we created in RestClient Class.
[System.Web.Mvc.HttpGet]  
       public async Task<ActionResult> ActivateAccount(string id)  
       {  
           string str = "";  
           RestClient restClient = new RestClient();  
           string value = await restClient.RunAsyncGet<string, string>("api/UserReg/VeryFiyAccount", id);  
  
           if (value != null)  
           {  
               str = value;  
           }  
           else  
           {  
               str = "Activation falid";  
           }  
           ViewBag.Message = str;  
           return View();    
       }  
Now, right-click on ActicationAcount method and add a View for displaying a user-friendly message and write the below code.
<link href="~/Content/bootstrap.css" rel="stylesheet" />  
<div style="height:70%;margin:100px;padding:150px;border:2px solid green;box-shadow:yellow 2px inset;border-radius:10px;" align="center">  
  
    @if (ViewBag.Message != null)  
    {  
        <div class="alert alert-success">  
            <strong>Success !</strong><b>@ViewBag.Message </b>  
        </div>  
    }  
    else  
    {  
        <div class="alert alert-danger">  
            <strong>Error!</strong>  
        </div>  
    }  
</div>
Here, we create a method RunAsyncGet in RestClient Class for consuming the API.
 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<U> RunAsyncGet<T, U>(dynamic uri, dynamic data)  
       {  
           HttpResponseMessage response = await this.client.GetAsync(uri + "/" + data);  
           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);  
       }  
Step 3
NoteWhen we write the method for consuming the service in the server side, then some time is needed to update the System.Net.Http.Formatting.Extension. So, for this, go to Tools >> NuGet Package Manager and then Package Manager console.

After that, we will write code for updating "Install-Package System.Net.Http.Formatting.Extension -Version 5.2.3" on console.
Step 4
After that, we will create a method in RegAPI Controller for creating the service.
[HttpGet]  
        [Route("VeryFiyAccount/{id}")]  
        public string VeryfiyUserAccount(string id)  
        {  
            string str = "";  
            try  
            {  
                str = objReg.VeryFiyAccount(id);  
            }  
            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 str;  
        }  
Step 5
Now, we will go to RegLogic class in a Business logic folder and write the below code. 
Before we write this logic, we will check in our database table that EmalVeryFyField is false.
public string VeryFiyAccount(string activationCode)  
    {  
  
        string str = "";  
        objEntity.Configuration.ValidateOnSaveEnabled = false;  
        var value = objEntity.RegDetails.Where(a => a.ActivateionCode == new Guid(activationCode)).FirstOrDefault();  
        if (value != null)  
        {  
            value.EmailIVeryFied = true;  
            objEntity.SaveChanges();  
            str = "Dear user, Your email successfully activated now you can able to login";  
        }  
        else  
        {  
            str = "Dear user, Your email not activated";  
        }  
  
        return str;  
  
    }  
After that, we will get the final output.
We will check also in our database that emailVeryFyFied is true.

No comments: