Part 2: MVC
Creating Login Page
This Tutorial we are going to learn about how to create simple form and check data with database by using Entity Framework
We also check some validation.
In tutorial MVC we are taking live project STORE Management System( Inventory Management Application). For this we will create all required DB and Form Part by Part.
If you did not subscribed my channel yet then please subscribed it for new MVC training video and other interesting videos..
Let’s Start...
Step 1:
First create a database structure and give the name BookStore
create database BookStore
go
USE [BookStore]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UsersLogin]
(
[Id] INT NOT NULL IDENTITY ,
[Username] NVARCHAR(50) NOT NULL,
[Password] NVARCHAR(MAX) NOT NULL,
[Attemped] INT NOT NULL DEFAULT 0,
[LastLogin] DATETIME NULL,
[RegDate] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
[Email] NVARCHAR(50) NOT NULL,
PRIMARY KEY ([Id])
)
GO
CREATE INDEX [BookStore_UsersLogin_Username] ON [dbo].[UsersLogin] ([Username])
GO
INSERT INTO [dbo].[UsersLogin]
([Username], [Password], [Email] ,[Attemped])
VALUES
('test', 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3', 'test@test.test',0)
GO
/* Store Procedure ....*/
alter PROCEDURE [dbo].[GetLoginInfo]
@UserName VARCHAR(50),
@Password varchar(Max)
AS
SET NOCOUNT ON
Declare @Fcount AS INT
SET @Fcount = (SELECT Attemped from UsersLogin WHERE UserName = @UserName)
IF EXISTS(SELECT * FROM UsersLogin WHERE UserName = @UserName)
BEGIN
Update UsersLogin set Attemped =0 WHERE UserName = @UserName
IF EXISTS(SELECT * FROM UsersLogin WHERE UserName = @UserName AND Password = @Password )
SELECT 'Success' AS UserExists
ELSE
Update UsersLogin set Attemped = @Fcount+1 WHERE UserName = @UserName
Update UsersLogin set LastLogin=GETDATE() WHERE UserName = @UserName
BEGIN
IF @Fcount >=3
SELECT 'Maximum Attempt Reached (3 times) .Your Account is locked now.' AS UserExists
ELSE
select CONVERT(varchar(10), (SELECT Attemped from UsersLogin WHERE UserName = @UserName)) AS UserFailedcount
END
END
ELSE
BEGIN
SELECT 'Credential Does not Exists' AS UserExists
END
Step 2: Now we are going to create Entity Frame Work, to create Entity framework (To Communicate with Database we use Entity Framework to achieve the task)
Right click on model folder àAdd new Itemà in data select Ado.net Entity Model and name it BookstoreEntity
Step 3: Now Follow Entity DataModel Wizard and Create Connection String
Step 5: Select a Table / Procedure/ View which u want in your EntitydataModel ..
Step 6:Now on Models folder add Class and Name it UserLogin.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace BookStoreMVCDemo.Models
{
public class UserLogin
{
[Required(ErrorMessage = "UserName is required")]
public string Username { get; set; }
[Required(ErrorMessage = "Password is required")]
[DataType(DataType.Password)]
public string Password { get; set; }
}
}
In this place basically we are setting validation and type of data which can be entered in DB
Some example
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}")]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}")]
For Email Regular Expression can be set
[RegularExpression(@"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", ErrorMessage = "Email is not valid")]
[RegularExpression(@"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", ErrorMessage = "Email is not valid")]
Step 7: Create Controller:Right click on controller folder and select add controller. Controller Scaffold window will open. Here we choose an Empty Controller and Name It LoginController
Now add some Code here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace BookStoreMVCDemo.Controllers
{
public class LoginController : Controller
{
// GET: Login
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(UsersLogin usersLogin )
{
BookStoreEntities bookStoreEntities = new BookStoreEntities();
var Pass = EnCodingDeCoding.SHA1.Encode(usersLogin.Password); // encoding
var Result = bookStoreEntities.GetLoginInfo(usersLogin.Username, Pass );
var item = Result.FirstOrDefault();
if (item == "Success")
{
return View("SucessLogin");
}
else if (item == "User Does not Exists")
{
ViewBag.NotValidUser = item;
}
else
{
ViewBag.Attempt = item;
}
return View("Index");
}
public ActionResult SucessLogin()
{
// return to home controller
return View();
}
}
}
Step 10: Now Right Click on Method of Controller and add view to your application
Index.cshtml view
@model BookStoreMVCDemo.Models.UserLogin
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
.sajha-demo {
height: 220px;
}
.centerposition {
padding-left: 400px;
font-weight: bold;
width: 1000px;
}
.error {
padding-left: 400px;
font-weight: bold;
width: 1000px;
color: red;
}
.loginbtn {
padding-left: 500px;
}
</style>
</head>
<body>
@using (Html.BeginForm())
{
<div class="sajha-demo" style="border:2px solid gray;">
<div class="form-group centerposition ">
<h1> Login </h1>
</div>
<div class="form-group centerposition ">
<label>User Name: </label>
@Html.EditorFor(model => model.Username)
@Html.ValidationMessageFor(model => model.Username)
</div>
<div class="form-group centerposition ">
<label>Password:</label>
@Html.EditorFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</div>
<div class="form-group error">
@if (@ViewBag.Attempt != null)
{
<label> Attempt count is: @ViewBag.Attempt</label>
}
@if (@ViewBag.NotValidUser != null)
{
<label> @ViewBag.NotValidUser</label>
}
</div>
<div class="loginbtn">
<input type="submit" value="Login" class="btn btn-primary" />
</div>
</div>
}
</body>
</html>
}
_Layout.cshtml code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div style="width: auto; background-color: #728ea7;">
@if (Request.IsAuthenticated)
{
<strong>@Html.Encode(User.Identity.Name)</strong>
@Html.ActionLink("Sign Out", "Logout", "User")
}
else
{
@Html.ActionLink("Register", "Register", "User")
<span> | </span>
@Html.ActionLink("Sign In", "Login", "User")
}
</div>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
No comments:
Post a Comment