how to do Log IN with current User in the masterpage - c#

how can i do a login with current user? the current user will be displayed in the masterpage of the default homepage and the label from the masterpage will inherit to the content pages of the master page.
here is my login page asp code:
<div class="container-fluid">
<form class="form-signin" runat="server">
<h1 class="form-signin-heading text-muted">Sign In</h1>
<asp:TextBox ID ="email" runat="server" CssClass="form-control" placeholder="Email Address"></asp:TextBox>
<asp:TextBox ID ="password" runat="server" CssClass="form-control" placeholder="Password" TextMode="Password"></asp:TextBox>
<br />
<asp:Button ID="btnLogIN" runat="server" CssClass="btn btn-primary btn-block" Text="Log In" OnClick="btnLogIN_Click" />
</form>
and my aspx.cs code is here and i dont know if this is correct.
protected void btnLogIN_Click(object sender, EventArgs e)
{
Utility u = new Utility();
string conn = u.connect();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand read = connUser.CreateCommand();
SqlDataReader reader = null;
int empid = 0;
string dbuser = "";
string dbpword = "";
string username = email.Text;
string passwords = password.Text;
string login = "Select * from MOSEFAccount where UserName = '" + username + "' AND Password = '" + passwords + "'";
try
{
connUser.Open();
read.CommandText = login;
reader = read.ExecuteReader();
}
catch
{
Console.WriteLine("Error");
}
while (reader.Read())
{
empid = reader.GetInt32(0);
dbuser = reader.GetString(1);
dbpword = reader.GetString(2);
}
if (username == dbuser && passwords == dbpword)
{
Response.Redirect("~/Default.aspx?ID=" + empid);
}
else
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script type ='text/javascript'>");
sb.Append("alert('Invalid Account');");
sb.Append(#"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditHideModalScript", sb.ToString(), false);
}
connUser.Close();
}

Can you elaborate on the meaning of current user? Unless you login you are not logged in user but anonymous user.
Update:
Store the pulled data in Session object and access it anytime whenever and wherever you like. For example:
For storing details use:-
if (username == dbuser && passwords == dbpword)
{
Session["UserName"] = username;
Session["EmpId"] = empid;
Response.Redirect("~/Default.aspx?ID=" + empid);
}
For displaying use (in the master page):
<%=Session["UserName"]%>
<%=Session["EmpId"]%>
You can build upon this like creating a User class and then creating an instance of this class and storing the instance itself in Session.

Related

Radio button returns wrong answer if no selection was submitted

