ASP.NET Conversion failed when converting the nvarchar value - c#

I'm trying to display the username in login session in the master page, I got this error after i log in it says
Conversion failed when converting the nvarchar value to data type
int.
Here's my MasterPage.cs
public partial class HRPortal_HRPortalMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Username"] != null)
{
if (!IsPostBack)
{
GetName();
}
}
}
void GetName()
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
string query = #"SELECT Username FROM Users WHERE UserID=#UserID";
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#UserID", Session["Username"].ToString());
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
ltName.Text = dr["Username"].ToString();
}
}
}
}
}
}
And here is my Login.cs
protected void btnLogin_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = #"SELECT u.UserID, u.Username, u.Password, t.UserType FROM Users u INNER JOIN UserType t ON t.TypeID = u.TypeID WHERE Username=#Username AND Username=#Username";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#Username", txtUsername.Text);
cmd.Parameters.AddWithValue("#Password", Helper.CreateSHAHash(txtPassword.Text));
//DataTable dt = new DataTable();
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
string Utype;
Utype = dr["UserType"].ToString();
if (Utype == "Employee")
{
Session["Username"] = txtUsername.Text;
Response.Redirect("~/HrPortal/Home.aspx");
}
else
{
Session["Username"] = txtUsername.Text;
Response.Redirect("~/Administrator/Home.aspx");
}
}
}
else
{
error.Visible = true;
}
}
}
}

You wrote
SELECT Username FROM Users WHERE UserID=#UserID
yet for the #UserID parameter you pass in the username.
Are you sure you didn't mean to write
SELECT Username FROM Users WHERE Username = #UserID
That would make more sense. The UserID and the username are unlikely to match, I would expect. It would also help to explain the error, since I assume that UserID in the database is an integer column, whereas the username is a string (i.e. nvarchar in SQL Server parlance) - and logically you can't compare a number to a string.

profiously UserID datatype is int and not nvarchar on your Database. Try:
cmd.Parameters.Add("#UserID",SqlDbType.Int).Value = int.Parse(Session["Username"].ToString());

You are passing username as userid here:
cmd.Parameters.AddWithValue("#UserID", Session["Username"].ToString());
pass Userid instead and there should be no problem.

You are using your Username as your UserID. Here:
cmd.Parameters.AddWithValue("#UserID", Session["Username"].ToString());
It should be:
cmd.Parameters.AddWithValue("#UserID", Session["UsedID"].ToString());
if you have stored the UserId in you session.
or SELECT Username FROM Users WHERE Username=#UserID ?
You also have a mistake in your other select, it should be
SELECT u.UserID, u.Username, u.Password, t.UserType FROM Users u INNER JOIN UserType t ON t.TypeID = u.TypeID WHERE Username=#Username AND **Password=#Password**

I think you must set session["UserID"] in login and use that in this query
string query = #"SELECT Username FROM Users WHERE UserID=#UserID";
base of your select in login, UserID is diffrent from Username

Related

ASP.NET C# Login with Roles is not Redirecting

I want to create a login module with roles. I have two tables Users and UserType.
The problem is after clicking the login it does not redirect to assigned pages, its still in the login page.
Here's the Login.cs code
protected void btnLogin_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = #"SELECT u.UserID, u.Username, u.Password, t.UserType FROM Users u INNER JOIN UserType t ON t.TypeID = u.TypeID WHERE Username=#Username AND Username=#Username";
//string query = #"SELECT UserID, Username, Password, TypeID FROM Users WHERE Username=#Username AND Username=#Username";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#Username", txtUsername.Text);
cmd.Parameters.AddWithValue("#Password", Helper.CreateSHAHash(txtPassword.Text));
DataTable dt = new DataTable();
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
Session["UserID"] = dr["UserID"].ToString();
}
if (dt.Rows.Count != 0)
{
string Utype;
Utype = dt.Rows.ToString().Trim();
if (Utype == "HR Admin")
{
Session["Username"] = txtUsername.Text;
Response.Redirect("~/Administrator/Home.aspx");
}
if (Utype == "Employee")
{
Session["Username"] = txtUsername.Text;
Response.Redirect("~/HrPortal/Home.aspx");
}
}
}
else
{
error.Visible = true;
}
}
}
}
}

How to display data based on current logged user?

