Saturday, March 10, 2018

Part 52 - How to use Automapper in Asp.net MVC




In this video you will be able to know about how to use Automapper in  Asp.net MVC. 

#AutoMapper Initialization (AutomapperWebProfile.cs)
 Create a folder Infrastructure in the root folder of the project and create a class AutomapperWebProfile and copy below code into this.

using MVCTutorial.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCTutorial.Infrastructure
{
    public class AutomapperWebProfile : AutoMapper.Profile
    {
        public AutomapperWebProfile()
        {

            CreateMap<EmployeeDomainModel, EmployeeViewModel>();

            CreateMap<EmployeeViewModel, EmployeeDomainModel>();

        }

        public static void Run()
        {
            AutoMapper.Mapper.Initialize(a =>
            {
                a.AddProfile<AutomapperWebProfile>();


            });
        }

       

    }
}

#EmployeeDomainModel.cs 
Create below class into Model folder

 public class EmployeeDomainModel
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }

    }

# EmployeeViewModel.cs 

Create below class into Model folder

public class EmployeeViewModel
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
       
    }


# Controller Code (TestController.cs)
Create a Test controller and in your Index method write below code. Here, I have added few record in EmployeeDomainModel and using AutoMapper, I copied data into EmployeeViewModel directly. In this way you can use Automapper. 

        public ActionResult Index()
        {
            List<EmployeeDomainModel> empDomainList = new List<EmployeeDomainModel>();

            empDomainList.Add(new EmployeeDomainModel { EmployeeId = 1, Name = "Ashish" });
            empDomainList.Add(new EmployeeDomainModel { EmployeeId = 2, Name = "Ajay" });
            
            List<EmployeeViewModel> empVMList = new List<EmployeeViewModel>();            
            
            AutoMapper.Mapper.Map(empDomainList, empVMList);

            return View();
        }



#Global.asax file
Add below code into Application_Start() Method. to Initialize Automapper and to create map between source and destination folder. 

  AutomapperWebProfile.Run();

Thanks  . Keep Learning and Sharing


All Code Factory


Thursday, March 8, 2018

Part 51 - Send OTP ( One Time Password ) to any mobile number in Asp.net MVC



In this video you will be able to know how to send OTP ( One time password) to any mobile number.  You need to follow below steps

1. Visit  TextLocal  official website and Register yourself
2. Generate API Key as show in video

3. Use your API key in C# MVC to send OTP via textlocal API 

Please copy below codes after generating API key.

# View Page (Index.cshtml)
Right click on your controller' s Index method and add a view. After adding view, replace content with below code. 

@model MVCTutorial.Models.EmployeeViewModel
@{
    ViewBag.Title = "Index";
    // Layout = null;
}

        <div class="well">
           
            <a href="#" class="btn btn-success" onclick="SendOTP()">Send OTP</a>

        </div>

<script>


    var SendOTP = function () {
        
        $.ajax({
            url: "/Test/SendOTP",
            type: "post",
            success: function (data) {
                if (data == "success") {
                    
                    alert("OTP sent successfully");
                    window.location = "/Test/EnterOTP";
                }
                else {
                    alert("failed");
                }
            }


        })

    }

</script>




# Controller Code (TestController.cs)
Create a Test controller and copy below code into this. 

using ASPSnippets.SmsAPI;
using MVCTutorial.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace MVCTutorial.Controllers
{
    public class TestController : Controller
    {
        public ActionResult Index()
        {         

            return View();
        }

      
        public JsonResult SendOTP()
        {
            int otpValue = new Random().Next(100000, 999999);
            var status = "";
            try
            {
                string recipient =  ConfigurationManager.AppSettings["RecipientNumber"].ToString();
                string APIKey = ConfigurationManager.AppSettings["APIKey"].ToString();

                string message = "Your OTP Number is " + otpValue + " ( Sent By : Technotips-Ashish )";
                String encodedMessage = HttpUtility.UrlEncode(message);

                using (var webClient = new WebClient())
                {
                    byte[] response = webClient.UploadValues("https://api.textlocal.in/send/", new NameValueCollection(){
                                        
                                         {"apikey" , APIKey},
                                         {"numbers" , recipient},
                                         {"message" , encodedMessage},
                                         {"sender" , "TXTLCL"}});

                    string result = System.Text.Encoding.UTF8.GetString(response);

                    var jsonObject = JObject.Parse(result);

                    status = jsonObject["status"].ToString();

                    Session["CurrentOTP"] = otpValue;
                }


                return Json(status, JsonRequestBehavior.AllowGet);


            }
            catch (Exception e)
            {

                throw (e);

            }

        }

        public ActionResult EnterOTP()
        {
            return View();
        }
        
        [HttpPost]
        public JsonResult VerifyOTP(string otp)
        {
            bool result = false;

            string sessionOTP = Session["CurrentOTP"].ToString();

            if (otp == sessionOTP)
            {
                result = true;

            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

    }
}




#Web.Config file
Add two keys into your web.config file . In first key, Enter Your API key generated by textlocal.com website . In second key, Enter your mobile number as recipient  with country code. example: 919234567895 . You can get mobile number either from database or from the textbox in which user enter his mobile number.


  <add key="APIKey" value="Enter your API key here" />
  <add key="RecipientNumber" value="91XXXXXXXXXX" />
  



All Code Factory