I am using the below code for my online quiz using ASP.NET and SQL Server 2008. I need my radio button to return wrong answer if nothing checked after pressing submit.
<div id="questionsdiv" runat="server" >
<asp:Label ID="lblalert" runat="server" ForeColor="Red" Font-Size="20px" Visible="false" /><br />
<asp:Repeater ID="questionsrpt" runat="server" OnItemDataBound="questionsrpt_ItemDataBound" >
<ItemTemplate>
<asp:HiddenField ID="hfID" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "id")%>' Visible="false" />
<asp:RequiredFieldValidator ID="rfvquiz" runat="server" Display="Dynamic" ControlToValidate="rbloptions" ValidationGroup="quizvalidation" ForeColor="Red" Text="*" SetFocusOnError="true"/> <asp:Label ID="lblquestion" runat="server" Font-Size="20px" Text='<%# DataBinder.Eval(Container.DataItem, "title")%>' /><br />
<asp:RadioButtonList ID="rbloptions" runat="server" ValidationGroup="quizvalidation" Font-Size="14px" style="font-weight:bold"/>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="btnsubmit" runat="server" OnClick="btnsubmit_Click" Text="Submit" ValidationGroup="quizvalidation" />
</div>
code behind
//quiz answers submitted
protected void btnsubmit_Click(object sender, EventArgs e)
{
SqlDataReader dReader;
string email = "";
string name = "";
string selectedanswer = "";
string correctanswer = "";
int questionId = 0;
int questionscount = 0;
int correctcount = 0;
int wrongcount = 0;
int success = 0;
ArrayList answersList = new ArrayList();
Page.Validate();
if (Page.IsValid)
{
email = txtemail.Text.Trim();
name = txtname.Text.Trim();
//check if this account has already taken the quiz.
DataTable accounts = new DataTable();
SqlCommand checkentrycmd = new SqlCommand("select * from " + quizresponsestable + " where quizid=#quizid and email=#email");
checkentrycmd.Parameters.AddWithValue("quizid", quizId);
checkentrycmd.Parameters.AddWithValue("email", email);
db checkentry = new db();
accounts = checkentry.returnDataTable(checkentrycmd);
if (accounts.Rows.Count > 0)
{
quizdetails.Visible = false;
detailsdiv.Visible = false;
questionsdiv.Visible = false;
lblmessage.Visible = true;
lblmessage.Text = "You have already taken this quiz!";
}
else
{
foreach (RepeaterItem item in questionsrpt.Items)
{
// Checking the item is a data item
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
//get the questionid
var hfId = item.FindControl("hfID") as HiddenField;
questionId = Convert.ToInt32(hfId.Value);
//get the submitted answer
var rdbList = item.FindControl("rbloptions") as RadioButtonList;
selectedanswer = rdbList.SelectedValue;
//disable to prevent submitting again
rdbList.Enabled = false;
//get the correct answer
SqlCommand getanswercmd = new SqlCommand("select optionid from " + quizquestionanswertable + " where questionid=#questionid");
getanswercmd.Parameters.AddWithValue("questionid", questionId);
db getanswer = new db();
dReader = getanswer.returnDataReader(getanswercmd);
if (!dReader.HasRows)
{
//can't find this question/answer
}
else
{
while (dReader.Read())
{
correctanswer = dReader["optionid"].ToString();
}
}
//compare both answers
if (selectedanswer == correctanswer)
{
correctcount++;
rdbList.SelectedItem.Attributes.Add("style", "color: #006400");
}
else
{
wrongcount++;
rdbList.SelectedItem.Attributes.Add("style", "color: #ff0000");
rdbList.Items.FindByValue(correctanswer).Attributes.Add("style", "color: #006400");
}
//add the submitted answer to list
answersList.Add(new string[] { questionId.ToString(), selectedanswer });
}
}
//create entry
SqlCommand insertentrycmd = new SqlCommand("insert into " + quizresponsestable + " (quizid, email, name, correctanswers, wronganswers, lastupdated) values (#quizid, #email, #name, #correctanswers, #wronganswers, #lastupdated);SELECT CAST(scope_identity() AS int)");
insertentrycmd.Parameters.AddWithValue("quizid", quizId);
insertentrycmd.Parameters.AddWithValue("email", email);
insertentrycmd.Parameters.AddWithValue("name", name);
insertentrycmd.Parameters.AddWithValue("correctanswers", correctcount);
insertentrycmd.Parameters.AddWithValue("wronganswers", wrongcount);
insertentrycmd.Parameters.AddWithValue("lastupdated", updatedate);
db insertentry = new db();
success = insertentry.ReturnIDonExecuteQuery(insertentrycmd);
//display the result on screen
if (success > 0)
{
foreach (string[] arr in answersList)
{
SqlCommand insertresponsecmd = new SqlCommand("insert into " + quizuserreponsetable + " (responseid, questionid, optionid, lastupdated) values (#responseid, #questionid, #optionid, #lastupdated)");
insertresponsecmd.Parameters.Clear();
insertresponsecmd.Parameters.AddWithValue("responseid", success);
insertresponsecmd.Parameters.AddWithValue("questionid", arr[0].ToString());
insertresponsecmd.Parameters.AddWithValue("optionid", arr[1].ToString());
insertresponsecmd.Parameters.AddWithValue("lastupdated", updatedate);
db insertresponses = new db();
insertresponses.ExecuteQuery(insertresponsecmd);
}
detailsdiv.Visible = false;
questionscount = correctcount + wrongcount;
lblalert.Visible = true;
//get the completion description from database table
SqlDataReader Treader;
SqlCommand getcompletiondesc = new SqlCommand("select completiondescription from " + quizdetailstable + " where id=#quizid");
getcompletiondesc.Parameters.AddWithValue("quizid", quizId);
db getdesc = new db();
Treader = getdesc.returnDataReader(getcompletiondesc);
if (!Treader.HasRows)
{
lblalert.Text = "Thanks for taking the Quiz." + "<br />" + "You have answered <span style='color:#006400;'>" + correctcount + "</span> questions correctly out of " + questionscount + "<br />";
}
else
{
while (Treader.Read())
{
string completiondesc = Treader["completiondescription"].ToString();
lblalert.Text = completiondesc + "<br />" + "You have answered <span style='color:#006400;'>" + correctcount + "</span> questions correctly out of " + questionscount + "<br />";
}
}
btnsubmit.Visible = false;
}
else
{
lblalert.Visible = true;
lblalert.Text = "Sorry! we could not process your request. Please try again.";
}
}
}
else
{
lblalert.Visible = true;
lblalert.Text = "Please answer all the questions!";
}
}
A question that I have is this:
If you are starting with an empty string for the SelectedValue, why don't you check the ensure that string.IsNullOrEmpty() fails for the value in question? The Page.IsValid() method will return "true" because, as far as it is concerned, the information that it uses to determine whether the Page is validated is complete.
And this part is free: (IMHO) if you are going to use a ValidationGroup, use a ValidationSummary as well. That way, you don't have to worry about individual labels

