August 2017 ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Thursday, 31 August 2017

How to create user registration page using asp.net mvc 5

20:12:00 Posted by raviteja swayampu No comments
In previous posts we saw how to create registration page in mvc5 using jquery.Current post gives you step by step instructions to create user registration page in mvc5 with model binding.you can also see registration and login pages created by other front end technologies like angular js along with mvc5.
Registration page using angular js in mvc5
login page using angular js in mvc5
Now come to the current application Creating user registration page in mvc5 with model binding.

user registration page using mvc 5

1.Create asp.net web application with empty mvc template.
2.Add database to App_Data folder.And add table with below schema.
CREATE TABLE [dbo].[TRegistration] (
    [Id]       INT            IDENTITY (1, 1) NOT NULL,
    [Name]     NVARCHAR (MAX) NOT NULL,
    [UserName] NVARCHAR (MAX) NOT NULL,
    [Password] NVARCHAR (MAX) NOT NULL,
    [Email]    NVARCHAR (MAX) NOT NULL,
    [Contact]  NVARCHAR (20)  NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);
2.Add Entity data model in models folder.
a) Go to Solution Explorer --> Models folder-- > Add --> New item --> Select ADO.net Entity Data       Model under data --> Enter model name --> Add.
b) A popup window will come (Entity Data Model Wizard) --> Select Generate from database -->           Next -->Chose your data connection --> select your database-- > next --> Select tables -->
     enter Model Namespace --> Finish.
3.Modify Model class file to perform form validations using data annotations.if you do not know how to perform validations using data annotations click below link.
Jquery validations using data annotations in mvc
 public partial class TRegistration
    {
        [Key]
        public int Id { get; set; }

        [Required(ErrorMessage ="Name Required",AllowEmptyStrings =false)]
        [DataType(DataType.Text)]
        public string Name { get; set; }

        [Required(ErrorMessage ="Username Required",AllowEmptyStrings =false)]
        [DataType(DataType.Text)]
        public string UserName { get; set; }

        [Required(ErrorMessage ="Password Required",AllowEmptyStrings =false)]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Required(ErrorMessage ="Email Required")]
        [DataType(DataType.EmailAddress)]       
        public string Email { get; set; }

        [Required(ErrorMessage = "Contact Required")]
        [DataType(DataType.PhoneNumber)]
        public string Contact { get; set; }
    }
when we click on submit button without entering any data validations will fire like in below pic.


registration page in aspdotnet mvc5

Add controller and action methods

4.Create a controller by right click on controller folder --> Add --> Controller --> Select Empty controller template --> name it.
5.Here in controller class i created two action methods 1.Index(HttpGet) and 2.Index(HttpPost).
6.First Index action method renders index view to display registration form and second index action method saves the user entered data to database table.
HomeController.cs:
 public class HomeController : Controller
    {     
        //Renders Index.cshtml page   
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        //Saves the user record to database..
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(TRegistration userrecord)
        {
            string encryptedpassword = CommonUtils.Encrypt(userrecord.Password);
            userrecord.Password = encryptedpassword;
            if (ModelState.IsValid)
            {
                try
                {
                    using (DatabaseEntities db = new DatabaseEntities())
                    {
                        db.TRegistrations.Add(userrecord);
                        db.SaveChanges();
                        ViewBag.Msg = "Record Inderted Successfully";
                    }
                }
                catch(Exception ex)
                {
                    throw ex;
                }
            }
            return View();
        }
    }
7.Here in above code i encrypted password before saving to database.see How to encrypt and decrypt password in c# to know about how to implement encryption and decryption asp.net mvc web applications.

Add View to display form

8.Now add index.cshtml page to solution which displays registration form.
9.Now add below code to index.cshtml page.

index.cshtml:
@model RegistrationUsingAspDotNetMVC.Models.TRegistration

@{
    ViewBag.Title = "Index";
}

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>Registration Using Model Binding</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Contact, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Contact, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
10.Finally enter some data in form and click submit button.We will get success message "Record inserted successfully" like below.

registration page in aspdotnet mvc5
11.Download source code for this application from here Download.

Conclusion:

I hope this tutorial will help you .To get more updates please subscribe to this blog subscribe. OR follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Wednesday, 30 August 2017

How to Encrypt and Decrypt password in C#

