Thursday, 9 June 2016

How to send SMS from asp.net MVC appliction

Description:
To fulfill this requirement I am using Twilio restful API service.

Implementation:


First of all create a account on Twilio and verify your phone number. Now configure a number for messaging. You can also buy a preferred number.

Add Twilio DLL

Now add the Twilio DLL to project. Here I will add this to project through Nuget. Run the below command in Package manager console:
                  Install-package twilio
Add Controller

Now add a empty controller to project. Import the Twilio namespace and write the below given code to send SMS.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Twilio;
namespace MVC_Project.Controllers
{
    public class SendSMSController : Controller
    {
        //
        // GET: /SendSMS/
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult SendSMS()
        {
            return View();
        }
        [HttpPost]
        public ActionResult SendSMS(string phone,string message)


        {
            string AccountSid  = "Account ID";
            string Token = "Auth Token";
            var twilio = new TwilioRestClient(AccountSid , Token);
            string number = "+91" + phone;
            var send = twilio.SendSmsMessage("+13183901909", number, message);
            TempData["successful"] = "SMS send Successfully";
            return RedirectToAction("sendsms");
        }
    }
}

Add View

Add view for send SMS and design as code given below:

@{
    ViewBag.Title = "Send SMS";
    var message = TempData["successful"];
}
<h2>Send SMS</h2>
@using (Html.BeginForm())
{
    <table>
        <tr><td>Enter phone No. :</td><td>@Html.TextBox("phone","",new {@placeholder="Phone Number",style="width:200px"})</td></tr>
        <tr><td>Message</td><td>@Html.TextArea("message", "", new { @placeholder = "Message", style = "width:200px;height:150px" })</td></tr>
        <tr><td></td><td><input type="submit" value="Send Message" /></td></tr>
    </table>   
}
<script type="text/javascript">
    var message = '@message';
    if(message)
        alert(message);
</script>
You have done it. Now build and run the application. To test it send sms to your mobile number.

Note: Trial account will send SMS to verified phone number.

Model validation example to validate email address in MVC

In this article I am going to explain how to validate the email address of users in MVC application using Data Annotation
Model validation example to validate email address in MVC

Description:
We can validate the email address using data annotation regular expression.  Add the below given code before email address property in model (specific class).

[Required(ErrorMessage="Enter Correct Email")]
[DataType(DataType.EmailAddress)]
[RegularExpression(@"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", ErrorMessage = "Invalid email")]

Implement:


First of all import the namespace
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
Model (Employee.cs) :
public partial class Employee
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
         [Required]
        [DataType(DataType.PhoneNumber)]
        public Nullable<int> Phone { get; set; }
         [Required]
         public Nullable<int> Salary { get; set; }
          [Required]
        public string Department { get; set; }
        [Required(ErrorMessage="Enter Correct Email")]
        [DataType(DataType.EmailAddress)]
        [RegularExpression(@"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", ErrorMessage = "Invalid email")]
        public string EmailId { get; set; }
[Required]
public string ImagePath { get; set; }
    }

In controller to validate the data we call the Modelstate.Isvalid. It check the validation errors.

Controller (EmployeeController.cs)
[HttpPost]
public ActionResult Create(Employee objemployee, HttpPostedFileBase file)
        {
            if(ModelState.IsValid)
            {
            }
            return View(objemployee);
        }
In view we have to enable the validation summary: @Html.ValidationSummary(true)

View (create.cshtml):
@model MVC_Project.Models.Employee
@{
    ViewBag.Title = "Create";
}


<h2>Create</h2>
@using (Html.BeginForm("Create","Employee",FormMethod.Post, new{enctype = "multipart/form-data"}))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Employee1</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Phone)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Phone)
            @Html.ValidationMessageFor(model => model.Phone)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Salary)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Salary)
            @Html.ValidationMessageFor(model => model.Salary)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Department)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Department)
            @Html.ValidationMessageFor(model => model.Department)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.EmailId)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EmailId)
            @Html.ValidationMessageFor(model => model.EmailId)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.ImagePath)
        </div>
        <div class="editor-field">
            <input type="file" name="file" id="ImagePath" accept=".png,.jpg,.jpeg" />
            @Html.ValidationMessageFor(model => model.ImagePath)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
} 
<div>
    @Html.ActionLink("Back to List", "Index")


</div>