Get data from database without refreshing the page in ASP.NET

I'm doing a project in ASP.net and with SQL Server. I'm calling a stored procedure on user login screen to authenticate the user. But when I call the stored procedure, the entire page needs to be refreshed in order to get the data.
How can I achieve the same without refreshing the page?
This is my current code
sql = "EXEC dbo.sProc_Admin_Auth #UserNm = '" + User + "',#Pwd = '"+Pwd+"'";
cmd = new SqlCommand(sql, cn.connect());
dr = cmd.ExecuteReader();
if(dr.Read())
{
Session["UserId"] = dr["UserId"].ToString();
Session["LoginId"] = User;
Session["UserNm"] = dr["FullNm"].ToString();// "Jayasurya Satheesh";
Session["Email"] = dr["Email"].ToString();
Session["JoinDt"] = dr["CreateDt"].ToString();
Response.Redirect("Index.aspx");
LblError.Visible = false;
}
else
{
LblError.Visible = true;
LblError.Text = "Login Failed!";
}
Use Ajax Extension, Here is the quick example:
.aspx File
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox runat="server" id="username" name="username" placeholder="Enter Username"></asp:TextBox>
<asp:TextBox name="passwd" ID="passwd" runat="server" placeholder="Enter Password"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Login" onclick="Button1_Click" />
<br />
<asp:Label ID="LblError" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
aspx.cs File - add this to Click event of Login Button
protected void Button1_Click(object sender, EventArgs e)
{
string sql = "";
SqlConnection cn = null;
SqlCommand cmd = null;
SqlDataReader dr = null;
string User = username.Text;
string Pwd = passwd.Text;
//cn = "<< your connection string>>";
try
{
cn.Open();
// Your code
sql = "EXEC dbo.sProc_Admin_Auth #UserNm = '" + User + "',#Pwd = '" + Pwd + "'";
cmd = new SqlCommand(sql, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Session["UserId"] = dr["UserId"].ToString();
Session["LoginId"] = User;
Session["UserNm"] = dr["FullNm"].ToString();// "Jayasurya Satheesh";
Session["Email"] = dr["Email"].ToString();
Session["JoinDt"] = dr["CreateDt"].ToString();
Response.Redirect("Index.aspx");
LblError.Visible = false;
}
else
{
LblError.Visible = true;
LblError.Text = "Login Failed!";
}
}
catch (Exception exce)
{
LblError.Text = exce.Message;
}
finally
{
cn.Close();
}
}
You can find UpdatePanel and ScriptManager under Toolbox -> Ajax Extension
Use try-catch block to handle runtime exceptions.
Based on the code you have, in Web Forms you can:
use an Update Panel;
or Page/Web Method
or a simple(r) Web handler (ashx)
If you want to load the data without refreshing the page. you can expose webservice method or create page method then you can call ASP.NET page method through ajax
[WebMethod]
public static string Insert_Data(string user, string pwd)
{
sql = "EXEC dbo.sProc_Admin_Auth #UserNm = '" + User + "',#Pwd = '"+Pwd+"'";
cmd = new SqlCommand(sql, cn.connect());
dr = cmd.ExecuteReader();
if(dr.Read())
{
Session["UserId"] = dr["UserId"].ToString();
Session["LoginId"] = User;
Session["UserNm"] = dr["FullNm"].ToString();// "Jayasurya Satheesh";
Session["Email"] = dr["Email"].ToString();
Session["JoinDt"] = dr["CreateDt"].ToString();
Response.Redirect("Index.aspx");
LblError.Visible = false;
}
else
{
LblError.Visible = true;
LblError.Text = "Login Failed!";
}
}
Client Side
$(document).ready(function () {
$('#btnsubmit').click(function () {
var name = $('#user').val();
var sex = $('#pwd').val();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Default.aspx/Insert_Data',
data: "{'user':'" + user+ "','pwd':'" + pwd + "'}",
async: false,
success: function (response) {
alert("Record saved successfully..!!");
},
error: function () {
alert("Error");
}
});
});
});
There are 3 possible ways I know of:
1) using update panel:
see example: http://www.aspdotnet-pools.com/2014/07/ajax-login-form-in-aspnet-using-cnet.html
2) using webmethod:
see example: http://www.aspforums.net/Threads/133296/Develop-simple-AJAX-Login-form-using-jQuery-in-ASPNet/
3) using tiered coding:
see example: https://www.codeproject.com/Articles/170882/jQuery-AJAX-and-HttpHandlers-in-ASP-NET
I prefer method 3 coding as it is more flexible and the tiered coding concept is portable to other web programming platform.