06:16:00 Posted by raviteja swayampu , 2 comments
In this article i will explain how to encrypt and decrypt password in C Sharp.In web applications we must encrypt developers encrypt(using encryption key) password before saving it to database.At the same time they decrypt password to compare user entered data during web login.
For Encryption and Decryption here i am using AES algoritham and symmetric key encryption and decryption.

Firstly the original text (text entered by user) i.e. clear text is converted into bytes and then for the AES algorithm to perform encryption, we need to generate Key and for using the derived bytes and the symmetric key.
namespace used for this process is using System.Security.Cryptography;
Using MemoryStream and CryptoStream the clear text is encrypted and written to byte array and finally the byte array is converted to Base64String and returned which is the final outcome.

Encryption and Decryption using C Sharp

1.Create a asp.net mvc web application with predefined templates available in visual studio.
2.Create a Controller and name it as HomeController.cs.
3.In HomeController i added two methods Encrypt and Decrypt methods.Encrypt method to encrypt text and Decrypt to decrypt text and Index action to render Index.cshtml page.
HomeController.cs:
public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult Encrypt(string Password)
        {
            string encryptedpassword = CommonUtils.Encrypt(Password);
            return Json(encryptedpassword, JsonRequestBehavior.AllowGet);
        }
        public JsonResult Decrypt(string Password)
        {
            string decryptedpassword = CommonUtils.Decrypt(Password);
            return Json(decryptedpassword, JsonRequestBehavior.AllowGet);
        }
    }
4.Add view page to index action by right click on index action --> add view --> name it.
5.Add Jquery reference library to index page.The design of the index page is look like below.

encrypt and decrypt password in C#

6.Here,when we click on Encrypt button the text entered in first textbox(ex:welcome) is encrypted and will displayed in second textbox like above picture.

Index.cshtml:
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<h3 class="text-info">Password Encryption and Decryption</h3>
<table>
    <tr>
        <td><input type="text" style="width:400px;" class="form-control" placeholder="Enter password to Encrypt" id="txtencrypt" /></td>
        <td><button class="btn btn-default" id="btnEncrypt">Encrypt</button></td>
    </tr>
    <tr>
        <td><input type="text" style="width:400px;" class="form-control" placeholder="Enter password to Decrypt" id="txtdecrypt" /></td>
        <td><button class="btn btn-default" id="btnDecrypt">Decrypt</button></td>
    </tr>
</table>
7.Add below script to send data entered in textboxes to server and server data to view using Jquery ajax methods.
$(document).ready(function () {
        $("#btnEncrypt").click(function () {
            var url="@Url.Action("Encrypt", "Home")";
            $.post(url,{Password:$.trim($("#txtencrypt").val())},function(data){
                if(data!=null){
                    $("#txtdecrypt").val(data);
                }
            });
        });
        $("#btnDecrypt").click(function () {
            var url="@Url.Action("Decrypt", "Home")";
            $.post(url,{Password:$.trim($("#txtdecrypt").val())},function(data){
                if(data!=null){
                    $("#txtencrypt").val(data);
                }
            });
        });
    });
8.Now it's time to add encryption and decryption code to solution.Right click solution --> add --> class file --> name it as CommonUtils.cs.
9.This static class contains static methods to perform Encryption and Decryption actions on given text.The source code is given below.

CommonUtils.cs:
public static class CommonUtils
    {
        public static string Encrypt(string clearText)
        {
            string EncryptionKey = "MITECHRAVI";
            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    clearText = Convert.ToBase64String(ms.ToArray());
                }
            }
            return clearText;
        }

        public static string Decrypt(string cipherText)
        {
            string EncryptionKey = "MITECHRAVI";
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }
            }
            return cipherText;
        }
    }
10.The namespace used here is System.Security.Cryptography.
11.In above code i am encrypting and decrypting given text with key"MITECHRAVI".
12.Download source code this application from here Download.

Conclusion:

I hope this tutorial will help you .To get more updates please subscribe to this blog subscribe. OR follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Friday, 25 August 2017

Registration page using Jquery in asp.net mvc

03:59:00 Posted by raviteja swayampu , No comments
Hi every one in this we gonna implement Registration page in asp.net mvc website.We already learn how to implement registration,login page using angular js in asp.net website in this blog.
1.Registration page using angular js
2.Login page using angular js
In this tutorial we gonna implement registration page using Jquery. In real time application development it is not possible to implement model binding every where in web application.In case of a web page contains multiple forms,dynamic forms we go for jquery to save data from front end to database.Now lets see in step by step manner.

