I trying to Implement Role based security, Page access and Show/Hide Menu items based on Role in ASP.Net
in this code when entered correct username and password then all code run perfectly but when entered wrong username and password then generating error "System.IndexOutOfRangeException: AdminId"
Code File:
protected void AdminLogOn_Click(object sender, EventArgs e)
{
if (inputName.Text == "" && inputName.Text == string.Empty)
{
lblMessage.Text = "Please Enter User Name!";
}
else if (inputPassword.Text == "" && inputPassword.Text == string.Empty)
{
lblMessage.Text = "Please Enter Password!";
}
else
{
int userId = 0;
string roles = string.Empty;
objBussinessObj.UserName = inputName.Text;
objBussinessObj.Password = inputPassword.Text;
SqlDataReader reader = objBussinessLogic.ValidateAdminLogin(objBussinessObj);
reader.Read();
userId = Convert.ToInt32(reader["AdminId"]);
roles = reader["Roles"].ToString();
switch (userId)
{
case -1:
lblMessage.Text = "Username and/or password is incorrect.";
break;
default:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, inputName.Text, DateTime.Now, DateTime.Now.AddMinutes(2880), RememberMe.Checked = false, roles, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(inputName.Text, RememberMe.Checked = false));
break;
}
}
}
//class file code:
public SqlDataReader ValidateAdminLogin(BussinessObj objBussiness)
{
SqlParameter[] param = new SqlParameter[3];
param[0] = new SqlParameter("@Mode", "ChkAdminLogin");
param[1] = new SqlParameter("@UserName", objBussiness.UserName);
param[2] = new SqlParameter("@Password", objBussiness.Password);
return objDataAccess.ExecuteReader(_spName, param);
}
stored procedure:
IF (@Mode='ChkAdminLogin')
BEGIN
SELECT @AdminId = AdminId, @RoleId = RoleId
FROM Admins WHERE Username = @UserName AND [Password] = @Password
IF @AdminId IS NOT NULL
BEGIN
SELECT @AdminId [AdminId],
(SELECT RoleName FROM Roles
WHERE RoleId = @RoleId) [Roles] -- User Valid
END
ELSE
BEGIN
SELECT -1 -- User invalid.
END
END