I have deigned a MVC-6 Application with two forms ,one is Registration form and after Registration I have another form to Login with the same UserName and Password which was entered during registration.What ever I have mention for error message display while register with same data,so the error message is not displaying.....
I am expecting if User is already exist in my database the error message should be display as "user is already exist..."
Please help me out with regarding solution...
Thanks in Advance,
What I have tried:
---Here Is My LogInController----
public class LoginController : Controller
{
public ActionResult Login()
{
return View();
}
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult LogIn(string userName, string password)
{
try
{
using (var context = new CmsDbContext())
{
var getUser = (from s in context.ObjRegisterUser where s.UserName == userName || s.EmailId == userName select s).FirstOrDefault();
if (getUser != null)
{
var hashCode = getUser.VCode;
var encodingPasswordString = Helper.EncodePassword(password, hashCode);
var query = (from s in context.ObjRegisterUser where (s.UserName == userName || s.EmailId == userName) && s.Password.Equals(encodingPasswordString) select s).FirstOrDefault();
if (query != null)
{
return RedirectToAction("Index", "Admin");
}
ViewBag.ErrorMessage = "Invallid User Name or Password";
return View();
}
ViewBag.ErrorMessage = "Invallid User Name or Password";
return View();
}
}
catch (Exception)
{
ViewBag.ErrorMessage = " Error!!! contact abc@info.in";
return View();
}
-----here is my Login view---
@{
ViewBag.Title = "LogIn";
}
<h2>LogIn</h2>
<div class="form-horizontal">
@using (Html.BeginForm("LogIn", "Login", null, FormMethod.Post))
{ @Html.AntiForgeryToken()
<div class="form-group">
<div class="col-md-12">
<input type="text" class="form-control" required="" placeholder="E-mail" name="UserName" />
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="password" class="form-control" required="" placeholder="Password" name="Password" />
</div>
</div>
<div class="form-group">
<div class="col-md-2">
<button class="btn btn-info btn-block">Log In</button>
</div>
</div>
<div class="form-group">
<div class="col-md-2"> <a href="#" class="btn btn-link btn-block">Forgot your password?</a> </div>
</div>
<div class="login-subtitle"> Don't have an account yet?</div>
<div>
@Html.ActionLink("Create an account", "Registration", "Admin") </div> }
</div>
-------here is my user model class---
public class User
{
[Key]
public int RegistrationId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string EmailId { get; set; }
public string Password { get; set; }
public string Gender { get; set; }
public string VCode { get; set; }
public DateTime CreateDate { get; set; }
public DateTime ModifyDate { get; set; }
public bool Status { get; set; }
--here is my Registration Controller---
public ActionResult Index()
{
return View();
}
public ActionResult Registration()
{
return View();
}
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Registration(User objNewUser)
{
try
{
using (var context = new CmsDbContext())
{
var chkUser = (from s in context.ObjRegisterUser where s.UserName == objNewUser.UserName || s.EmailId == objNewUser.EmailId select s).FirstOrDefault();
if (chkUser == null)
{
var keyNew = Helper.GeneratePassword(10);
var password = Helper.EncodePassword(objNewUser.Password, keyNew);
objNewUser.Password = password;
objNewUser.CreateDate = DateTime.Now;
objNewUser.ModifyDate = DateTime.Now;
objNewUser.VCode = keyNew;
context.ObjRegisterUser.Add(objNewUser);
context.SaveChanges();
ModelState.Clear();
return RedirectToAction("LogIn", "Login");
}
ViewBag.ErrorMessage = "User Allredy Exixts!!!!!!!!!!";
return View();
}
}
catch (Exception e)
{
ViewBag.ErrorMessage = "Some exception occured" + e;
return View();
}
}
--here is my registration view---
<h2>Registration</h2>
<div class="panel panel-default mb0">
<div class="panel-heading ui-draggable-handle">
<h3 class="panel-title">New User Registration</h3>
</div> @using (Html.BeginForm("Registration", "Admin", null, FormMethod.Post))
{ @Html.AntiForgeryToken()
<div class="panel-body">
<div class="form-group pt20">
<label class="col-md-3 col-xs-12 control-label align-right pt7">First Name</label>
<div class="col-md-6 col-xs-12">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-pencil"></span></span>
<input type="text" class="form-control form-group" required="" name="FirstName"> @*Getting value by name and the name should be the name given in database column*@
</div> <span class="help-block">First Name field sample</span>
</div>
<div class="clearfix"></div>
</div>
<div class="form-group">
<label class="col-md-3 col-xs-12 control-label align-right pt7">Last Name</label>
<div class="col-md-6 col-xs-12">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-pencil"></span></span>
<input type="text" class="form-control form-group" required="" name="LastName"> @*Getting value by name and the name should be the name given in database column*@
</div> <span class="help-block">Last Name field sample</span>
</div>
<div class="clearfix"></div>
</div>
<div class="form-group">
<label class="col-md-3 col-xs-12 control-label align-right pt7">User Name</label>
<div class="col-md-6 col-xs-12">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-pencil"></span></span>
<input type="text" class="form-control form-group" required="" name="UserName"> @*Getting value by name and the name should be the name given in database column*@
</div> <span class="help-block">User Name field sample</span>
</div>
<div class="clearfix"></div>
</div>
<div class="form-group">
<label class="col-md-3 col-xs-12 control-label align-right pt7">Email Id</label>
<div class="col-md-6 col-xs-12">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-pencil"></span></span>
<input type="text" class="form-control form-group" required="" name="EmailId"> @*Getting value by name and the name should be the name given in database column*@
</div> <span class="help-block">Email-Id field sample</span>
</div>
<div class="clearfix"></div>
</div>
<div class="form-group">
<label class="col-md-3 col-xs-12 control-label align-right pt7">Password</label>
<div class="col-md-6 col-xs-12">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-unlock-alt"></span></span>
<input type="password" class="form-control" required="" name="Password">
</div> <span class="help-block">Password field sample</span>
</div>
<div class="clearfix"></div>
</div>
<div class="form-group">
<label class="col-md-3 col-xs-12 control-label align-right pt7">Gender</label>
<div class="col-md-6 col-xs-12">
<label class="radio-inline">
<input type="radio" checked="checked" value="Male" name="Gender">Male
</label>
<label class="radio-inline">
<input type="radio" value="Female" name="Gender">Female
</label>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="panel-footer">
<input type="reset" value="Clear Form" name="btnReset" class="btn btn-default" />
<input type="submit" id="btnSubmit" name="btnSubmit" value="Submit" class="btn btn-primary pull-right" />
</div> }
</div>
---here is my another helper class for password hash---
public static class Helper
{
public static string ToAbsoluteUrl(this string relativeUrl)
{
if (string.IsNullOrEmpty(relativeUrl)) return relativeUrl;
if (HttpContext.Current == null) return relativeUrl;
if (relativeUrl.StartsWith("/")) relativeUrl = relativeUrl.Insert(0, "~");
if (!relativeUrl.StartsWith("~/")) relativeUrl = relativeUrl.Insert(0, "~/");
var url = HttpContext.Current.Request.Url;
var port = url.Port != 80 ? (":" + url.Port) : String.Empty;
return String.Format("{0}://{1}{2}{3}", url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
}
public static string GeneratePassword(int length)
{
const string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
var randNum = new Random();
var chars = new char[length];
var allowedCharCount = allowedChars.Length;
for (var i = 0; i <= length - 1; i++)
{
chars[i] = allowedChars[Convert.ToInt32((allowedChars.Length) * randNum.NextDouble())];
}
return new string(chars);
}
public static string EncodePassword(string pass, string salt)
{
byte[] bytes = Encoding.Unicode.GetBytes(pass);
byte[] src = Encoding.Unicode.GetBytes(salt);
byte[] dst = new byte[src.Length + bytes.Length];
System.Buffer.BlockCopy(src, 0, dst, 0, src.Length);
System.Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
byte[] inArray = algorithm.ComputeHash(dst);
return EncodePasswordMd5(Convert.ToBase64String(inArray));
}
public static string EncodePasswordMd5(string pass)
{
Byte[] originalBytes;
Byte[] encodedBytes;
MD5 md5;
md5 = new MD5CryptoServiceProvider();
originalBytes = Encoding.Default.GetBytes(pass);
encodedBytes = md5.ComputeHash(originalBytes);
return BitConverter.ToString(encodedBytes);
}
public static string base64Encode(string sData)
{
try
{
byte[] encData_byte = new byte[sData.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch (Exception ex)
{
throw new Exception("Error in base64Encode" + ex.Message);
}
}
public static string base64Decode(string sData)
{
try
{
var encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();
byte[] todecodeByte = Convert.FromBase64String(sData);
int charCount = utf8Decode.GetCharCount(todecodeByte, 0, todecodeByte.Length);
char[] decodedChar = new char[charCount];
utf8Decode.GetChars(todecodeByte, 0, todecodeByte.Length, decodedChar, 0);
string result = new String(decodedChar);
return result;
}
catch (Exception ex)
{
throw new Exception("Error in base64Decode" + ex.Message);
}
}