Registration page using Jquery in asp.net mvc

1.Create a asp.net mvc web project by select empty mvc template.

2.Add a database in AppData folder and create a table and name it as Customer.
3.Database script is as follows..
CREATE TABLE [dbo].[Customer] (
    [Id]                INT           IDENTITY (1, 1) NOT NULL,
    [Name]              NVARCHAR (50) NOT NULL,
    [UserName]          NVARCHAR (50) NOT NULL,
    [Password]          NVARCHAR (50) NOT NULL,
    [Email]             NVARCHAR (50) NOT NULL,
    [Contact]           BIGINT        NOT NULL,
    [Gender]            NVARCHAR (10) NOT NULL,
    [Country]           NVARCHAR (20) NOT NULL,
    [ConfirmNewsLetter] BIT           NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);
4.Add Entity data model in models folder.
  a) Go to Solution Explorer --> Models folder-- > Add --> New item --> Select ADO.net Entity Data       Model under data --> Enter model name --> Add.
  b) A popup window will come (Entity Data Model Wizard) --> Select Generate from database -->           Next -->Chose your data connection --> select your database-- > next --> Select tables -->
     enter Model Namespace --> Finish.
5.Add controller and name it as HomeController and add Index() action method to render Index.cshtml page.SaveRecords() to save the records to database.
HomeController.cs:
public class HomeController : Controller
    {
        public ActionResult Index()
        {
            List _list = new List()
            {
                new SelectListItem {Text="--Select Country--" ,Value="" },
                new SelectListItem {Text="India",Value="India" },
                new SelectListItem {Text="Jermany",Value="Jermany" },
                new SelectListItem {Text="USA",Value="USA" },
                new SelectListItem {Text="Russia",Value="Russia" },
                new SelectListItem {Text="Japan",Value="Japan" }
            };
            ViewBag.Country = _list;
            return View();
        }
        public JsonResult SaveRecords(Customer customer)
        {
            bool result = false;
            if (customer != null)
            {
                using (DatabaseEntities db=new DatabaseEntities())
                {
                    db.Customers.Add(customer);
                    db.SaveChanges();
                    result = true;
                }
            }
            return Json(result,JsonRequestBehavior.AllowGet);
        }
    }
6.Now to add view to index action method by right click on index action and add view.
7.Below is the index view code after some design modification done.

Index.cshtml:
@model RegistrationUsingJquery.Models.Customer

@{
    ViewBag.Title = "Index";
}
<script type="text/javascript">
    var url = "@Url.Action("SaveRecords","Home")";
