Running sql SubQueries in asp.net c# - 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

Related

Check if a SQL table exists in C#

var conn = new SqlConnection("");
try
{
conn.Open();
string s = $"SELECT Email FROM {tableName} WHERE {query}";
SqlCommand cmd = new SqlCommand(s, conn);
SqlDataReader reader = cmd.ExecuteReader();
int email = reader.GetOrdinal("Email");
while (reader.Read())
{
var response = new User
{
Email = reader.IsDBNull(email) ? null : reader.GetString(email)
};
emailList.Add(response);
}
reader.Close();
}
finally
{
conn.Close();
}
How do I update this code to verify if a table with name {tableName} exists in sql database before executing this code.
Run the following query and substitute {tablename} with the name of the table, you are looking for:
SELECT name, SCHEMA_NAME(schema_id) AS [schema], create_date, object_id, modify_date FROM sys.tables WHERE name = {tablename}

ASP.NET Conversion failed when converting the nvarchar value

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

Retrieving ID while having only user_name

I'm trying to make a private message system.
What I have so far.
- checking if player exists with the name from textbox, if not, error shows up.
Now, I'm trying to insert it to the table. The problem is that the table have 2 colums
to_user_id
from_user_id
And becasuse I'm using a textbox to enter the name of the user, I dont how to retrieve to_user_id from users table while having only name.
this is my code
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString());
conn.Open();
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select * from [users]";
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
while (rd.Read())
{
if (rd[1].ToString() == TextBox_To.Text)
{
flag = false;
break;
}
}
conn.Close();
if (flag == true)
{
Label1.Visible = true;
Label1.Text = "User does not exist";
}
else if(flag == false)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString()))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = #"INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date)
VALUES (#title, #content, #to, #from, #date)";
cmd.Parameters.AddWithValue("#title", TextBox_Title.Text);
cmd.Parameters.AddWithValue("#content", TextBox_Msg.Text.Replace("\n", "<br/>"));
cmd.Parameters.AddWithValue("#to", TextBox_To.Text);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
cmd.Parameters.AddWithValue("#from", Session["id"].ToString());
con.Open();
cmd.ExecuteNonQuery();
}
}
Of course I got an error
Conversion failed when converting the nvarchar value 'username' to data type int.
#edit,
#cordan I tried this
DECLARE #user_id = (SELECT id FROM users WHERE user_login=#to );
INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date)
VALUES (#title, #content, #user_id, #from, #date);
cmd.Parameters.AddWithValue("#to", TextBox_To.Text);
got this error
Incorrect syntax near '='.
Must declare the scalar variable "#user_id".
This bit here is a huge NO!!
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select * from [users]";
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
while (rd.Read())
{
if (rd[1].ToString() == TextBox_To.Text)
{
flag = false;
break;
}
}
conn.Close();
You are selecting every single user from the users table, just to determine if the one you're trying to find exists.
Aside from the fact that you could almost certainly just add:
if (rd[1].ToString() == TextBox_To.Text)
{
foundUserId = (int)rd[0]; // I'm assuming the first column in users is the Id - it probably is
flag = false;
break;
}
DONT DO THAT!!
Instead, you should just be looking for the one username you're interested in
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select top 1 Id from [users] where username=#username";
cmdd.Parameters.AddWithValue("#username",username);
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
var userId = 0;
if(rd.Read())
{
userId = (int)rd[0];
}
conn.Close();
if (userId == 0)
{
Label1.Visible = true;
Label1.Text = "User does not exist";
return;
}
else
.... // userId holds the users Id
...
cmd.Parameters.AddWithValue("#to", userId);

Ado.Net Fill Grid By Logged in User

I need to fill a gridview with records according to the currently logged in user. My stored procedure asks for one parameter, the ID of the user. I want that parameter to be the currently logged in user but i cant figure out how to accomplish this.
My stored Procedure to grab the records:
#cnt_ID int
AS
BEGIN
SELECT TOP (100) PERCENT dbo.vtCursusPlanning.cur_CursusID AS CursusID, dbo.vtCursusPlanning.cur_Omschrijving AS Omschrijving, CONVERT(varchar,
dbo.vtData.dat_Datum, 100) AS Datum, CONVERT(varchar, dbo.vtData.dat_Start, 100) AS DStart, CONVERT(varchar, dbo.vtData.dat_Stop, 100) AS DStop,
dbo.vtContactPersonen.cnt_Initialen AS Username
FROM dbo.vtData INNER JOIN
dbo.vtCursusPlanning ON dbo.vtData.cur_FK = dbo.vtCursusPlanning.cur_CursusID INNER JOIN
dbo.vtContactPersonen ON dbo.vtCursusPlanning.cnt_FK = dbo.vtContactPersonen.cnt_ID INNER JOIN
dbo.vtCursusCursisten ON dbo.vtData.cur_FK = dbo.vtCursusCursisten.cst_fk
WHERE (dbo.vtContactPersonen.cnt_ID = #cnt_ID) AND (NOT (dbo.vtCursusCursisten.cst_fk IS NULL)) AND (NOT (dbo.vtCursusPlanning.cur_Project IS NULL))
ORDER BY DStart
END
And my attempt to fill the gridview with my C# code.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
GridView1.DataKeyNames = new string[] { "#cnt_ID" };
string connectionString = ConfigurationManager.ConnectionStrings["KRIS-Planning"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("spOffice2010Evaluaties", conn);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add("#cnt_ID", SqlDbType.Int);
comm.Parameters["#cnt_ID"].Value = UserID;
try
{
conn.Open();
reader = comm.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
reader.Close();
}
catch (Exception ex)
{
dbErrorLabel.Text = Convert.ToString(ex);
}
finally
{
conn.Close();
}
}
}
Try this one instead;
string UserId = HttpContext.Current.User.Identity.Name;

Use Selected ID in DetailView as Parameter

If i find the 3 "Yes" in my table for a given ID then i am sending an email. So as you can see the code below is using the querystring as parameter and using that in my select statement but what i want to do is use the selected ID in the DetailView instead of the query-string. Here is the code that uses the query-sting:
protected void Check_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT count(*) from MyTable WHERE ID =#ID And (field1='Yes' And field2='Yes' And field3='Yes')", con);
cmd.Parameters.Add("#ID", Request.QueryString["ID"]);
cmd.Connection = con;
con.Open();
int result = (int)cmd.ExecuteScalar();
if (result == 1)
{
send email...
}
and here is the updated code that i modified and tried to use the DetailView ID but does not work properly, what am i doing wrong here pls help:
protected void Check_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
{
string ID = Detailview1.Rows[0].Cells[1].Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT count(*) from MyTable WHERE ID =#ID And (field1='Yes' And field2='Yes' And field3='Yes')", con);
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ID;
cmd.Connection = con;
con.Open();
int result =(int) cmd.ExecuteScalar();
if (result == 1)
{
send email...
}
Looks like you are always looking same row which is the header in most of the case.
string ID = Detailview1.Rows[0].Cells[1].Text;
Instead of this you should use parameters of the event like e if you set every thing correctly you can get the ID by e.Keys. You can check the value of it in debug mode.

Categories

Resources