Repeater - textbox content to database C#

I'm trying to insert content to my local database from a textbox inside a repeater element, in a post - comment way. So far I've tried looping on all the generated rows to find the specific textbox but I have had no luck, either the insert goes empty, or I get 1 insert per preexisting row, or I get the same value inserted over and over again through different posts.
I finally tried to pass the post id to the itemfinder and it's kind of working, but the "comm_contenido" inserts from the textbox are still going empty to the database.
My question is what it the correct and more direct way to handle these kind of inserts from within a Repeater?.
C#:
protected void Button1_Command(object sender, CommandEventArgs e)
{
string postid = e.CommandArgument.ToString();
string emailcc = Session["EMAIL"].ToString();
string user_id = Session["ID"].ToString();
string usrnom = Session["NOMBRE"].ToString();
string usrfoto = Session["FOTO_URL"].ToString();
//string COMM_CONTENIDO = lblcomm.Text.ToString();
var COMM_fecha = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
TextBox txt2;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConexionBD"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
int m = Int32.Parse(postid);
txt2 = (TextBox)Repeater_UsrPosts.Items[m].FindControl("txtcomentar");
string txt1 = txt2.Text;
cmd.CommandType = CommandType.Text;
cmd.CommandText = (#"INSERT INTO MIEMBROS_Comments (COMM_USER_ID, COMM_CONTENIDO, COMM_FECHA, COMM_USER_NOMBRE, COMM_USER_FOTO, COMM_POST_ID) VALUES ('"
+ user_id + "','" + txt1 + "','" + COMM_fecha + "','" + usrnom + "','" + usrfoto + "','" + postid + "');");
cmd.Connection = conn;
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
}
}
//txtpublica.Text = "";
traerposts();
}
ASP:
<asp:Repeater ID="Repeater_UsrPosts" runat="server" >
<ItemTemplate>
<!-- Post -->
<div class="post clearfix">
<div class="user-block">
<img alt="" src="<%#Eval("post_user_foto")%>" class="img-circle img-bordered-sm" />
<span class="username">
<%#Eval("post_user_nombre") %>
<i class="fa fa-times"></i>
</span>
<span class="description"><%#Eval("post_fecha") %></span>
</div>
<!-- /.user-block -->
<p>
<%#Eval("post_contenido") %>
</p>
<ul class="list-inline">
<li><i class="fa fa-share margin-r-5"></i>Share</li>
<li><i class="fa fa-thumbs-o-up margin-r-5"></i>Like
</li>
<li class="pull-right">
<asp:LinkButton ID="bttnabrircomentarios" runat="server" class="link-black text-sm">
<i class="fa fa-comments-o margin-r-5"></i>Comments</asp:LinkButton>
</li>
</ul>
<asp:TextBox ID="txtcomentar" runat="server" class="form-control input-sm" placeholder="Escribe un comentario" EnableViewState="False"></asp:TextBox>
<%# Eval("post_id") %> -
<asp:Button ID="Button1" runat="server" Text="Button"
OnCommand="Button1_Command" CommandName="myCommand"
CommandArgument='<%# Eval("post_ID") %>' />
<br />
</div>
<!-- /.post -->
</ItemTemplate>
</asp:Repeater>
You can reach the TextBox Control by assigning OnTextChanged to it, and you can also assign its AutoPostBack to true if you wanted to reach the data immediately.
but you should use if(!IsPostBack) before you bind your data to your repeater, so it doesn't reset your Controls before you could reach the data.
OnTextChanged needs two parameter, one of them is the sender object which is calling it, That's your TextBox, something like..
ASP
<asp:Repeater ID="RepeaterExample" runat="server"><ItemTemplate>
<asp:TextBox runat="server" ID="TextBoxExample" AutoPostBack="True" OnTextChanged="TextBoxExample_OnTextChanged"/>
</ItemTemplate></asp:Repeater>
Behind Code
protected void TextBoxExample_OnTextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox) sender;
//Response.Write(txt.Text);
//or whatever you want to do with it.
}
and if you wanted to use it with Button_OnClick, you should use like a global string you can call later, you can do something like this..
ASP
<asp:Button runat="server" ID="ButtonExample" OnClick="ButtonExample_OnClick"/>
Behind Code
private string text = "";
protected void TextBoxTest_OnTextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
text = txt.Text;
}
protected void ButtonExample_OnClick(object sender, EventArgs e)
{
//Response.Write(text);
}
but the last method will take the value of the last TextBox whose text has changed, unless you add it together like..
text += txt.Text;
Hope, I could help..
This were the changes that worked for me to locate the specific textbox and prevent posting unwanted data.
C#:
protected void Button1_Command(object sender, CommandEventArgs e)
{
string postid = e.CommandArgument.ToString();
string emailcc = Session["EMAIL"].ToString();
string user_id = Session["ID"].ToString();
string usrnom = Session["NOMBRE"].ToString();
string usrfoto = Session["FOTO_URL"].ToString();
var COMM_fecha = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
Control s = (Control)sender;
TextBox tb = (TextBox)s.NamingContainer.FindControl("txtcomentar");
tb.ReadOnly = true;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConexionBD"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
string txt1 = tb.Text;
cmd.CommandType = CommandType.Text;
cmd.CommandText = (#"INSERT INTO MIEMBROS_Comments (COMM_USER_ID, COMM_CONTENIDO, COMM_FECHA, COMM_USER_NOMBRE, COMM_USER_FOTO, COMM_POST_ID) VALUES ('"
+ user_id + "','" + txt1 + "','" + COMM_fecha + "','" + usrnom + "','" + usrfoto + "','" + postid + "');");
cmd.Connection = conn;
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
}
}
traerposts();
}
And on the ASP I added the property EnableVIewState="true" to the textbox and also to the repeater.
At last, most important, I added if (!Page.IsPostBack) to the onload event.
And with all this together the comments on each post are being inserted correctly.