How do you display data that is retrieved from database according to the current login user? I know that I should declare the id, but I don't really know how...
I have 2 tables in SQL.
User:
ID || Name || Last_Name || date ||
List
ID || Product || description || user_id
private void BindGridView()
{
string constr = ConfigurationManager.ConnectionStrings["strConn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = #"SELECT * From List where ID = #ID";
cmd.Parameters.AddWithValue("#ID", ?);
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
ad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
according to your table the query should be
select * from list where user_id = id
here id is the userid passed to the method
e.g private void BindGridView(int id)
another way is to use session
and to store id after login you have to store it in session
session["UserId"] = userid;
and you can use it in function like
int userid = Convert.ToInt32(session["UserId"]);
cmd.CommandText = "SELECT * FROM list where user_id = " + userid + "";
and also dont forget to use conn.Open() and conn.Close() after executing query

Must declare the scalar variable "#loginName"

I am trying to login using LoginID and Password as user name and password respectively, however I'm getting an exception:
Must declare the scalar variable “#loginName”
protected void SignInButton_Click(object sender, EventArgs e)
{
int customerId = 0;
int loginName = Convert.ToInt32(LoginTextBox.Text);
string password = PasswordTextBox.Text;
SqlCommand command = new SqlCommand();
SqlDataReader reader;
command.CommandText = "Select CustomerID from Customers where LoginID= #loginName and Password= #password";
command.Parameters.AddWithValue("#LoginID", loginName);
command.Parameters.AddWithValue("#Password", password);
command.Parameters.AddWithValue("#CustomerID", customerId);
reader = DbUtility.GetDataReader(command);
if (reader.HasRows)
{
reader.Read();
customerId = reader.GetInt32(0);
Session["CustomerID"] = customerId;
Response.Redirect("ListCategories.aspx");
}
else
{
MessegeLabel.Text = "User Name or Password Incorrect";
}
}
You have some SQL there which includes the parameter #loginName. You never provide that parameter; you provide an unused parameter called #LoginID instead (along with an unused #CustomerID also, for some reason).
It's telling you that it needs you to provide all the parameters your SQL snippet uses.
command.CommandText = "Select CustomerID from Customers where LoginID= #loginName and Password= #password";
command.Parameters.AddWithValue("#LoginID", loginName);
command.Parameters.AddWithValue("#Password", password);
command.Parameters.AddWithValue("#CustomerID", customerId);
So provide it:
command.Parameters.AddWithValue("#loginName", loginName);

Insert records by user who's connected Winforms

I have a form (F1) where user will provide their respective credentials username and password .
After a sucessfull login , the controls moves to the Client Form (F2) and display welcome username in a label on it.
Client Form contains:
labels and textboxes(name, address, function , ...)
Button Insert
DataGridView bind to DB (name, address, function ,.., UserId)
Now , I want to insert a Client.
After filling textboxes, I want to add a Client a show it added by user who's connected.
Ex: if I logged with Username Rose after that add a client, in my datagridView , show me my row of insert added by Rose.
Code of my Login and passing username to Client Form
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
//textBox2.Text = Encrypt(textBox2.Text);
SqlConnection con = new SqlConnection("Data Source=User-PC\\SQLEXPRESS;Initial Catalog=timar;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("select Username from [User] where Username='" + textBox1.Text + "' and Password='" + textBox2.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
this.Hide();
Client c = new Client(dt.Rows[0][0].ToString());
v.Show();
}
else if (dt.Rows.Count > 1)
{
MessageBox.Show("Nom d'utilisateur et Mot de passe dupliqué !");
}
else
MessageBox.Show("Nom d'utilisateur ou Mot de passe incorrecte !");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is my code of Insert:
public Client(string username)
{
InitializeComponent();
lblUser.Text = username;
DisplayData();
FillData();
}
private void button1_Click(object sender, EventArgs e)
{
if ( comboBox2.SelectedValue != null && textBox1.Text != string.Empty && textBox2.Text != string.Empty && textBox4.Text != string.Empty)
{
string cmdStr = "Insert into Client (idUser,name,address,function,telephone,commentaire)values (#idUser,#name,#,address,#function,#telephone,#commentaire)";
SqlConnection con = new SqlConnection("Data Source=User-PC\\SQLEXPRESS;Initial Catalog=timar;Integrated Security=True");
SqlCommand cmd = new SqlCommand(cmdStr, con);
con.Open();
//The problem in the line below how Can I get the id of username,Error cannot convert string Rose to int.
cmd.Parameters.AddWithValue("#idUser",label.Text);
cmd.Parameters.AddWithValue("#name", (comboBox2.SelectedValue));
cmd.Parameters.AddWithValue("#,address", textBox1.Text);
cmd.Parameters.AddWithValue("#function", textBox2.Text);
cmd.Parameters.AddWithValue("#telephone", textBox4.Text);
cmd.Parameters.AddWithValue("#commentaire",txtArchive.Text);
int LA = cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Le Client a été ajouter avec succés !","Saisie Rendez-vous", MessageBoxButtons.OK, MessageBoxIcon.Information);
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Vérifier que tous les champs sont remplis !","Erreur",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
I am not able to figure out how to do this, I am very new to c# and trying to learn.
Thanks in Advance.
When checking for login, write your query this way:
SELECT [Id], [UserName] from [Users] WHERE [UserName]=#UserName AND [Password]=#Password
Then store both [Id] and [UserName] which you get from the query when the login is successful (the resultset contains one record). This way you can use username and id of the logged-in user every time you need.
For example:
var cmd = #"SELECT [Id], [UserName] FROM [Users] " +
#"WHERE [UserName] = #UserName AND [Password] = #Password";
var cn = #"Data Source=User-PC\SQLEXPRESS;Initial Catalog=timar;Integrated Security=True";
var da = new SqlDataAdapter(cmd, cn);
da.SelectCommand.Parameters.AddWithValue("#UserName", textBox1.Text);
da.SelectCommand.Parameters.AddWithValue("#Password", textBox2.Text);
var dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 1)
{
int id = dt.Rows[0].Field<int>("Id");
string userName = dt.Rows[0].Field<string>("UserName");
//...
}
Note:
You should used parametrized query to prevent SQL Injection attacks.
First and foremost, parameterize your queries for login! At the moment you are VERY susceptible to SQL Injection attack! Lest you get a visit from Little Bobby Tables.
In answer to your question, change the query on your login form to return both the user's Id and their username.
SqlDataAdapter sda = new SqlDataAdapter("select Id, Username from [User] where Username=#Username and Password=#Password", con);
Now, when you read the single result you can get Id from field 0 and username from field 1.
if (dt.Rows.Count == 1)
{
this.Hide();
var row = dt.Rows[0];
int userId = (int)row[0];
string username = (string)row[1];
Client c = new Client(userId, username);
v.Show();
}
Note also in that code, I'm passing both to the Client form. Update the constructor to save both pieces of information in local variables:
public class Client : Form
{
private int _userId;
public Client(int userId, string username)
{
InitializeComponent();
_userId = userId;
lblUser.Text = username;
DisplayData();
FillData();
}
}
Thereafter, you can use _userId anywhere you like in Client form. E.g. in the save button click:
cmd.Parameters.AddWithValue("#idUser",_userId);

Running sql SubQueries in asp.net c#

hello everyone i am working on mycollege project and trying to make a user login application in asp.dot net.
I have two tables in my database one is customer full detail and other is customer login detail
What I want to do to count the row in first query and if login_id and password matches then it executes the other query to retrive and displays the customer first name, on the redirectedd page
below is what i have done any other type of method is also welcomed
here is my code
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
SqlConnection connection = new SqlConnection(conn);
connection.Open();
cmd = new SqlCommand("select COUNT(*) from customer_login where login_id = #a and pass_login=#b",connection);
cmd.Parameters.AddWithValue("#a", Login1.UserName);
cmd.Parameters.AddWithValue("#b", Login1.Password);
string user_name;
int i = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if (i == 1)
{
e.Authenticated = true;
cmd = new SqlCommand("select f_name from customer where id = (select cust_id from customer_login where login_id = #a)", connection);//This query successfully runs in mssms but it gives error in aspx
// cmd.Parameters.AddWithValue("#c",new SqlCommand ("select cust_id from customer_login where login_id = #a"));
//cmd.Parameters.AddWithValue("#a", Login1.UserName);
sdr = cmd.ExecuteReader();
sdr.Read();
user_name = sdr["f_name"].ToString();
sdr.Close();
if (Session["productID"] != null)
{
Session["user"] = user_name.ToString();
Response.Redirect("~/Detail/cart.aspx");
}
else
{
Response.Redirect("Default.aspx");
}
}
else
{
e.Authenticated = false;
}
}
the problem is it gives following error "Incorrect syntax near the keyword 'select'.
Must declare the scalar variable "#a". "
thanku
because you have not assigned value to #a
cmd = new SqlCommand("select f_name from customer where id = (select cust_id from customer_login where login_id = #a)", connection);
cmd.Parameters.AddWithValue("#a",Value);
please
//cmd.Parameters.AddWithValue("#a", Login1.UserName);
uncomments this line to
cmd.Parameters.AddWithValue("#a", Login1.UserName);
then check again

Categories

Resources