Prevent over booking ticket by using busno and date - c#

Am working on small project and am new to coding, i want the system to be a booking system whenever specific bus is booked for specific date then that bus will be specific to that date. for example Bus12 is booked to be used on 21 of Aug then if by mistake the admin tries to book the same bus for something else prevent that booking based on checking the date and busno. am simply using web forms, below is my database table and behind code.please help me am not getting any error nothing is stored in my database table when i refresh it.i want if the entered date and Busno is same as the one in table then prevent booking.
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["MyDatabase1ConnectionString"].ConnectionString;
tbDate.Text = Calendar1.SelectedDate.ToShortDateString();
using (SqlConnection con = new SqlConnection(cs))
{
string check = "SELECT BusNo, Date FROM Ticket WHERE (BusNo = #busno) AND(Date = #NewDate))";
SqlCommand cmd = new SqlCommand(check, con);
cmd.Parameters.AddWithValue("#busno", tbBusno.Text);
cmd.Parameters.AddWithValue("#NewDate", DateTime.Parse(tbDate.Text));
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
if (rdr.HasRows)
{
Response.Write("double booking");
}
else
{
string insertQuery = "INSERT INTO Ticket (BusNo, Date, Time,Bickup,DropOff,Fare) VALUES (#busno ,#date , #time , #bickup , #dropoff ,#fare )";
SqlCommand cmd2 = new SqlCommand(insertQuery, con);
cmd2.Parameters.AddWithValue("#busno", tbBusno.Text);
cmd2.Parameters.AddWithValue("#date", DateTime.Parse(tbDate.Text));
cmd2.Parameters.AddWithValue("#time", tbTime.Text);
cmd2.Parameters.AddWithValue("#dropoff", tbDrop.Text);
cmd2.Parameters.AddWithValue("#bickup", tbBickup.Text);
cmd2.Parameters.AddWithValue("#fare", int.Parse(tbfare.Text));
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
}
}
}
}
}

Can try removing the while (rdr.Read()) portion ?
So your code will be
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
Response.Write("double booking");
}
else
{
string insertQuery = "INSERT INTO Ticket (BusNo, Date, Time,Bickup,DropOff,Fare) VALUES (#busno ,#date , #time , #bickup , #dropoff ,#fare )";
SqlCommand cmd2 = new SqlCommand(insertQuery, con);
cmd2.Parameters.AddWithValue("#busno", tbBusno.Text);
cmd2.Parameters.AddWithValue("#date", DateTime.Parse(tbDate.Text));
cmd2.Parameters.AddWithValue("#time", tbTime.Text);
cmd2.Parameters.AddWithValue("#dropoff", tbDrop.Text);
cmd2.Parameters.AddWithValue("#bickup", tbBickup.Text);
cmd2.Parameters.AddWithValue("#fare", int.Parse(tbfare.Text));
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
}
}

Related

Asp.Net SQL Update Statement

