My Linux Stuff - Complete Blog For Linux Articles

My Linux Stuff - Complete Blog For Linux Articles

A Website For Complete Linux OS,Step by Step linux Installtion, Linux Tips and Tricks and Linux Stuff and so on... Connect and sharing here....

TOP 50 ENGINEERING COLLEGES IN INDIA 2014

TOP 50 ENGINEERING COLLEGES IN INDIA 2014

This below survey was taken many form many colleges in India. These Top 50 Engineering Colleges in India have Good Infrastructure, Good Environment, Educations , Staff, Placement , Research Activities and other Facilities are good.

Top 10 Government Engineering Colleges in India

Top 10 Government Engineering Colleges in India

These Government Engineering Colleges in India are really good for all kind of stuff like Education , research , Placement and New Innovation Ideas etc... But Getting seat in these colleges are heavy competition in students .....

Top 10 Colleges In India 2014

Top 10 Colleges In India 2014

Indian Institute Of Technology Delhi,Indian Institute Of Technology Bombay,Indian Institute Of Technology Kanpur,Indian Institute Of Technology Madras,Indian Institute Of Technology Kharagpur,Indian Institute Of Technology Roorkee,University Of Delhi,Indian Institute Of Technology Guwahati,University Of Calcutta,University Of Mumbai, National Institute Of Technology,Trichy.

2014 LATEST SURVEY TOP RANKING ENGINEERING COLLEGES IN INDIA

2014 LATEST SURVEY TOP RANKING ENGINEERING COLLEGES IN INDIA

This below survey was taken many form many colleges in India. These Top 100 Engineering Colleges in India have Good Infrastructure, Good Environment, Educations , Staff, Placement , Research Activities and other Facilities are good. If you want to do Engineering as your dream and try out these colleges

Subscribe Now!

Enter your email address:

Sunday, September 6, 2015

Login and Registration Page in ASP.Net MVC3

In this article I will show how to create a Login and Registration form in ASP.Net MVC. This is a quick simple example of how to implement it in ASP.NET MVC project.
Before implementing the steps given below create a table in your database as I have created for this project:



create table mvcUser
(
      FirstName varchar(50),
      LastName varchar(50),
      userID varchar(50) constraint mvcPrime primary key,
      PasswordConfirm varchar(30),
      StreetAddress1 varchar(100),
      StreetAddress2 varchar(100),
      City varchar(50),
      State varchar(50),
      ZIPCode varchar(20)
)
Please implement the following steps to create a Login and Registration Form:
·         Open Microsoft Visual Studio 2010 à Select New Project à Select Web from the Installed Templates àSelect ASP.NET MVC 3 Web Application à Enter the project name “UserFormDemo” in the Name textbox àClick OK.
Login and Registration Form in ASP.Net MVC
After select the project you can see the following (New ASP.NET MVC 3 Project) dialog box:
Select Empty from the Select a template option à Select ASPX view engine à Click OK.
Login and Registration Form in ASP.Net MVC
Add a new Controller in your project and enter the controller name as “HomeController” as shown in the below figure:
Login and Registration Form in ASP.Net MVC
After adding a controller add a Model in your project and enter the model class name as “Login.cs”.
Login and Registration Form in ASP.Net MVC
You also have to configure your web.config and Globax.asax file for the implementation of this project:
Add connectionStrings element under configuration tag and authentication element under system.web tag.
<connectionStrings>
<add name="cs"connectionString="Data source=server_name; Initial Catalog=database_name;  User Id=user_id; Password=user_passwordproviderName="System.Data.SqlClient" />
</connectionStrings>

<authentication mode="Forms">
     <forms loginUrl="~/Home/LogOn"defaultUrl="~/Home/Home"timeout="2880" />
</authentication>

Change the RegisterRoutes definition in Global.asax file as show below:
public static void RegisterRoutes(RouteCollection routes)
{
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default"// Route name
                "{controller}/{action}/{id}"// URL with parameters
                new { controller = "Home", action = "LogOn", id = UrlParameter.Optional }
            );
}

In the Model class add the properties, methods and class as I did in the below Model (Login) class:
using System;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Web.Mvc;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;

namespace UserFormDemo.Models
{
    public class Login
    {
        [Required(ErrorMessage = "Email Id Required")]
        [DisplayName("Email ID")]
        [RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"
                                    ErrorMessage = "Email Format is wrong")]
        [StringLength(50, ErrorMessage = "Less than 50 characters")]
        public string EmailId
        {
            getset;
        }