Entered correct data but log in keeps failing c# asp.net [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I am new to c# asp.net. got this code from a tutorial but I am getting an error. My label says log in failed though I entered the correct data. Please help me :( and it says: Object reference not set to an instance of an object when I entered an incorrect data.
here's my ConnectionClass.cs
public class ConnectionClass
{
private static SqlConnection conn;
private static SqlCommand command;
static ConnectionClass()
{
string connectionString = ConfigurationManager.ConnectionStrings["CoffeeDBConnectionString"].ToString();
conn = new SqlConnection(connectionString);
command = new SqlCommand("", conn);
}
public static User LoginUser(string login, string password)
{
//Check if user exists
string query = string.Format("SELECT COUNT(*) FROM SkyMusic.dbo.user WHERE username = '{0}'", login);
command.CommandText = query;
try
{
conn.Open();
int numofUsers = (int) command.ExecuteScalar();
if (numofUsers < 1)
{
//user exists, check if the passwords match
query = string.Format("SELECT password FROM user WHERE username = '{0}'", login);
command.CommandText = query;
string dbPassword = command.ExecuteScalar().ToString();
if (dbPassword == password)
{
//Passwords match
query = string.Format("SELECT email, user_type FROM users WHERE username = '{0}'", login);
command.CommandText = query;
SqlDataReader reader = command.ExecuteReader();
User user = null;
while (reader.Read())
{
string email = reader.GetString(0);
string type = reader.GetString(1);
user = new User(login, password, email, type);
}
return user;
}
else
{
//passwords do not match
return null;
}
}
else
{
return null;
}
}
finally
{
conn.Close();
}
}
my login:
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div id="formcont">
<table>
<tr>
<td><asp:Label ID="Label1" runat="server" Text="Username:"></asp:Label></td>
<td><asp:TextBox ID="TextBox1" runat="server" Width="142px"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="Label2" runat="server" Text="Password:"></asp:Label></td>
<td><asp:TextBox ID="TextBox2" runat="server" Width="142px"></asp:TextBox></td>
</tr>
<tr>
<td colspan="2"></br><asp:Button ID="Button1" runat="server" Text="Log In" />
<br />
</td>
</tr>
</table>
<p>Don't have an account? Click here!</p>
</div>
</asp:Content>
and
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
User user = ConnectionClass.LoginUser(txtUname.Text, txtPass.Text);
if (user != null)
{
Session["login"] = user.login;
Session["type"] = user.type;
Response.Redirect("Home.aspx");
}
else
{
lblError.Text = "Login Failed";
}
}
please help :(
here's my db
id, username, password, email, user_type
There are two problems or error
1. You can not login with correct credential:
Check this.
if (numofUsers < 1)
{
//user exists, check if the passwords match
query = string.Format("SELECT password FROM user WHERE username = '{0}'", login);
If no of user is less than 1 how can a user exists in system.
2. Null reference error:
In case user does not exists then this method returned null you should be handling null and showing incorrect credential or user does not exists
EDIT
Rahul seems to be correct in comments of question. Debug your code first.
EDIT
As per your comment you were using
if (numofUsers < 1)
then you changed to
if (numofUsers <= 1)
Use it as
if (numofUsers > 0)

Admin user not able to login (Role based)

I have a functionality where Super Admin creates user. For Ex: SuperUser creates admin.
Then, I am unable to log in with the Admin details. The data of the admin is getting stored in the table. I am sure its role based issue. But I am not getting exactly where it is stucking. Please see the code for your reference:-
Role Define:-
<div class="form_div">
<div class="normalText3">
<div class="txtlbl">Username:</div>
<div>
<asp:TextBox ID="txtUsername" runat="server" CssClass="form_txtfld"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtUsername" ErrorMessage="*" ></asp:RequiredFieldValidator>
</div>
</div>
<div class="normalText3">
<div class="txtlbl">Password:</div>
<div>
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" CssClass="form_txtfld"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtUsername" ErrorMessage="*" ></asp:RequiredFieldValidator>
</div>
</div>
<div class="normalText3">
<div class="txtlbl"></div>
<div>
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="button-form" onclick="btnLogin_Click" />
</div>
</div>
</div>
Code behind for the login data:-
protected void btnLogin_Click(object sender, EventArgs e)
{
String LoginID = txtUsername.Text.Trim().ToLower();
String LoginPassword = txtPassword.Text.Trim();
LoginLogic _LoginLogic = new LoginLogic();
DataSet dsLoginDetails = _LoginLogic.Ds_getLoginDetails(LoginID, LoginPassword);
if (dsLoginDetails.Tables[0].Rows.Count > 0)
{
if (LoginID.ToLower() == "mserm")
{
Session["user"] = LoginID;
Session["role"] = UserRoles.RELATIONSHIPMANAGER;
Session["password"] = LoginPassword;
Response.Redirect("mseLoanApplications.aspx");
}
else if (LoginID.ToLower() == "msebo")
{
Session["user"] = LoginID;
Session["role"] = UserRoles.BUSINESSOFFICER;
Session["password"] = LoginPassword;
Response.Redirect("mseLoanApplications.aspx");
}
else if (LoginID.ToLower() == "mser")
{
Session["user"] = LoginID;
Session["role"] = UserRoles.RISKOFFICER;
Session["password"] = LoginPassword;
Response.Redirect("mseLoanApplications.aspx");
}
else if (LoginID.ToLower() == "fxadmin")
{
Session["user"] = LoginID;
Session["role"] = "fxadmin";
Session["password"] = LoginPassword;
Response.Redirect("rblfileuploader.aspx");
}
else if (LoginID.ToLower() == "mediaadmin")
{
Session["user"] = LoginID;
Session["role"] = "mediaadmin";
Session["password"] = LoginPassword;
Response.Redirect("mediakitadmin.aspx");
}
else if (LoginID.ToLower() == "dropboxadmin")
{
Session["user"] = LoginID;
Session["role"] = "dropboxadmin";
Session["password"] = LoginPassword;
Response.Redirect("dropboxadmin.aspx");
}
else if (LoginID.ToLower() == "careeradmin")
{
Session["user"] = LoginID;
Session["role"] = "careeradmin";
Session["password"] = LoginPassword;
Response.Redirect("CareerJobList.aspx");
}
else if (LoginID.ToLower() == "careersa")
{
Session["user"] = LoginID;
Session["role"] = "careersa";
Session["password"] = LoginPassword;
Response.Redirect("CareerJobList.aspx");
}
else
{
Session["user"] = LoginID;
Session["role"] = "admin";
Session["password"] = LoginPassword;
Response.Redirect("CareerJobList.aspx");
}
}
else
{
String sc = "<Script>alert('Can not Login. Invalid Username or Password')</script>";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "Ad" + DateTime.Now, sc, false);
}
}
Please help, I tried debugging the code and I was getting null values.
The following code you provided in your comment for the Ds_getLoginDetails method:
public class LoginLogic
{
public LoginLogic();
public void ChangePassword(string LoginID, string LoginPassword);
public DataSet Ds_getLoginDetails(string LoginID, string LoginPassword);
}
The Ds_getLoginDetails method does not return any data and it does not query your database.
You when you initialise a new instance of LoginLogic and call Ds_getLoginDetails you are never actually returning an object.
Your login details should look something like:
public DataSet Ds_getLoginDetails(string LoginID, string LoginPassword)
{
var ds = new DataSet();
using (var conn = new SqlConnection("Your connection string comes here"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "select * from Users where LoginID=#LoginID and Password=#Password";
cmd.Parameters.AddWithValue("#LoginID", LoginID);
cmd.Parameters.AddWithValue("#Password", LoginPassword);
var adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds);
}
return ds;
}

Categories

Resources