I have an Asp.net application on my page the user requests for a user to be removed. This then populates my 'Admin_TaskList' db.
An administrator then goes in the secure area of the site and enters the users name and clicks a button. Upon the confirmation, the user is then deleted from my 'Users' db (already got this working) but I want my 'Admin_TaskList' db 'Status' column to change from 'To Do' to 'Completed'.
As I sad I have the delete bit working but I am struggling updating my other table.
Snippet of code I have tried
conn.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE FROM Admin_TaskList SET Status = 'Complete' WHERE Description = 'Remove User' AND Name = #Name", conn);
cmd2.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd2 = cmd2.ExecuteReader();
conn.Close();
Full code
public void btnRemoveConfirmYes_Click(object sender, EventArgs e)
{
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = #Name", conn);
cmd1.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd1 = cmd1.ExecuteReader();
conn.Close();
conn.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE FROM Admin_TaskList SET Status = 'Complete' WHERE Description = 'Remove User' AND Name = #Name", conn);
cmd2.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd2 = cmd2.ExecuteReader();
conn.Close();
txtRemoveUser.Text = "";
Response.Redirect("/AdminSide/TaskList.aspx");
}
Instead of using a SqlDataReader to update a value use SqlCommand.ExecuteNonQuery:
int updated = cmd2.ExecuteNonQuery();
Remember that you need to use ExecuteNonQuery on commands that modify your data like Delete, Insert or Update.
MSDN:
You can use the ExecuteNonQuery to perform catalog operations (for
example, querying the structure of a database or creating database
objects such as tables), or to change the data in a database without
using a DataSet by executing UPDATE, INSERT, or DELETE statements.
The complete method:
int deleted, updated;
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
using (var conn = new SqlConnection(connection))
{
conn.Open();
string delSql = "DELETE FROM Users WHERE Name = #Name";
using (var cmd = new SqlCommand(delSql, conn))
{
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtRemoveUser.Text;
deleted = cmd.ExecuteNonQuery();
}
string updSql = #"UPDATE Admin_TaskList
SET Status = 'Complete'
WHERE Description = 'Remove User'
AND Name = #Name";
using (var cmd = new SqlCommand(updSql, conn))
{
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtRemoveUser.Text;
updated = cmd.ExecuteNonQuery();
}
}

Assign SQL query result to session variable

I am trying to run a SQL query based on who's logged in which gets the Team_ID and assigns it to the session variable. I am having trouble assigning the result to the variable.
protected void ButtonLogin_Click(object sender, EventArgs e)
{
//check what user category was selected and login to appropriate page
if (DropDownListUserType.SelectedIndex == 1)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Team_User where Email = #username and Password_1 = #password", con);
cmd.Parameters.AddWithValue("#username", UserName.Text);
cmd.Parameters.AddWithValue("#password", Password.Text);
SqlCommand cmdID = new SqlCommand("select Team_ID from Team_User where Email = #username and Password_1 = #password", con);
cmdID.Parameters.AddWithValue("#username", UserName.Text);
cmdID.Parameters.AddWithValue("#password", Password.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
SqlDataReader reader = cmdID.ExecuteReader();
int Team_ID = reader.GetInt32(1);
Session["Team_ID"] = Team_ID;
Response.Redirect("AddPlayer.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
}
}
Your code doesn't make a whole lot of sense....
If you only want the Team_ID - why are you loading the whole row first, and then call the database again to get just the Team_ID???
I tried to simplify your code a good bit:
protected void ButtonLogin_Click(object sender, EventArgs e)
{
// check what user category was selected and login to appropriate page
if (DropDownListUserType.SelectedIndex == 1)
{
// define connection string and SQL query as strings
string connectionString = ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString;
string query = "SELECT Team_ID FROM dbo.Team_User WHERE Email = #username AND Password_1 = #password";
// set up SqlConnection and SqlCommand in "using" blocks
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// define and fill parameters - DO NOT use .AddWithValue!
cmd.Parameters.Add("#username", SqlDbType.VarChar, 100).Value = UserName.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar, 100).Value = Password.Text;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
// if we got back a result ....
if(result != null)
{
int teamID = Convert.ToInt32(result.ToString());
Session["Team_ID"] = teamID;
Response.Redirect("AddPlayer.aspx");
}
else
{
// if result is NULL, then the username+password
// were NOT found - do what needs to be done in that case here
}
}
}
}

How to Retrieve Date and time from SQL to datetimepicker in c#?