        [DataType(DataType.Password)]
        [Required(ErrorMessage="Password Required")]
        [DisplayName("Password")]
        [StringLength(30, ErrorMessage = ":Less than 30 characters")]
        public string Password
        {
            get;  set;
        }

        public bool IsUserExist(string emailid, string password)
        {
            bool flag = false;
            SqlConnection connection = new SqlConnection
    System.Configuration.ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
            connection.Open();
            SqlCommand command = new SqlCommand("select count(*) from mvcUser where 
           userID='"
 + emailid + "' and PasswordConfirm='" + password + "'", connection);
            flag = Convert.ToBoolean(command.ExecuteScalar());
            connection.Close();
            return flag;
        }
    }
    public class Register
    {
        [Required(ErrorMessage="FirstName Required:")]
        [DisplayName("First Name:")]
        [RegularExpression(@"^[a-zA-Z'.\s]{1,40}$",ErrorMessage="Special Characters not 
                                                                             allowed"
)]
        [StringLength(50, ErrorMessage = "Less than 50 characters")]
        public string FirstName { getset; }

        [Required(ErrorMessage="LastName Required:")]
        [RegularExpression(@"^[a-zA-Z'.\s]{1,40}$", ErrorMessage = "Special Characters  
                                                                        not allowed"
)]
        [DisplayName("Last Name:")]
        [StringLength(50, ErrorMessage = "Less than 50 characters")]
        public string LastName { getset; }

        [Required(ErrorMessage="EmailId Required:")]
        [DisplayName("Email Id:")]
        [RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"
                                                ErrorMessage = "Email Format is wrong")]
        [StringLength(50, ErrorMessage = "Less than 50 characters")]
        public string EmailId { getset; }

        [Required(ErrorMessage="Password Required:")]
        [DataType(DataType.Password)]
        [DisplayName("Password:")]
        [StringLength(30, ErrorMessage = "Less than 30 characters")]
        public string Password { getset; }

        [Required(ErrorMessage="Confirm Password Required:")]
        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "Confirm not matched.")]
        [Display(Name = "Confirm password:")]
        [StringLength(30, ErrorMessage = "Less than 30 characters")]
        public string ConfirmPassword { getset; }

        [Required(ErrorMessage="Street Address Required")]
        [DisplayName("Street Address1:")]
        [StringLength(100, ErrorMessage = "Less than 100 characters")]
        public string StreetAdd1 { getset; }

        [DisplayName("Street Address2:")]
        [StringLength(100, ErrorMessage = "Less than 100 characters")]
        public string StreetAdd2 { getset; }

        [Required(ErrorMessage="City Required")]
        [DisplayName("City:")]
        [RegularExpression(@"^[a-zA-Z'.\s]{1,40}$", ErrorMessage = "Special Characters 
                                                                         not allowed"
)]
        [StringLength(50, ErrorMessage = "Less than 50 characters")]
        public string City { getset; }

        [Required(ErrorMessage="State Required")]
        [DisplayName("State:")]
        [RegularExpression(@"^[a-zA-Z'.\s]{1,40}$", ErrorMessage = "Special Characters 
                                                                         not allowed"
)]
        [StringLength(50, ErrorMessage = "Less than 50 characters")]
        public string State { getset; }

        [Required(ErrorMessage="ZipCode Required")]
        [DisplayName("Zip Code:")]
        [StringLength(20, ErrorMessage = "Less than 20 characters")]
        public string Zip { getset; }

        [Required(ErrorMessage = "Enter Verification Code")]
        [DisplayName("Verification Code:")]
        public string Captcha { getset; }

        public bool IsUserExist(string emailid)
        {
            bool flag = false;
            SqlConnection connection = new  SqlConnection
    (System.Configuration.ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
            connection.Open();
            SqlCommand command = new SqlCommand("select count(*) from mvcUser where 
            userID='"
 + emailid + "'", connection);
            flag = Convert.ToBoolean(command.ExecuteScalar());
            connection.Close();
            return flag;
        }

        public bool Insert()
        {
            bool flag = false;
            if (!IsUserExist(EmailId))
            {
                SqlConnection connection = new SqlConnection
    (System.Configuration.ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
                connection.Open();
                SqlCommand command = new SqlCommand("insert into mvcUser values('" + 
                FirstName + "','" + LastName + "','" + EmailId + "','" + Password + "', 
                '"
 + StreetAdd1 + "','" + StreetAdd2 + "','" + City + "','" + State +"', 
                '"
 + Zip + "')", connection);
                flag = Convert.ToBoolean(command.ExecuteNonQuery());
                connection.Close();
                return flag;
            }
            return flag;
        }
    }
    public class CaptchImageAction : ActionResult
    {
        public Color BackgroundColor { getset; }
        public Color RandomTextColor { getset; }
        public string RandomText { getset; }
        public override void ExecuteResult(ControllerContext context)
        {
            RenderCaptchaImage(context);
        }
        private void RenderCaptchaImage(ControllerContext context)
        {
            Bitmap objBmp = new Bitmap(150, 60);
            Graphics objGraphic=Graphics.FromImage(objBmp);
            objGraphic.Clear(BackgroundColor);
            SolidBrush objBrush = new SolidBrush(RandomTextColor);
            Font objFont = null;
            int a;
            string myFont, str;
            string[] crypticsFont = new string[11];
            crypticsFont[0] = "Times New roman";
            crypticsFont[1] = "Verdana";
            crypticsFont[2] = "Sylfaen";
            crypticsFont[3] = "Microsoft Sans Serif";
            crypticsFont[4] = "Algerian";
            crypticsFont[5] = "Agency FB";
            crypticsFont[6] = "Andalus";
            crypticsFont[7] = "Cambria";
            crypticsFont[8] = "Calibri";
            crypticsFont[9] = "Courier";
            crypticsFont[10] = "Tahoma";
            for (a = 0; a < RandomText.Length; a++)
            {
                myFont = crypticsFont[a];
                objFont=new Font(myFont,18,FontStyle.Bold | FontStyle.Italic | 
                                                                  FontStyle.Strikeout);
                str=RandomText.Substring(a,1);
                objGraphic.DrawString(str,objFont,objBrush,a*20,20);
                objGraphic.Flush();
            }
            context.HttpContext.Response.ContentType="image/GF";
            objBmp.Save(context.HttpContext.Response.OutputStream,ImageFormat.Gif);
            objFont.Dispose();
            objGraphic.Dispose();
            objBmp.Dispose();
        }
    }
}

