Cannot insert information in SQL database - c#

I'm developing a website for a parent association, for a school. My system has two reserved areas, which parents and also teachers/school members has access. These two areas, are the backoffice and the FrontOffice.
I can begin a new session with a dad or mother username, and their respective password, and then in frontoffice i've a new page where, it was supossed, a new meal be sucessfully done reserved and in result of that a new row should be inserted in a SQL database table.
It happens that for this, i've next code:
protected void ReserveMeal (object sender, EventArgs e)
{
string tipoRefeicao=string.Empty;
DateTime DataSelecionada = Convert.ToDateTime(BasicDatePicker1.Text.ToString());
bool refeicaoFinalizada = false; //Refeicao nao é consumida no imediato
try
{
//ligar a base de dados e realizar nova conexao
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Vitor\Documents\Visual Studio 2015\Projects\Educational\Educational\App_Data\SchoolPASS.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
string selectUser = "SELECT count (*) from EEAluno where NomeUtilizadorEE='" + newName + "'";
string res = Convert.ToString(selectUser);
SqlCommand com = new SqlCommand(selectUser, con);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
con.Close();
if (temp == 1)
{
con.Open();
string verificaPassword = "select Password from EEAluno where NomeUtilizadorEE='" + newName + "'";
SqlCommand passCommand = new SqlCommand(verificaPassword, con);
string password = passCommand.ExecuteScalar().ToString();
if (password == Session["Pass"].ToString())//Nao testado
{
//Inserir refeicao numa tabela nova
SqlCommand insert = new SqlCommand("INSERT INTO TabelaRefeicoesEncomendadas (NomePessoa,TipoRefeicao,Data, Finalizada) VALUES (#NomePessoa,#TipoRefeicao,#Data,#Finalizada)", con);
//insert.Parameters.Add("#Id", 1);
insert.Parameters.AddWithValue("#NomePessoa", newName);
insert.Parameters.AddWithValue("#TipoRefeicao", tipoRefeicao);
insert.Parameters.AddWithValue("#Data", DataSelecionada);
insert.Parameters.AddWithValue("#Finalizada", refeicaoFinalizada);//escreve falso na DB
}
}
}
catch (Exception exc)
{
}
}
Doing a carefully analysis, in code, you could observe that i'm, trying to check if the autenticated user is the correct user.
So if we have many users inside a DB table, only one, only for example "X" (i assumed that "X" has sucessfully logged into system), is the active user, in a determined computer, and only "X" could reserve a meal for the respective children.
Resume: I've thinked in a algorithm to check the user session, and then insert a reserved meal, into a database table. I did not succeed. I think it can not verify correctly the sessions. Two errors exist.
Every time that i try to create the meal (when method is called), the username is incremented, so if username is "X" username becomes "XX"
The information about meal is not inserted into SQL database.
Could you help me!

Based on the code snipped provided, you are not executing the sql command for the insert.
Something like this should work, after you are done setting up the parameters:
insert.ExecuteNonQuery();

Related

How can I make it so only the logged in user view his own grade?

This is the student info table where the student info comes from //This is the login code for the user and it get the user log in info from the studentinfo table.
private void btnlogin_Click(object sender, EventArgs e)
{
i = 0;
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from stdinfotable WHERE Username='" + textuser.Text + "' and Password= '" + textpass.Text + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter dta = new MySqlDataAdapter(cmd);
dta.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if(i==0)
{
MessageBox.Show("Error");
}
else
{
this.Hide();
StudentPage f = new StudentPage();
f.Show();
MySqlDataAdapter data = new MySqlDataAdapter("ViewAllGrades", con);
data.SelectCommand.CommandType = CommandType.StoredProcedure;
DataTable dtTable = new DataTable();
data.Fill(dtTable);
dtTable.Select("Last_Name");
f.stdGrade.DataSource = dtTable;
f.stdGrade.Columns[0].Visible = false;
}
con.Close();
}
This is the ViewlAllGrades stored procedure where the grade info is returned from
CREATE DEFINER=`root`#`localhost` PROCEDURE `ViewAllGrades`()
BEGIN
SELECT *
FROM Grades;
END
I am trying to make it so only the logged in user can view his own grade rather than viewing every user grade. So I am wondering should I try to do within the stored procedure or in Visual Studio and how would I achieve such thing? Also my primary keys which are ID are from both table are auto incremented so I cant not necessarily use those
Right now your stored procedure is selecting all of the grades. First thing to do would be to parameterize the query, accepting the user as the input, and using the WHERE clause to find only the grades for that student. Without seeing your tables, I cannot tell you exactly what this would look like, but as an example: SELECT * FROM Grades WHERE StudentId = #StudentId;
The second thing you need to figure out is how to get the current user's student id and then pass it to the stored procedure. Again, without seeing your tables, I can hardly guess. It appears you already have the username of the current user. Are you able to run a query to find the studentId from the username? If so, then you first need to run that procedure with username as the parameter to get the studentId.
A third concern is with your first query. Since it has not been parameterized, it is susceptible to SQL injection attacks. This poses a MAJOR security risk. If someone maliciously enters a username or password, they can escape the SQL you intended to run and drop all of your tables.
Hopefully that helps!