</script>
<script src="~/Scripts/app.js"></script>
@using (Html.BeginForm())
{
    <div class="form-horizontal">
        <h4 class="text-info">Registration Using Jquery</h4>
        <hr />
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger", id = "spnName" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger",id="spnUserName" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control"} })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger",id="spnPassword" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger", id = "spnEmail" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Contact, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Contact, "", new { @class = "text-danger", id = "spnContact" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.RadioButtonFor(model=>model.Gender,"Male")<label>Male</label>
                @Html.RadioButtonFor(model => model.Gender, "Female")<label>Female</label>
                @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger", id = "spnGender" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Country",ViewBag.Country as List<SelectListItem>,new { @class="form-control"})
                @Html.ValidationMessageFor(model => model.Country, "", new { @class = "text-danger", id = "spnCountry" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ConfirmNewsLetter, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.ConfirmNewsLetter)
                    @Html.ValidationMessageFor(model => model.ConfirmNewsLetter, "", new { @class = "text-danger", id = "spnConfirmNewsLetter" })
                </div>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" onclick="SaveRecord();" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}
registration-page-using-jquery-in-asp.netmvc-mitechdev.com

Add Jquery script code to validate and save data in DB

8.Right click on scripts --> add javascript file--> name it as app.js.
9.Enter below script code in app.js file.


//Form validation function
function validateform() {
    var result = true;
    var emailReg = /^([\w-\.][email protected]@([\w-]+\.)+[\w-]{2,4})?$/i;
    var phoneReg = /([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})/;

    if ($("#Name").val() == "") {
        $("#spnName").text("Full Name Required");
        result = false;
    } else {
        $("#spnName").text("");
    }
    if ($("#UserName").val() == "") {
        $("#spnUserName").text("UserName Required");
        result = false;
    } else {
        $("#spnUserName").text("");
    }
    if ($("#Password").val() == "") {
        $("#spnPassword").text("Password Required");
        result = false;
    } else {
        $("#spnPassword").text("");
    }
    if ($("#Email").val() == "") {
        $("#spnEmail").text("Email Required");
        result = false;
    }
        //validating email with regular expression
    else if (!emailReg.test($.trim($("#txtEmail").val()))) {
        $("#spnEmail").text("Valid Email Required");
        result = false;
    } else {
        $("#spnEmail").text("");
    }
    if ($("#Contact").val() == "") {
        $("#spnContact").text("Contact Required");
        result = false;
    }
        //validating phone number with regular expression
    else if (!phoneReg.test($.trim($("#Contact").val()))) {
        $("#spnContact").text("Valid Contact Required");
        result = false;
    } else {
        $("#spnContact").text("");
    }
    //validating radio button checked or not
    if (!$("input[name='Gender']:checked").val()) {
        $("#spnGender").text("Select Gender");
        result = false;
    } else {
        $("#spnGender").text("");
    }
    //validating checkbox
    if ($("#ConfirmNewsLetter").prop('checked') == false) {
        $("#spnConfirmNewsLetter").text("Select Policy");
        result = false;
    } else {
        $("#spnConfirmNewsLetter").text("");
    }
    //validating dropdownlist
    if ($("#Country").val() == "") {
        $("#spnCountry").text("Select country");
        result = false;
    } else {
        $("#spnCountry").text("");
    }
    return result;
}

function SaveRecord() {
    if (validateform()) {
        var customer = {
            Name: $("#Name").val(),
            UserName: $("#UserName").val(),
            Password: $("#Password").val(),
            Email: $("#Email").val(),
            Contact: $("#Contact").val(),
            Gender: $("input[name='Gender']:checked").val(),
            Country: $("#Country").val(),
            ConfirmNewsLetter: $("#ConfirmNewsLetter").val()
        };
        $.post(url, { customer: customer }, function (data) {
            if (data == true) {
                alert("Record inserted successfully");
            }
            else {
                alert("Record insertion failed");
            }
        });
    }
}
10.Here, validateform() method validates the form.SaveRecord() method sends the for data to server to save in database.in above code i created customer object to hold form data.here we can use a form collection object also but Form collection object sends all elements of form including unnecessary elements also.So,it is a wast of memory that's why i created a java script object here.
Note: The fields of java script object(customer in above script code) and properties of the receiving object in controller action method must be same(SaveRecord(Customer customer) action method).
11.I performed validations for this form using jquery.Click here to know how to implement jquery validations on real time web applications.We can also implement validations using data annotations also.
12.The records inserted in database are look like below.
Download source code for this applications Download(VS2015)

registration-page-using-jquery-in-asp.netmvc-mitechdev.com

Conclusion:

I hope this tutorial will help you .To get more updates please subscribe to this blog subscribe. OR follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Tuesday, 22 August 2017

How to validate a form in realtime using jquery

05:38:00 Posted by raviteja swayampu No comments
Hi every one welcome again with another real time application.In this post we will see about how to perform validations on forms using Jquery.You know there are many ways to perform validations on data entry forms in ASP.NET MVC for example,
1.Using Data Annotations
2.Using Validation plugins
But in real time developers do not consider the option of validation using data annotations.There are some limitations in using Data annotations.It destroys the layout structure if the validation message is long.And developers go for validation plugins for specific purposes only.for example if client wants validations messages to be displayed as tool tips that time they opt one jquery plugin that fits for his functionality.Generally they for jquery normal validations.

Validating form with Jquery:

Requirements:Jquery library(i used v1.10.2),Bootstrap3 for styling form.Add both references in _Layout.cshtml page.
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
In this post we will see how to perform validations on form using jquery.
1.I created a html form that contains most used html controls like textbox,radio button,checkboxes etc.
2.I used Bootstrap Css framework to style it.see the below code.
3.Index.cshtml:
@{
    ViewBag.Title = "Index";
}
<style type="text/css">
    input{max-width:500px;}
</style>
<h3 class="text-info">Realtime Form Validation Using Jquery</h3>

<div class="container">
    <div class="row">
        <form id="frmRegistration">
            <div class="form-group">
                <label class="text-info">Full Name:</label>
                <input type="text" class="form-control" id="txtFullName" onkeypress="return blockSpecialChar(event);" />
                <span style="color:red;" id="spntxtFullName"></span>
            </div>
            <div class="form-group">
                <label class="text-info">UserName:</label>
                <input type="text" class="form-control" id="txtUserName" />
                <span style="color:red;" id="spntxtUserName"></span>
            </div>
            <div class="form-group">
                <label class="text-info">Password:</label>
                <input type="password" class="form-control" id="txtPassword" />
                <span style="color:red;" id="spntxtPassword"></span>
            </div>
            <div class="form-group">
                <label class="text-info">Confirm Password:</label>
                <input type="password" class="form-control" id="txtConfirmPassword" />
                <span style="color:red;" id="spntxtConfirmPassword"></span>
            </div>
            <div class="form-group">
                <label class="text-info">Email:</label>
                <input type="email" class="form-control" id="txtEmail" />
                <span style="color:red;" id="spntxtEmail"></span>
            </div>
            <div class="form-group">
                <label class="text-info">Contact No:</label>
                <input type="text" maxlength="12" class="form-control" id="txtContactNo"  onkeypress="return blockSpecialChar(event);" />
                <span style="color:red;" id="spntxtContactNo"></span>
            </div>
            <div class="form-group">
                <label class="text-info">Gender:</label>
                <input type="radio" value="Male" id="rdnMale" name="gender" />Male
                <input type="radio" value="Female" id="rdnFemale" name="gender" />Female
                <span style="color:red;" id="spnrdlgender"></span>
            </div>
            <div class="form-group">
                <label class="text-info">Country:</label>
                <select id="ddlCountry" class="form-control">
                    <option value="" selected="selected">--select country--</option>
                    <option value="India">India</option>
                    <option value="Jermany">Jermany</option>
                    <option value="Japan">Japan</option>
                    <option value="China">China</option>
                    <option value="United States">United States</option>
                    <option value="Mexico">Mexico</option>
                    <option value="Russia">Russia</option>
                    <option value="United Kingdom">United Kingdom</option>
                    <option value="Canada">Canada</option>
                    <option value="South korea">South korea</option>
                    <option value="Israil">Israil</option>
                    <option value="Austrila">Austrila</option>
                    <option value="France">France</option>
                    <option value="Spain">Spain</option>
                </select>
                <span style="color:red;" id="spnddlCountry"></span>
            </div>
            <div class="form-group">
                <input type="checkbox" id="chkpolicy" />&nbsp;I Agree to policy
                <span style="color:red;" id="spnchkpolicy"></span>
            </div>
            <div class="form-group">
                <input type="button" id="btnSubmit" onclick="return validateform();" class="btn btn-success" value="Submit" />
            </div>
        </form>
    </div>
</div>
4.The form look like below..
5.To perform validation on above form i wrote below jquery script.This script is fired when we click on submit button present at the end of form.
function validateform() {
        var result = true;
        var emailReg = /^([\w-\.][email protected]@([\w-]+\.)+[\w-]{2,4})?$/i;
        var phoneReg= /([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})/;
        //Validating a normal textbox
        if ($("#txtFullName").val() == "") {
            $("#spntxtFullName").text("Full Name Required");
            result = false;
        } else {
            $("#spntxtFullName").text("");
        }
        if ($("#txtUserName").val() == "") {
            $("#spntxtUserName").text("UserName Required");
            result = false;
        } else {
            $("#spntxtUserName").text("");
        }
        if ($("#txtPassword").val() == "") {
            $("#spntxtPassword").text("Password Required");
            result = false;
        } else {
            $("#spntxtPassword").text("");
        }
        if ($("#txtPassword").val() != "") {
            if ($("#txtConfirmPassword").val() != $("#txtPassword").val()) {
                $("#spntxtConfirmPassword").text("Password not matched");
                result = false;
            } else {
                $("#spntxtConfirmPassword").text("");
            }
        }
        if ($("#txtEmail").val() == "") {
            $("#spntxtEmail").text("Email Required");
            result = false;
        }
        //validating email with regular expression
        else if (!emailReg.test($.trim($("#txtEmail").val()))) {
            $("#spntxtEmail").text("Valid Email Required");
            result = false;
        }else {
            $("#spntxtEmail").text("");
        }
        if ($("#txtContactNo").val() == "") {
            $("#spntxtContactNo").text("Contact Required");
            result = false;
        }
        //validating phone number with regular expression
        else if (!phoneReg.test($.trim($("#txtContactNo").val()))) {
            $("#spntxtContactNo").text("Valid Contact Required");
            result = false;
        } else {
            $("#spntxtContactNo").text("");
        }
        //validating radio button checked or not
        if (!$("input[name='gender']:checked").val()) {
            $("#spnrdlgender").text("Select Gender");
            result = false;
        } else {
            $("#spnrdlgender").text("");
        }
        //validating checkbox
        if ($("#chkpolicy").prop('checked')==false) {
            $("#spnchkpolicy").text("Select Policy");
            result = false;
        } else {
            $("#spnchkpolicy").text("");
        }
        //validating dropdownlist
        if ($("#ddlCountry").val() == "") {
            $("#spnddlCountry").text("Select country");
            result = false;
        } else {
            $("#spnddlCountry").text("");
        }
        return result;
    }
6.I used regular expressions to check whether contact number and email fields are in correct format.
7.finally below java script function restricts user without entering special characters in FullName and ContactNumber fields.
8.It fires on keypress and blocks special characters.below is code..
//blocks the special characters in textbox.
    function blockSpecialChar(e) {
        var k;
        document.all ? k = e.keyCode : k = e.which;
        return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
    }
9.If i click on submit button without giving any data in form fields we will get validations message like below..


10.Download source code for this application from here Download.

Conclusion:

I hope this tutorial will help you .To get more updates please subscribe to this blog subscribe. OR follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Monday, 21 August 2017

Sending Email with Attachments in ASP.NET Using C#

04:26:00 Posted by raviteja swayampu , No comments
In this post we gonna implement how to send email with attachments using C Sharp.Sending Email is a very common task in any web application for many purposes.In daily web development we need to add mail functionality to our projects to send mails to customers or other purposes.

Current article will explains you how to implement basic email sending application(for gmail) in ASP.NET project using C Sharp as a programming language.The implementation process and Base class libraries used in current application is same for ASP.NET MVC also.

The namespace used for sending mails here is System.Net.Mail.Follow the below few steps to implement email sending application on your own.
1.Create a ASP.NET empty web application by taking Web forms template.
2.Add a Web form to solution by right click on project-->Add-->select web form-->name it.
3.Here i named it as SendEmail.aspx.
SendEmail.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SendEmail.aspx.cs" Inherits="SendEmailUsingASP.NET.SendEmail" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Sending Email With Attachement</title>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <style type="text/css">
        input,textarea{
            max-width:300px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div class="container">
        <div class="row">
            <h3 class="text-info">Sending Email with Attachements</h3>
            <asp:Label ID="lblMessage" runat="server" style="color:green;"></asp:Label>  
            <div class="form-group">
                <label class="text-info">From:</label>
                <asp:TextBox ID="txtFrom" runat="server" class="form-control"></asp:TextBox>
            </div>      
            <div class="form-group">
                <label class="text-info">Password:</label>
                <asp:TextBox ID="txtPassword" type="password" runat="server" class="form-control"></asp:TextBox>
            </div> 
            <div class="form-group">
                <label class="text-info">To:</label>
                <asp:TextBox ID="txtTo" runat="server" class="form-control"></asp:TextBox>
            </div> 
            <div class="form-group">
                <label class="text-info">Subject:</label>
                <asp:TextBox ID="txtSubject" runat="server" class="form-control"></asp:TextBox>
            </div> 
            <div class="form-group">
                <label class="text-info">Body:</label>
                <asp:TextBox ID="txtBody" textMode="MultiLine" runat="server" class="form-control"></asp:TextBox>
            </div> 
            <div class="form-group">
                <label class="text-info">Attachment:</label>
                <asp:FileUpload ID="fileupload" runat="server" class="form-control"/>
            </div> 
            <div class="form-group">
                <asp:Button ID="btnSubmit" runat="server" Text="Send Mail" OnClick="SendMail" class="btn btn-default" />
            </div>
        </div>
    </div>
    </form>
</body>
</html>
4.Application looks like below in browser...


5.Now to shift to code behind of page SendEmail.aspx.
6.Replace CS file code with below code.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SendEmailUsingASP.NET
{
    public partial class SendEmail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        public void SendMail(object sender,EventArgs e)
        {
            try
            {
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(txtFrom.Text);
                mail.To.Add(txtTo.Text);
                mail.Subject = txtSubject.Text;
                mail.Body = txtBody.Text;
                mail.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.UseDefaultCredentials = false;
                NetworkCredential nc = new NetworkCredential(txtFrom.Text, txtPassword.Text.Trim());
                smtp.Credentials = nc;
                smtp.EnableSsl = true;
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;

                if (fileupload.PostedFile != null)
                {
                    HttpPostedFile attachment = fileupload.PostedFile;
                    int filelength = attachment.ContentLength;
                    if (filelength > 0)
                    {
                        string fileName = Path.GetFileName(fileupload.PostedFile.FileName);
                        mail.Attachments.Add(new Attachment(fileupload.PostedFile.InputStream, fileName));
                    }
                }
                smtp.Send(mail);
                lblMessage.Text = "Mail Sent Successfully";
            }
            catch(Exception ex)
            {
                lblMessage.Text = "Mail Sening Failed due exception: " + ex;
            }
        }
    }
}
7.After clicking on Send Mail button i got notification alert from my outlook.Yes i got test mail with attachment to my inbox like this.

8.Oh i forgot to share source code Download...

Conclusion:

I hope this tutorial will help you .To get more updates please subscribe to this blog subscribe. OR follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Sunday, 20 August 2017

Reordering list via drag and drop using AngularJs

00:15:00 Posted by raviteja swayampu , No comments
In this article i am going to implement Reordering List via drag and drop using Angular Js and ASP.NET MVC. In this application we can change the order of the list using drag and drop.The order of the list is preserved by saving in database.

In previous posts i implemented angular applications along with asp.net mvc. Visit below link to explore more angular applications in this site.
http://www.mitechdev.com/2017/01/learning-angular-js-in-aspnet-mvc.html.
In current angular application i have used a angular js directive "angular drag and drop".I download it from github. This directive allows us to implement sortable lists with HTML5 and drop API.

Reordering list via drag & drop using angularjs

Step 1:Create table&Insert data

1.For this application i used Visual studio 2015 express.
2.Create a asp.net mvc web application.
3.Database code for this application is as follows.
--- Table definition...
CREATE TABLE [dbo].[ReorderList] (
    [Listid]    INT           NOT NULL,
    [ListName]  NVARCHAR (50) NOT NULL,
    [ListOrder] INT           NOT NULL,
    PRIMARY KEY CLUSTERED ([Listid] ASC)
);
4.Insert some sample data into ReorderList table.
INSERT INTO [dbo].[ReorderList] ([Listid], [ListName], [ListOrder]) VALUES (1, N'Sample Task data 1', 1)
INSERT INTO [dbo].[ReorderList] ([Listid], [ListName], [ListOrder]) VALUES (2, N'Sample Task data 2', 2)
INSERT INTO [dbo].[ReorderList] ([Listid], [ListName], [ListOrder]) VALUES (3, N'Sample Task data 3', 3)
INSERT INTO [dbo].[ReorderList] ([Listid], [ListName], [ListOrder]) VALUES (4, N'Sample Task data 4', 4)
INSERT INTO [dbo].[ReorderList] ([Listid], [ListName], [ListOrder]) VALUES (5, N'Sample Task data 5', 5)

Step 2: Add Entity Data Model to project

1.Add Entity data model in models folder.
2.Go to Solution Explorer --> Models folder-- > Add --> New item --> Select ADO.net Entity Data Model under data --> Enter model name --> Add.
3.A popup window will come (Entity Data Model Wizard) --> Select Generate from database --> Next -->Chose your data connection --> select your database-- > next --> Select tables --> enter Model Namespace --> Finish.

Step 3:Add drag&drop directive files

1.This application uses 'angular drag and drop lists' directive for adding drag and drop features.
2.Download angular drag and drop lists open source project files from github.
3.Add 'angular-drag-and-drop-lists.min.js' file to solution.

Step 4:Create controller & implement methods

1.Create a Controller and name it as HomeController.
2.I created two methods Index() and SaveListOrder() in controller.
Index(): To render index.cshtml page.send data list data to index view using strongly typed binding.
SaveListOrder(): Saves the Reordered list to database.
HomeController.cs
public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            DatabaseEntities db = new DatabaseEntities();            
            return View(db.ReorderLists.ToList());
        }
        public JsonResult SaveListOrder(List newlist)
        {
            bool status = false;
            try
            {
                if (newlist != null)
                {
                    using (DatabaseEntities db=new DatabaseEntities())
                    {
                        foreach(var item in newlist)
                        {
                            db.ReorderLists.Attach(item);
                            db.Entry(item).State = EntityState.Modified;
                        }
                        db.SaveChanges();
                        status = true;
                    }
                }
            }
            catch(Exception ex)
            {
                status = false;
                throw ex;
            }
            return Json(status,JsonRequestBehavior.AllowGet);
        }
    }

