I am on the verge of finishing a web-project similar to nike+ and runkeeper, it is a prototype for a company make running devices, anyhow I have stumbled upon a problem here, and I am getting a error message that says Invalid syntax near keyword WHERE. I cannot for the life of me figure it out.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Email"] == null) //If user is not logged in, send to startpage
{
Response.Redirect("~/UserPages/Default.aspx");
}
else if (!IsPostBack)
{
//User info is selected from DB and put in textboxes
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["jaklin11ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM [Users] WHERE Email = #Email", con1);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Email", Session["Email"].ToString());
using (con1)
{
con1.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
imgProfileImageProfile.ImageUrl = rdr["ProfileImage"].ToString();
textProfileImageProfile.Text = rdr["ProfileImage"].ToString();
textFirstNameProfile.Text = rdr["FirstName"].ToString();
textLastNameProfile.Text = rdr["LastName"].ToString();
textHeightProfile.Text = rdr["Height"].ToString();
textWeightProfile.Text = rdr["Weight"].ToString();
textPasswordProfile.Text = rdr["Password"].ToString();
textBirthdateProfile.Text = rdr["Birthdate"].ToString();
textAreaCode.Text = rdr["AreaCode"].ToString();
textTown.Text = rdr["Town"].ToString();
ddlGenderProfileEdit.Text = rdr["Gender"].ToString();
}
}
}
}
Related
It only can be called once. where did I gone wrong? The second time it executes, no text appears. The Login and Site.Master are two different partial classes. I am kind of confounded on how to solve this.
Login.aspx
public partial class Login : System.Web.UI.Page
{
SqlDataReader dR;
DatabaseMgmt drObj = new DatabaseMgmt();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void submitButton_Click(object sender, EventArgs e)
{
string strEmail, strPwd;
int intShopperID;
strEmail = txtEmail.Text.ToLower();
strPwd = txtPwd.Text.Trim();
string strSqlCmd = "SELECT ShopperID FROM Shopper WHERE Email ="+ "'" + strEmail + "'" + "AND Passwd ="+ "'"+ strPwd + "'";
dR = drObj.ExecuteSelect(strSqlCmd);
if(dR.Read())
{
intShopperID = Convert.ToInt32(Session["ShopperID"]);
Session["ShopperID"]=intShopperID;
Response.Redirect("Default.aspx");
}
else
{
intShopperID = 0;
lblMsg.Text = "Incorrect email or password";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
dR.Close();
}
}
Site.Master
public partial class Site : System.Web.UI.MasterPage
{
DatabaseMgmt dBObj = new DatabaseMgmt();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ShopperID"] != null)
{
string strSqlCmd;
strSqlCmd = "SELECT Name FROM Shopper WHERE ShopperID = " + Session["ShopperID"];
lblWelcome.Text = "Welcome Eric";
logoutButton.Visible = true;
loginButton.Visible = false;
regButton.Visible = false;
}
else
{
logoutButton.Visible = false;
loginButton.Visible = true;
regButton.Visible = true;
lblWelcome.Text = "";
}
}
Display Welcome Message
First Run
Second Run
database
I did not see where you are reading the ShopperID from the database. Perhaps that is your issue. ???
To address the Parameterisation issue, I think you should consider something more like this:
public int GetShopperID(System.String strEmail, System.String strPwd) {
int result = 0;
string strSqlCmd = "SELECT ShopperID FROM Shopper WHERE Email = #Email AND Passwd = #Passwd";
using (var cmd = new System.Data.SqlClient.SqlCommand(strSqlCmd, new System.Data.SqlClient.SqlConnection(_databaseConnection))) {
cmd.Parameters.Add("#Email", System.Data.SqlDbType.VarChar, 50);
cmd.Parameters.Add("#Passwd", System.Data.SqlDbType.VarChar, 50);
cmd.Parameter["#Email"].Value = strEmail;
cmd.Parameter["#Passwd"].Value = strPwd;
cmd.Connection.Open();
using (var reader = cmd.ExecuteReader()) {
if (reader.Read()) {
result = Convert.ToInt32(reader["ShopperID"]);
}
}
}
return result;
}
First, it appears you close your connection, however you don't have an explicit open connection (unless you didn't include that line by mistake) which on a postback your query won't produce results since the connection is closed after you run it the first time. Second, confirm you don't have your code in a !Page.IsPostBack, which could also cause it not to appear. Finally you can do all that you are trying to do using one datareader instead of opening up two datareaders with this:
string strEmail = txtEmail.Text.ToLower();
string strPwd = txtPwd.Text.Trim();
string conString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT ShopperID, Name FROM Shopper WHERE Email = #Email AND Passwrd = #Passwrd", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Email", strEmail);
cmd.Parameters.AddWithValue("#user_name", strPwd);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows)
{
if(dr["ShopperID"].ToString() != Session["ShopperID"].ToString())
{
Response.Redirect("~/default.aspx");
}
else if (dr["ShopperID"].ToString() == Session["ShopperID"].ToString())
{
lblWelcome.Text = "Welcome " + dr["Name"].ToString();
}
else
{
lblMsg.Text = "Incorrect email or password";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}
}
con.Close();
}
}
This also addresses the SQL injection by using Type-Safe SQL Parameters, which was outlined as an issue in other comments.
I am trying to use a SqlDataReader to run queries on two tables where the 1st column in the Selection table is a foreign key referencing to the Items table, and then display the results in labels, but I keep getting the error:
Invalid attempt to read when no data is present.
Here is my code:
public partial class Read : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(#"data source = localhost; integrated security = true; database = dev_handin1");
SqlCommand cmd = null;
SqlDataReader rdr = null;
string sqlsel = "SELECT MainItemId FROM Selection";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetInfo();
}
}
private void GetInfo() {
try
{
cmd = new SqlCommand(sqlsel, conn);
conn.Open();
sqlsel = "SELECT * FROM Items WHERE ItemId = MyMainItem";
rdr = cmd.ExecuteReader();
var MyMainItem = rdr[0];
while (rdr.Read())
{
LabelCategory1.Text = rdr[1].ToString();
LabelHeadline1.Text = rdr[2].ToString();
LabelText1.Text = rdr[3].ToString();
LabelJoke1.Text = rdr[4].ToString();
}
}
catch (Exception ex)
{
LabelMessage1.Text = ex.Message;
}
finally
{
rdr.Close();
conn.Close();
}
}
}
}
I'm pretty new at this so please bear with me.
Hello im trying to create login form that saves your UserID to Userdetails class. But for some reason log in doesnt work.I think there is somewhere mistake in if (login.Read()) in validate_login but im not sure. If i put messagebox to if (r.valid) it doesnt work so thats why i think somewhere in if (login.Read()) . Any form of help would be welcome. Thanks.
I have tryed rewriting mysql query, ( cmd.CommandText = )
If i remove if (r != null) i get this error System.NullReferenceException: 'Object reference not set to an instance of an object.'
r was null.
private void db_connection()
{
try
{
conn = "..connection string..";
connect = new MySqlConnection(conn);
connect.Open();
}
catch (MySqlException e)
{
throw;
}
}
private LoginUser validate_login(string user, string pass)
{
db_connection();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "Select * from table2 where username=#user and password=#pass";
cmd.Parameters.AddWithValue("#user", user);
cmd.Parameters.AddWithValue("#pass", pass);
cmd.Connection = connect;
LoginUser usr = null;
MySqlDataReader login = cmd.ExecuteReader();
if (login.Read())
{
usr = new LoginUser();
usr.UserID = login["UserID"].ToString();
usr.valid = true;
}
return usr;
}
private void button1_Click(object sender, EventArgs e)
{
{
string user = username.Text;
string pass = password.Text;
var r = validate_login(user, pass);
if (r != null)
{
if (r.valid)
{
MessageBox.Show("validated");
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader reader = cmd.ExecuteReader();
Console.WriteLine(String.Format("{0}", r.UserID));
UserDetails.m_gnUserId = Convert.ToInt32(r.UserID);
}
}
}
}
validate_login should work as follows:validate_login should run query and search for username and password that is same as textbox #user and #pass.
button1_Click should start that validate_login
Note:I know i need to hash passwords in my db and i currently dont. Its my next step after this.
Your problem is probably because you return null, if there were no such record in database.
LoginUser usr = null;
If that's not what you want, you should return new LoginUser with field valid set to false.
var usr = new LoginUser(){ valid = false };
And don't forget to check for that in your button's event handler.
I created an app like a quiz.. When I try to show the score in the labels I got this error:
An unhandled exception of type 'System.Data.SQLite.SQLiteException' occurred in System.Data.SQLite.dll Additional information: database is locked database is locked
I know which is the problem, but I don`t know how to solve it.
The problem is for sure in the Menu Form (the 'highest parent'). And I know that because the app updates the database from the Quiz form, but when it comes back and read the database so that I can change the labels I got that error. ONLY IF THE update_score() is both in Meniu() (or even in Meniu_Load() ) and after the .ShowDialog()
update_score() -reads database and change labels
Conclusion: I can not show in labels the highest scores both times: when I open the app and when comes back from the quizz form..So, I have to put in comment the update_score after the showdialog (the user won`t know the score when it comes back) or in the Meniu /Meniu_Load (it does not show at the beginning).
How can I solve it?
The Menu code:
public partial class Meniu : Form
{
SQLiteConnection con;
public bool con_opened = false; // tin minte daca am deschis conexiunea
public int bs_lit=0, bs_info = 0;
public Meniu()
{
//this.StartPosition = FormStartPosition.CenterScreen;
InitializeComponent();
con_opened=false;
update_score();
}
private void Meniu_Load(object sender, EventArgs e)
{
//con_opened=false;
//update_score();
}
public void db1_read()
{
if (con_opened == false)
{
con = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");//Version=3;
con_opened = true;
con.Open();
}
string sql = "select * from bestscore WHERE materie LIKE 'literatura'";
SQLiteCommand command = new SQLiteCommand(sql, con);
SQLiteDataReader reader = command.ExecuteReader();
reader.Read();
bs_lit = Int32.Parse(reader[1].ToString());
command.Dispose();
sql = "select * from bestscore WHERE materie LIKE 'informatica'";
SQLiteCommand cmd = new SQLiteCommand(sql, con);
SQLiteDataReader rdr = cmd.ExecuteReader();
rdr.Read();
bs_info = Int32.Parse(rdr[1].ToString());
cmd.Dispose();
con.Close();
con_opened = false;
}
private void update_score()
{
db1_read();
lbl_bs_info.Text = bs_info.ToString();
lbl_bs_lit.Text = bs_lit.ToString();
}
private void btn_literatura_testare_Click(object sender, EventArgs e)
{
testare flit = new testare();
this.Hide();
flit.reveal = false;
flit.materie = "literatura";
flit.ShowDialog();
update_score(); // if the function is here and in Meniu()
// or Meniu_load()I receive the error
// if it`s just one of them
//it works just fine
if (flit.reveal == true)
this.Show();
else
Application.Exit();
}
}
Thank you!
I found the answer: I didn`t Dispose the readers. Now it works.
public void db1_read()
{
if (con_opened == false)
{
con = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");//Version=3;
con_opened = true;
con.Open();
}
string sql = "select * from bestscore WHERE materie LIKE 'literatura'";
SQLiteCommand command = new SQLiteCommand(sql, con);
SQLiteDataReader reader = command.ExecuteReader();
reader.Read();
bs_lit = Int32.Parse(reader[1].ToString());
command.Dispose();
reader.Dispose();
sql = "select * from bestscore WHERE materie LIKE 'informatica'";
SQLiteCommand cmd = new SQLiteCommand(sql, con);
SQLiteDataReader rdr = cmd.ExecuteReader();
rdr.Read();
bs_info = Int32.Parse(rdr[1].ToString());
cmd.Dispose();
rdr.Dispose();
con.Close();
con_opened = false;
}
I am trying to create login operation.
How can I use another column's data by using a username and password query to my db.
In my db, there is a another column(personnel_type_id) and I want to create a session with username and password but also the personnel_type_id data.
How can I use personel_type_id data without using another parameter in my code?
protected void btnGiris_Click(object sender, EventArgs e)
{
string sorgu = "Select * from Personnels where VS_personnel_username = #kullaniciAdi AND VS_personnel_password= #sifre ";
SqlCommand cmd = new SqlCommand(sorgu, cnn);
cmd.Parameters.AddWithValue("#kullaniciAdi", txtKullaniciAdi.Text);
cmd.Parameters.AddWithValue("#sifre", txtSifre.Text);
cnn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Session.Timeout = 300;
Session.Add("kullaniciAdi", dr["VS_personnel_username"].ToString());
Response.Redirect(Request.RawUrl);
}
else
{
lblSonuc.Text = "Kullanıcı girişi sağlanamadı";
}
cnn.Close();
}
Should be something like:
protected void btnGiris_Click(object sender, EventArgs e)
{
string sorgu = "Select * from Personnels where VS_personnel_username = #kullaniciAdi AND VS_personnel_password= #sifre ";
SqlCommand cmd = new SqlCommand(sorgu, cnn);
cmd.Parameters.AddWithValue("#kullaniciAdi", txtKullaniciAdi.Text);
cmd.Parameters.AddWithValue("#sifre", txtSifre.Text);
cnn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Session.Timeout = 300;
Session.Add("kullaniciAdi", dr["VS_personnel_username"].ToString());
Session.Add("your_user_id_parameter", dr["personnel_type_id"].ToString());
Response.Redirect(Request.RawUrl);
}
else
{
lblSonuc.Text = "Kullanıcı girişi sağlanamadı";
}
cnn.Close();
}
If you don't want/can/need to store that "personnel_type_id" as a session variable you have to implement some kind of lookup in the database each time you need it.