Add the following Views and methods in the Controller class:
using System;
using System.Web.Mvc;
using System.Web.Security;
using System.Drawing;
using System.Text;
using UserFormDemo.Models;

namespace MvcApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult LogOn()
        {
            return View();
        }
        public ViewResult Register()
        {
            return View();
        }

        public ActionResult Home()
        {
            return View();
        }

        [HttpPostValidateInput(false)]
        public ActionResult LogOn(Login model)
        {
            if (ModelState.IsValid)
            {
                if (model.IsUserExist(model.EmailId, model.Password))
                {
                    ViewBag.UserName = model.EmailId;
                    FormsAuthentication.RedirectFromLoginPage(model.EmailId, false);
                }
                else
                {
                    ModelState.AddModelError("""EmailId or Password Incorrect.");
                }
            }
            return View(model);
        }

        [HttpPostValidateInput(false)]
        public ActionResult Register(Register model)
        {

            if (ModelState.IsValid)
            {
                string realCaptcha = Session["captcha"].ToString();
                if (model.Captcha == realCaptcha)
                {
                    if (model.Insert())
                    {
                        return RedirectToAction("LogOn""Home");
                    }
                    else
                    {
                        ModelState.AddModelError("""Email Id Already Exist");
                    }
                }
                else
                    ModelState.AddModelError("""Verification Code is Incorrect");
            }
            return View(model);
        }
        public CaptchImageAction Image()
        {
            string randomText = SelectRandomWord(6);
            Session["captcha"] = randomText;
            HttpContext.Session["RandomText"] = randomText;
            return new CaptchImageAction() { BackgroundColor = Color.LightGray, 
                       RandomTextColor = Color.Black, RandomText = randomText };
        }
        private string SelectRandomWord(int numberOfChars)
        {
            if (numberOfChars > 36)
            {
                throw new InvalidOperationException("Random Word Characters cannot be 
                greater than 36"
);
            }
            char[] columns = new char[36];
            for (int charPos = 65; charPos < 65 + 26; charPos++)
                columns[charPos - 65] = (char)charPos;
            for (int intPos = 48; intPos <= 57; intPos++)
                columns[26 + (intPos - 48)] = (char)intPos;
            StringBuilder randomBuilder = new StringBuilder();
            Random randomSeed = new Random();
            for (int incr = 0; incr < numberOfChars; incr++)
            {
                randomBuilder.Append(columns[randomSeed.Next(36)].ToString());
            }
            return randomBuilder.ToString();
        }
    }
}

After establishing the code you have to add the Master Page and Views in your project to present the user interface:
·         Adding a Master Page:
Right click on Shared Folder à Add New Item à Select MVC 3 view Master Page (ASPX) à Enter the Site.Master in the Name textbox à Click Add.
Login and Registration Form in ASP.Net MVC
Add the following content in the Master Page (Site.Master):
<html>
<head id="Head1" runat="server">
    <script type="text/javascript">
        function Cancel() {
            location.href = "Logon";
        }
    </script>
    <style type="text/css">
          h1
          {
              color:Blue;
              margin:10px 0px 0px 40%;
              font-family:Calibri;
          }
          a
          {
              color:Black;
              text-decoration:none;
              font-size:large;
              font-family:Calibri;
          }
          table
          {
              margin-top:0px;
          }
    </style>

    <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
    </head>
    <body style="background-color:Aqua">
    <script src="<%: Url.Content("~/Scripts/jquery-1.4.4.min.js") %>"   
                                                        type="text/javascript"></script>
    <script src="<%= Url.Content("~/Scripts/JavaScript/jquery-ui-1.8.7.min.js")%>" 
                                                        type="text/javascript"></script> 
    <script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>" 
                                                        type="text/javascript"></script> 
    <script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" 
                                                         type="text/javascript"></script>
    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
   <div>
    <h1>Welcome to My Site</h1>
    <hr />
        <table align="right">
            <tr>
                <td>
                     <%: Html.ActionLink("[Register]","Register"%>
                     <%: Html.ActionLink("[Log On]","LogOn"%>
                </td>
            </tr>
        </table>
       
         <asp:ContentPlaceHolder ID="MainContent" runat="server" />
    </div>
</body>
</html>


Add a view:

·         Enter View name as LogOn.
·         Select Login class as a strongly typed view.
·         Select Site.master as your master page.
Login and Registration Form in ASP.Net MVC
Add the following content in your LogOn View source page:
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    LogOn
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <style type="text/css">
        .btnStyle
        {
            borderthin solid #000000;
            line-heightnormal;
            width80px;
        }
    </style>
    <%using (Html.BeginForm("LogOn""Home"FormMethod.Post))
      %>
    <div class="fontStyle">
        <center>
            <table style="margin-top: 100px;margin-left:150px">
                <tr>
                    <td colspan="2">
                        <div>
                            <asp:Image ID="Image1" runat="server" 
                                 ImageUrl="~/Content/Multi_purpose.png" Width="250px" />
                            <hr />
                        </div>
                    </td>
                </tr>
                <tr style="height:30px">
                    <td align="right">
                        <%: Html.LabelFor(m => m.EmailId) %>
                    </td>
                    <td style="width:200px" align="right">
                        <%: Html.TextBoxFor(m => m.EmailId)%>
                    </td>
                    <td style="width:250px;color:Red" align="left">
                        <%: Html.ValidationMessageFor(m => m.EmailId)%>
                    </td>
                </tr>
                <tr style="height:30px">
                    <td align="right">
                        <%:Html.LabelFor(m => m.Password) %>
                    </td>
                    <td align="right">
                        <%: Html.PasswordFor(m => m.Password)%>
                    </td>
                    <td style="width:250px;color:Red" align="left">
                        <%: Html.ValidationMessageFor(m => m.Password) %>
                    </td>
                </tr>
                <tr style="height:30px">
                    <td colspan="2" align="center">
                        <input type="submit" value="Sign In" class="btnStyle" />
                    </td>
                </tr>
                <tr>
                    <td colspan="3" style="color:Red;" align="left">
                        <%: Html.ValidationSummary(true)%>
                    </td>
                </tr>
            </table>
        </center>
    </div>
    <%%>
</asp:Content>

Add a view:

·         Enter View name as Register.
·         Select Register class as a strongly typed view.
·         Select Site.master as your master page.

Login and Registration Page in ASP.Net MVC3
Add the following content in your Register View source page:
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Register
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <style type="text/css">
        .btnStyle
        {
            borderthin solid #000000;
            line-heightnormal;
            width80px;
        }
    </style>

    <%using (Html.BeginForm("Register""Home"FormMethod.Post))
      %>
    <div>
        <table style="margin-left: 350px" align="center">
            <tr>
                <td>
                    <table style="font-family: Calibri">
                        <tr style="height: 80px">
                            <td colspan="2" align="center">
                                <asp:Label ID="lblBanner" runat="server" Text="Register 
                             New Account"
 Font-Names="Consolas" Font-Size="Larger" Font-
                             Underline
="True"></asp:Label>
                            </td>
                        </tr>
                        <tr>
                            <td style="width: 200px">
                                <%: Html.LabelFor(m => m.FirstName) %>
                            </td>
                            <td style="width: 150px">
                                <%: Html.TextBoxFor(m => m.FirstName) %>
                            </td>
                            <td style="width: 200px; color: Red" align="left">
                                <%: Html.ValidationMessageFor(m => m.FirstName) %>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <%: Html.LabelFor(m => m.LastName) %>
                            </td>
                            <td>
                                <%: Html.TextBoxFor(m => m.LastName) %>
                            </td>
                            <td style="color: Red">
                                <%: Html.ValidationMessageFor(m => m.LastName) %>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <%: Html.LabelFor(m => m.EmailId) %>
                            </td>
                            <td>
                                <%: Html.TextBoxFor(m => m.EmailId) %>
                            </td>
                            <td style="color: Red">
                                <%: Html.ValidationMessageFor(m => m.EmailId) %>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <%: Html.LabelFor(m => m.Password) %>
                            </td>
                            <td>
                                <%: Html.PasswordFor(m => m.Password) %>
                            </td>
                            <td style="color: Red">
                                <%: Html.ValidationMessageFor(m => m.Password) %>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <%: Html.LabelFor(m => m.ConfirmPassword) %>
                            </td>
                            <td>
                                <%: Html.PasswordFor(m => m.ConfirmPassword) %>
                            </td>
                            <td style="color: Red">
                                <%: Html.ValidationMessageFor(m => m.ConfirmPassword) %>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <%: Html.LabelFor(m => m.StreetAdd1) %>
                            </td>
                            <td>
                                <%: Html.TextBoxFor(m => m.StreetAdd1) %>
                            </td>
                            <td style="color: Red">
                                <%: Html.ValidationMessageFor(m => m.StreetAdd1) %>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <%: Html.LabelFor(m => m.StreetAdd2) %>
                            </td>
                            <td>
                                <%: Html.TextBoxFor(m => m.StreetAdd2) %>
                            </td>
                            <td style="color: Red">
                                <%: Html.ValidationMessageFor(m => m.StreetAdd2) %>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <%: Html.LabelFor(m => m.City) %>
                            </td>
                            <td>
                                <%: Html.TextBoxFor(m => m.City) %>
                            </td>
                            <td style="color: Red">
                                <%: Html.ValidationMessageFor(m => m.City) %>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <%: Html.LabelFor(m => m.State) %>
                            </td>
                            <td>
                                <%: Html.TextBoxFor(m => m.State) %>
                            </td>
                            <td style="color: Red">
                                <%: Html.ValidationMessageFor(m => m.State) %>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <%: Html.LabelFor(m => m.Zip) %>
                            </td>
                            <td>
                                <%: Html.TextBoxFor(m => m.Zip) %>
                            </td>
                            <td style="color: Red">
                                <%: Html.ValidationMessageFor(m => m.Zip) %>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2" align="center">
                                <input type="image" id="image" src="<%: 
                                Url.Action("Image","Home") %>" alt="Click to Refresh" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <%: Html.LabelFor(m => m.Captcha) %>
                            </td>
                            <td>
                                <%: Html.TextBoxFor(m => m.Captcha) %>
                            </td>
                            <td style="color: Red">
                                <%: Html.ValidationMessageFor(m => m.Captcha) %>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2" align="center">
                                <input type="submit" value="Register" class="btnStyle" />
                                <input type="button" value="Cancel" onclick="return 
                                 Cancel()"
 class="btnStyle" />
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2" style="color: Red" align="right">
                                <%: Html.ValidationSummary(true%>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </div>
    <%%>
</asp:Content>

Add a view:

·         Enter View name as Home.
·         Select Login class as a strongly typed view.
Login and Registration Form in ASP.Net MVC3
Add the following content in your Home View source page:
<html>
<head runat="server">
    <title>Home</title>
</head>
<body>
    <div>
        <h2>Welcome User!</h2>
    </div>
</body>
</html>

Now both coding and design part is over. Now when you debug or run your project you will have the following screen from which user can login if he had registered in the database.
Login and Registration Form in ASP.Net MVC
When you click on the Register link, a registration page will open from where user can registered:
Login and Registration Form in ASP.Net MVC
After creating or registering account when user login he will get the following page with welcome message:


Login and Registration Form in ASP.Net MVC



Source From : www.mindstick.com/Articles

Related Posts Plugin for WordPress, Blogger...