Step 5:Prepare script&View to display list

1.Add View to Index action method.
2.Add below script to display list from database and saves the sorted list to db.
var app = angular.module('myapp', ['dndLists']);
    app.controller('myController', ['$http', function ($http) {
        var myController = this;
        //gets the list data from database.
        myController.Tasks [email protected](Json.Encode(Model))
        myController.IsProcessing = false;
        //Update order of list
        myController.Sorting = function (index) {
            debugger;
            myController.IsProcessing = true;
            myController.Tasks.splice(index, 1);
            var newData = [];
            angular.forEach(myController.Tasks, function (val, index) {
                val.Order = index + 1;
                newData.push(val);
            })
           //saves the sorted list to db
            $http.post('/home/SaveListOrder', newData).then(function (response) {
            }).finally(function () {
                myController.IsProcessing = false;
            })
        }
    }])
3.Index.cshtml:
@{
    ViewBag.Title = "Index";
}
@model IEnumerable<ReorderingListUsingAngular.ReorderList>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<script src="~/Scripts/angular-drag-and-drop-lists.min.js"></script>

<h3 style="text-align:center;">Reordering Lists in using Angularjs</h3><br />

<div ng-app="myapp">
    <div ng-controller="myController as c" class="simpleDemo list-type1">
        <div class="loader" ng-show="vm.IsProcessing">
            Please Wait...
        </div>
        <ol dnd-list="c.Tasks">
            <li ng-repeat="item in c.Tasks"
                dnd-list-id="{{item.Listid}}"
                dnd-draggable="item"
                dnd-moved="c.Sorting($index)"
                dnd-effect-allowed="move"
                dnd-selected="models.selected = item"
                ng-class="{'selected': models.selected === item}">
                {{item.ListName}}
            </li>
        </ol>
    </div>