Inserting string data into database in c#

I am working on sharp nlp where i am extracting all the adjective now i need to store this in database and i have successfully added this to database but the problem is with me that i want to store adjective separately to database how can i store the adjective separately or for example we have string and we want to store each word separately into database and we have only one column how can we do this? .please help me out
here is my code.
private void button2_Click(object sender, EventArgs e)
{
try
{
string cleaned = richTextBox1.Text.Trim();
string st = "INSERT INTO TABLE1(adjective)VALUES('" + cleaned + "')";
SqlConnection con = new SqlConnection("Data Source=ZAZIKHAN\\SQLEXPRESS;Initial Catalog=mis;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(st, con);
if (cmd.ExecuteNonQuery() == 1)
{
MessageBox.Show(" succesfully added");
}
else
{
MessageBox.Show("Sorry we couldnt add the Values Please try Again");
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
now i have this data to be stored which is in richtextbox.
local/JJ daily/JJ n/price/rate/JJ human/JJ possible/JJ correct/JJ exact/JJ local/JJ
local/JJ daily/JJ n/price/rate/JJ human/JJ possible/JJ correct/JJ exact/JJ local/JJ
dry/JJ nd/JJ
new/JJ full/JJ OK/JJ final/JJ white/JJ OK/JJ howajaa/JJ smajder/JJR agaa/JJ nasambd/JJ Live/JJ
final/JJ
great/JJ s3/JJ final/JJ
resistant/JJ Z1/JJ white/JJ new/JJ black/JJ amaa.Kintact/JJ possible/JJ main/JJ mobile/JJ rapak/JJ mil/JJ
important/JJ mil/JJ smart/JJ
35-h/JJ OK/JJ full/JJ
Want/JJ complete/JJ white/JJ same/JJ
available/JJ perfect/JJ
interested/JJ
First off, the lines
string cleaned = richTextBox1.Text.Trim();
string st = "INSERT INTO TABLE1(adjective)VALUES('" + cleaned + "')";
create a massive security hole known as SQL Injection.
In order to store the adjectives separately in a properly denormalized database, you would have a parent table where e.g. the original sentence is stored, and a child table with a 1:N relationship to the parent where you store one row per adjective plus the appropriate ID of the parent row.
Since you only have one column available, you can use any convenient format to store the array of adjectives in a single column. You could serialize that array (to Binary, XML, JSON, etc) and store it, or since you know you have a limited input character set, you could even store it as a comma separated list.
You can prefix your words with some characters to indicate whether they are verb , noun , adjective and tehn insert those value in database
eg
N_JonSkeet - Noun
V_Solve - Verb
A_Highest - Adjective
string cleaned = extractAdjective(richTextBox1.Text.Trim());
string st = "INSERT INTO TABLE1(word) VALUES(#Word)";
SqlConnection con = new SqlConnection("Data Source=ZAZIKHAN\\SQLEXPRESS;Initial Catalog=mis;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(st, con);
SqlParameter param = new SqlParameter("#Word", SqlDbType.NChar);
param.Value = "A_"+cleaned;
cmd.Parameters.Add(param);
I would separate the string into a list and then iterate over the list and insert into your DB:
var vals = "local/JJ daily/JJ n/price/rate/JJ human/JJ possible/JJ...";
var results = vals.Replace(" ", "")
.Replace("/JJ", "|")
.Replace("/", "|")
.Split('|')
.Distinct();
while(var result in results)
{
// DO insert here
}

Retrieving user password from DB

I have a table that has a list of user names and passwords and I want to match the the user name and password the user enter with the one saved in the DB. The code I am using only retrieves the login information of the first record in the users table, how can I change that so the code would work for all user.
I am a beginners at VS and I am trying to learn the basics so later on I will be implementing more complex login page with encryption.. Thank you
private void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
cn.ConnectionString = "Server=;Database=;User Id=naljalid;Password=";
cmd.Connection = cn;
string username = tbxUserName.Text;
cmd.CommandText = "SELECT UserPassword FROM tblLoginProject WHERE UserName=username";
// open a connection to DB
cn.Open();
//read the table
dr = cmd.ExecuteReader();
//read a record from te data reader
dr.Read();
// compare the passwords
if (tbxPassword.Text == dr.GetString(0))
{
MessageBox.Show("Hello");
}
else
{
MessageBox.Show("Login failed, please re-enter your password");
}
}
The key to this is the SQL query, specifically the WHERE clause:
SELECT UserPassword FROM tblLoginProject
This query will return all the passwords from the database. But you want to retrieve the password of only one user, so you need to implement a WHERE clause
SELECT UserPassword FROM tblLoginProject WHERE UserName = #username
This query will retrieve the password for only a certain user where the value of the field UserName equals the value passed in the parameter #username. So now we need to make sure to pass that value. You can't just include it in the SQL query like you're doing right now. We do it like this:
cmd.Paramateres.AddWithValue("#username", username);
This should work fine, but for best practices you should check for both username and password at the same time:
SELECT count(*) FROM tblLoginProject WHERE UserName = #username AND UserPassword = #password
Then of course we pass both values:
cmd.Paramateres.AddWithValue("#username", username);
cmd.Paramateres.AddWithValue("#password", password);
This will return 0 if no users are found with that combination of username and password (invalid login), or more than 0 if such a user was found (valid login).
Next stop you should research hashing passwords. After that would be salting these hashes. Good luck!
Change the query a tidge to this:
cmd.CommandText = "SELECT UserPassword FROM tblLoginProject WHERE UserName = #username";
and then set that parameter value:
cmd.Parameters.AddWithValue("#username", tbxUserName.Text);
That will get you the row for the user you're looking for. Now on to a few more recommendations. The ADO.NET classes implement the IDispoable interface. That interface identifies that the class uses some unmanaged resources. You want to make sure those get disposed. Consider the following rewrite of your current code:
using (SqlConnection cn = new SqlConnection("Server=;Database=;User Id=naljalid;Password="))
using (SqlCommand cmd = new SqlCommand("SELECT UserName FROM tblLoginProject WHERE UserName = #username AND Password = #password", cn))
{
cn.Open();
cmd.Parameters.AddWithValue("#username", tbxUserName.Text);
cmd.Parameters.AddWithValue("#password", tbxPassword.Text);
var result = cmd.ExecuteScalar() as string;
if (string.IsNullOrEmpty(result))
{
// user was not found
}
else
{
// user was found
}
}
It leverages the using statement to ensure that the objects get disposed.

COM object that has been separated from its underlying RCW cannot be used?

Setting aside the salt and hash debate. And Please reply only if you know the answer.
I am trying to create a method where a user enters their credentials with date and times are recorded automatically when logging in and out.
I have two problems
Problem 1 -
I have created a simple method just for logging in and out. When I included the date and time code I noted that these where recorded and stored for all users. I currently have two users. So if one user logins date and time are recorded and stamp for the other user.
Problem 2 -
The second problem is as the subject headers says I get a error message when the Update command parameter is in the same method as with Select.
If anyone could help me I would be grateful with both of the problems. Hopefully It is only a minor issue? If omitting date and time then I will be grateful if someone could help me on multi login function.
Access 2003 ~ Two tables. Table 1 - Named LoginTable Table 2 - Named LoginLogTable
LoginTable
FieldName DataType
UserName Text
Password Text
LoginLogTable
FieldName DataType
UserNameID Text
UserName Text
LoggedIn Date/Time
LoggedInTime Date/Time
private void btnLogin_Click(object sender, EventArgs e)
{
using (var command = myCon.CreateCommand())
{
command.CommandText = "select UserName, Password from LoginTable where WHERE STRCOMP(UserName, #UserName,0) = 0 AND STRCOMP(Password, #Password,0)=0";
command.Parameters.AddWithValue("UserName", (txtUserName.Text));
command.Parameters.AddWithValue("Password", (txtPassword.Text));
myCon.Open();
var reader = command.ExecuteReader();
{
if (reader.HasRows)
{
MessageBox.Show("Login Successful");
Form2 frm = new Form2();
frm.Show();
while (reader.Read())
{
txtUserName.Text = reader["UserName"].ToString();
txtPassword.Text = reader["Password"].ToString();
}
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myCon;
cmd.CommandText = "UPDATE [LoginLogTable] SET [LoggedInDate] = ?, [LoggedInTime] = ?";
cmd.Parameters.AddWithValue("#LoggedInDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedInTime", DateTime.Now.ToString("HH:mm"));
cmd.ExecuteNonQuery();
myCon.Close();
}
else MessageBox.Show("Login Falied");
}
}
myCon.Close();
myCon.Close();
}
You don't have any condition in your update query, so it will update all records in the table. Add a condition to only update a single record. I don't know what you have in your table, but something like this:
cmd.CommandText = "UPDATE [LoginLogTable] SET [LoggedInDate] = ?, [LoggedInTime] = ? where UserName = ?";
cmd.Parameters.AddWithValue("LoggedInDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("LoggedInTime", DateTime.Now.ToString("HH:mm"));
cmd.Parameters.AddWithValue("UserName", txtUserName.Text);
You should close and dispose the first data reader and command before executing the second command.
I suppose you need a UserName column in your LoginLogTable and update table something like this
UPDATE [LoginLogTable] SET [LoggedInDate] = ?, [LoggedInTime] = ? WHERE UserName = 'YourUserName'.
And the second, I believe you no need a Reader here. You can use ExecuteScalar instead Reader. The second command can not run because a Reader has open state.

Exception while inserting values in to SQL table through C#

HI i had manullay created textbox's and then used it for creating a new user. I am using SQL SERVER 2005 for backend and Visual Server 2008 for front..
I have this LoginAccount table which stores details of the new user created. When i Click the button(in which i have written code to create a new user through SQL insert),
string strConnection = ConfigurationManager.ConnectionStrings"FHDLConnectionString"].ToString();
SqlConnection sqlConnection = new SqlConnection(strConnection);
string username = TextBox1.Text;
string password = TextBox2.Text;
string confirmpass = TextBox3.Text;
string SQLQuery = "Select username From LoginAccount where '" + username + "'";
string SQLQuery1 = "Insert into LoginAccount values ('" + username + "','" + password + "')";
SqlCommand command = new SqlCommand(SQLQuery, sqlConnection);
SqlCommand command1 = new SqlCommand(SQLQuery1, sqlConnection);
sqlConnection.Open();
string CheckUsername = "";
if (password.ToString() != confirmpass.ToString())
{
Literal1.Text = " Password's does not match ";
}
else
{
try
{
CheckUsername = command.ExecuteScalar().ToString();
}
catch (Exception er)
{
Literal1.Text = " Username already exists ";
}
string insertQuery = "";
try
{
insertQuery = command1.ExecuteScalar().ToString();
Server.Transfer("Login_Created.aspx");
}
catch (Exception er)
{
Literal1.Text = " Could not create the user, Please retry with some other option ";
}
}
sqlConnection.Close();
I am getting these exception's
An expression of non-boolean type specified in a context where a condition is expected, near 'fhdl'
This error i got at the first catch
and
Object reference not set to an instance of an object.
This for at the last catch.
But the main thing is i am able to insert the username and password into the LoginAccount table!!!!!!! i.e. when i saw the table contents i could see the new user created in that table.
The other thing is This code executed perfectly once before but not now :(
Please could anyone tell me where am i going wrong?
I am new to C# with SQl ...
1 - ExecuteScalar() means that there's a return value. The insert doesn't have a return value. Use ExecuteNonQuery instead.
2 - Also, for the insert statement, specify the fields you're inserting into. Without specifying the fields, it's trying to insert into the first two columns of the table, which may not be username and password.
insert into LoginAccount(UserName, Password) values ....
3 - your select statement is incorrect.
select from LoginAccount where UserName='... You're missing the field name.
Three things:
Your first query doesn't do what you want it to. It resolves to:
Select username From LoginAccount where 'username'
You want to check the username against the database.
This code leaves you wide open to SQL Injection attacks. See this article for how to prevent them in C#.
On a similar note, you really don't want to store passwords in the clear in your database either.

Categories

Resources