If I enter a value(already entered in DB) and click a button(Retrieve) in my windows form, I have to retrieve date and time to my datetimepicker1 from SQL(already entered values).
Please correct my code.
This is my code.
private void button9_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=NIFAL;Initial Catalog=LaundrySystem;Integrated Security=True;");
con.Open();
str = "select * from LaundrySystemTable where laundID='" + textBox1.Text.Trim() + "'";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
string temp1 = reader["entryDate"].ToString();
DateTime dt1 = DateTime.Parse(temp1);
dateTimePicker1.Value = dt1.ToString("MM:dd:yyyy");
reader.Close();
con.Close();
}
}
NEVER use such an SQL that is open to SQL inkjection attacks, use parameters instead:
using (SqlConnection con = new SqlConnection("Data Source=NIFAL;Initial Catalog=LaundrySystem;Integrated Security=True;"))
{
string sql = "select entryDate from LaundrySystemTable where laundID=#id";
var cmd = new SqlCommand( sql, con );
cmd.Parameters.AddWithValue( "#id", textBox1.Text.Trim() ); // if its type is not string, then do the conversion here
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
dateTimePicker1.Value = (DateTime?)reader["entryDate"];
}
con.Close();
}

Check for duplicate entries before insertion (C#.net)

I have a textbox form that students fill out about their general information such as first and last name, city, state, etc. Sometimes a student can't remember if they filled out the form before and it will lead to duplicate entries in the ms-access database. Ideally I would like the code to first search the ms-access database for a matching first name AND last name on the same record before insertion. If there's a record that matches on both the entered first and last name fields then a script would run and say something like, "A matching record already exists, would you like to continue?" Clicking "Yes" would enter the record into a new row, clicking "Cancel" would not enter it into the database at all.
I started this code but I'm not sure if it's the right direction, any guidance would be appreciated, thanks.
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = #FName AND [LName] = #LName", con))
{
con.Open();
using (OleDbDataReader myReader = com.ExecuteReader())
{
(This is where I am stuck)
}
}
Below is the current code for the submit button.
protected void btnSubmit_Click(object sender, EventArgs e)
{
{
//Preforms insert statement on click to allow additions to the database
DateTime CurrentDate;
CurrentDate = DateTime.Now;
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\sites\schoolinfo\students_dev\App_Data\Studentdb.mdb";
string cmdstr = "INSERT into StudentList(FName, LName, BDay, Gender, School, Grade, Address, APT, City, State, Zip, Email, Phone, CellPhone, ParentFName, ParentLName, ParentEmail) values(#FName, #LName, #BDay, #Gender, #School, #Grade, #Address, #APT, #City, #State, #Zip, #Email, #Phone, #CellPhone, #ParentFName, #ParentLName, #ParentEmail)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
{
con.Open();
}
//The following fields are added from the student information to the corresponding database fields
com.Parameters.AddWithValue("#FName", txtFirstName.Text);
com.Parameters.AddWithValue("#LName", txtLastName.Text);
com.Parameters.AddWithValue("#BDay", txtBirthDate.Text);
com.Parameters.AddWithValue("#Gender", ddlGender.Text);
com.Parameters.AddWithValue("#School", txtSchool.Text);
com.Parameters.AddWithValue("#Grade", txtGrade.Text);
//The following fields are added from the contact information to the corresponding database fields
com.Parameters.AddWithValue("#Address", txtAddress.Text);
com.Parameters.AddWithValue("#APT", txtApt.Text);
com.Parameters.AddWithValue("#City", txtCity.Text);
com.Parameters.AddWithValue("#State", ddlState.Text);
com.Parameters.AddWithValue("#Zip", txtZip.Text);
com.Parameters.AddWithValue("#Email", txtEmail.Text);
com.Parameters.AddWithValue("#Phone", txtPhone.Text);
com.Parameters.AddWithValue("#CellPhone", txtCellPhone.Text);
com.Parameters.AddWithValue("#ParentFName", txtParentFName.Text);
com.Parameters.AddWithValue("#ParentLName", txtParentLName.Text);
com.Parameters.AddWithValue("#ParentEmail", txtParentEmail.Text);
com.ExecuteNonQuery();
con.Close();
//End database connection
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Student has been successfully added!')", true);
}
}
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = #FName AND [LName] = #LName", con))
{
// Add your #Fname and #LName parameters here
com.Parameters.AddWithValue("#FName", firstName);
com.Parameters.AddWithValue("#LName", lastName);
con.Open();
using (OleDbDataReader myReader = com.ExecuteReader())
{
myReader.Read();
int count = myReader.GetInt32(0);
// return count > 0 or whatever to indicate that it exists
}
}
couple of things:
you can set in your table the first name and last name as 1 primary key (yes it possible in ms-access). this way you will NEVER get any duplicate records
count(*) is not the best practice with databases.. but since you are dealing with ms-access
using (OleDbDataReader myReader = com.ExecuteReader())
{
// reads the first and only column count(*) and convert it to a number
if (Convert.ToInt16(myReader[0]) > 0)
{
// an entry already exists
}
}
You should use ExecuteScalar when the return value of your query is only a single row with a single column. Of course the OleDbCommand that has parameters placeholders in its command text needs to have also a corresponding Parameters collection
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = #FName AND [LName] = #LName", con))
{
con.Open();
com.Parameters.AddWithValue("#FName", txtFirstName.Text);
com.Parameters.AddWithValue("#LName", txtLastName.Text);
int count = Convert.ToInt32(com.ExecuteScalar());
if(count == 0)
{
... record doesn't exist
}
else
{
... you have got count records
}
}
However let me say that this logic is rather weak. What happen if two students have the same First and Last name? What happen if someone mistype the name?. I think that you should require something more unique. Like a SSN or another ID provided by your school. (A Student Number or something alike)
if (txtYear.Text != "")
{
cmd = new SqlCommand("Select YearName from Year where YearName='" + txtYear.Text + "'", ConnOpen());
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
int i = ds.Tables[0].Rows.Count;
if (i > 0)
{
MessageBox.Show("Duplicate Values are not valid!!!");
}
else
{
if (Classes.ClassDatabaseConnection.UserMessage("Are you srue you want to Add this Year!!!", "Confirm Updation") == true)
{
string insert = "insert into Year(YearName) values('" + txtYear.Text + "')";
int result = sqlrep.ExecuteNonQuery(insert);
if (result > 0)
{
System.Windows.Forms.MessageBox.Show("Year Added Successfully.", "Information", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
}
}
dataLoad();
}
}

How to insert date time in database?

I'am making a time attendance system and I don't know how to store datetime in database. I really need some help with my system if anyone has any code for time attendance please share your Code a little help would do thanks..
Here is my Code:
con = newSqlConnection(#"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
dt = new DataTable();
cmd = new SqlCommand(#"SELECT EmpID FROM data WHERE EmpID='" + Code.Text + "'", con);
con.Open();
sdr = cmd.ExecuteReader();
int count = 0;
while (sdr.Read())
{
count = count + 1;
}
con.Close();
if (count == 1)
{
con.Open();
DateTime dtn = DateTime.Now;
dtn = Convert.ToDateTime(DateTime.Now.ToString("hh:mm"));
string query = #"INSERT INTO Time (TimeIn) Values ('" + dtn + "')";
cmdd = new SqlCommand(query, con);
sdr = cmdd.ExecuteReader();
sdr.Read();
dataGridView.DataSource = databaseDataSet.Time ;
con.Close();
MessageBox.Show("Verify Ok");
}
else
{
MessageBox.Show("Please Try Again");
}
Do not use ExecuteReader() but ExecuteNonQuery(); add query parameters, do not modify query text, technically it could be something like that:
...
if (count == 1) {
...
DateTime dtn = DateTime.Now;
string query =
#"insert into Time (
TimeIn)
values (
#TimeIn)"; // <- query parameter instead of query text modification
using (var query = new SqlCommand(query, con)) {
// bind query parameter with its actual value
query.Parameters.AddWithValue("#TimeIn", dtn);
// Just execute query, no reader
query.ExecuteNonQuery();
}
...
However, table Time as it appears in the question looks very strange, hardly does it contain TimeIn field only.

Categories