</div>
4.Add styles to lists using below css code.
.list-type1 {
        width: 400px;
        margin: 0 auto;
    }

    .list-type1 ol {
         counter-reset: li;
         list-style: none;
         *list-style: decimal;
         font-size: 15px;
         font-family: 'Raleway', sans-serif;
         padding: 0;
         margin-bottom: 4em;
    }

    .list-type1 ol ol {
         margin: 0 0 0 2em;
    }

    .list-type1 ol li {
         position: relative;
         display: block;
         padding: .4em .4em .4em 2em;
         *padding: .4em;
         margin: .5em 0;
         background: #93C775;
         color: #000;
         text-decoration: none;
         -moz-border-radius: .3em;
         -webkit-border-radius: .3em;
         border-radius: 10em;
         transition: all .2s ease-in-out;
    }

   .list-type1 a:hover {
         background: #d6d4d4;
         text-decoration: none;
         transform: scale(1.1);
    }
   .list-type1 li:before {
         content: counter(li);
         counter-increment: li;
         position: absolute;
         left: -1.3em;
         top: 50%;
         margin-top: -1.3em;
         background: #93C775;
         height: 2em;
         width: 2em;
         line-height: 2em;
         border: .3em solid #fff;
         text-align: center;
         font-weight: bold;
         -moz-border-radius: 2em;
         -webkit-border-radius: 2em;
         border-radius: 2em;
         color: #FFF;
   }
5.Download the source code this application from here download(VS2015).

Conclusion:

I hope this tutorial will help you .To get more updates please subscribe to this blog subscribe. OR follow on Social networks for daily awesome updates[Facebook,twitter,google plus]