Need algorithm For room reservation - asp.net

I need a room reservation algorithm that room should not be book before its date once a room is booked should not be book on that similar date. I am using sql server and was using status active or booked but its not working.
public void res(DateTime? arrivalDate,DateTime? departureDate)
{
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = (#"Server=DESKTOP-8JJO9NL\SQLEXPRESS;Database=HMS;Trusted_Connection=True");
myConn.Open();
SqlCommand com = new SqlCommand();
com.Connection = myConn;
string sql = "";
sql = "select count(*) from Roomsdata where Room#=#roomnum and Status='Active and arrivaldate >= #arrivalDate and departure <= #departureDate'";
com.CommandText = sql;
com.Parameters.Clear();
com.Parameters.AddWithValue("#roomnum", Roomnum);
com.Parameters.AddWithValue("#arrivalDate", arrivalDate);
com.Parameters.AddWithValue("#departureDate", departureDate);
int numRecords = (int)com.ExecuteScalar();
if (numRecords == 1)
{
SqlConnection myConn2 = new SqlConnection();
myConn2.ConnectionString = (#"Server=DESKTOP-8JJO9NL\SQLEXPRESS;Database=HMS;Trusted_Connection=True");
myConn2.Open();
SqlCommand myCmd = new SqlCommand("update Roomsdata set [customername]=#customername ,[contact] =#contact ,[arrivaldate]=#arrivaldate,[departure]=#departure ,[Status]='Booked' ,[stayingdays]=DATEDIFF(day,arrivaldate,departure) ,[Total amount]=DATEDIFF(day,arrivaldate,departure)*1278 FROM [HMS].[dbo].[Roomsdata] where Room#=#roomnum1", myConn2);
myCmd.Parameters.AddWithValue("roomnum1", Roomnum);
myCmd.Parameters.AddWithValue("#customername", Costumername);
myCmd.Parameters.AddWithValue("#contact", Contact);
myCmd.Parameters.AddWithValue("#arrivaldate", Arrivaldate);
myCmd.Parameters.AddWithValue("#departure", Departuredate);
myCmd.ExecuteNonQuery();
myConn2.Close();
}
else
{
throw new Exception("Room is Already Booked");
}

Related

How to use SQL Data Reader to check quantity in database?

I want to check quantity in the tblProducts with the quantity selected by the user. If the user selects more than in tblProducts, there will be a pop up message and the quantity will not added. If there is available quantity in tblProducts, the user can add the quantity. Do I need to put SP_UpdateCart in both if statement?
if (e.CommandName == "DoPlus")//Check quantity here
{
string PID = (e.CommandArgument.ToString());
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SP_getUserCartItem", con)
{
CommandType = CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("#PID", PID);
cmd.Parameters.AddWithValue("#UserID", UserID);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
int myQty = Convert.ToInt32(dr["Qty"].ToString());
int PQuantity = Convert.ToInt32(dr["PQuantity"].ToString());
if (dt.Rows.Count > 0)
{
if (myQty < PQuantity)
{
Int32 updateQty = Convert.ToInt32(dt.Rows[0]["Qty"].ToString());
SqlCommand myCmd = new SqlCommand("SP_UpdateCart", con)
{
CommandType = CommandType.StoredProcedure
};
myCmd.Parameters.AddWithValue("#Quantity", updateQty + 1);
myCmd.Parameters.AddWithValue("#CartPID", PID);
myCmd.Parameters.AddWithValue("#UserID", UserID);
con.Open();
Int64 CartID = Convert.ToInt64(myCmd.ExecuteScalar());
con.Close();
BindProductCart();
BindCartNumber();
}
else if (myQty > PQuantity)//check quantity between tblCart and
tblProducts
{
Response.Write("<script>alert('Please choose quantity less than
stated!');</script>");
Int32 updateQty = Convert.ToInt32(dt.Rows[0]["Qty"].ToString());
SqlCommand myCmd = new SqlCommand("SP_UpdateCart", con)
{
CommandType = CommandType.StoredProcedure
};
myCmd.Parameters.AddWithValue("#Quantity", updateQty);
myCmd.Parameters.AddWithValue("#CartPID", PID);
myCmd.Parameters.AddWithValue("#UserID", UserID);
con.Open();
Int64 CartID = Convert.ToInt64(myCmd.ExecuteScalar());
con.Close();
BindProductCart();
BindCartNumber();
}
}
}
dr.Close();
}con.Close();
}
}
}

How to store a select query result ( one result ) to a variable using executescalar() ? ( ASP.NET )

i have to store a select query result in a variable .i'm new in asp.net . i used executescalar but it doesn't work. i try many times but i failed here my last try :
using (SqlConnection sqlConnection = new SqlConnection())
{
var connetionString = ConfigurationManager.ConnectionStrings["connections"].ToString();
sqlConnection.ConnectionString = connetionString;
string sql = "Select sum((prime_comptant+10)*0.12) from mvt_garantie_quittance where numero_quittance='" + numQuittance + "'";
SqlDataAdapter adapter = new SqlDataAdapter(sql, sqlConnection);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
string result = dataset.Tables[0].ToString();
}
Can you fix the code to me? i have to store the result in a variable
string sql = "Select sum((prime_comptant+10)*0.12) from mvt_garantie_quittance where numero_quittance='" + numQuittance + "'";
var connetionString = ConfigurationManager.ConnectionStrings["connections"].ToString();
string result = null;
using (SqlConnection conn = new SqlConnection(connetionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
result = cmd.ExecuteScalar().ToString();
}

Conversion failed

I want to add some parameter to a table and I get this error in the Visual Studio 2013. I'm having trouble with Date & Time. My date & time datatypes used in SQL Server 2008 R2 are Date and Time(7). I get this error
Conversion failed when converting date and/or time from character string
What is my mistake?
My code:
string strquery = "select count(*) from SaloonGeneralReservation where SaloonReservationDate=#SaloonReservationDate";
SqlConnection connection2 = DBConnection.getConnection();
connection2.Open();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection2;
cmd2.CommandText = strquery;
cmd2.Parameters.Add("#SaloonReservationDate", txt1_date.Text);
int intRowCount = (int) cmd2.ExecuteScalar();
txt1_date.Text = intRowCount.ToString();
connection2.Close();
if (intRowCount == 1)
{
Messages myMsg = new Messages(); // ایجاد نمونه از کلاس
myMsg.CreateMessageAlert("سالن در این تاریخ رزرو شده است . لطفا تاریخ دیگری وارد نمایید.");
txt1_date.Text = "";
}
else
{
string strQuery = "INSERT INTO [WeedingSalonGeneralRes](Date,Time,Fruit,Drink,Desert,MainFood,Salad,TableFlower,SaloonLighting,Saloondesign,SloonCrew,Pastry,GiftCard,customer_id)" + "VALUES(#Date,#Time,#Fruit,#Drink,#Desert,#MainFood,#Salad,#TableFlower,#SaloonLighting,#Saloondesign,#SloonCrew,#Pastry,#GiftCard,#customer_id)";
SqlConnection connection = DBConnection.getConnection();
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = strQuery;
string cis = Session["customerID"].ToString();
cmd.Parameters.Add("#Date", txt1_date.Text);
cmd.Parameters.Add("#Time", txt2_time.Text);
cmd.Parameters.Add("#Fruit", fruit);
cmd.Parameters.Add("#Drink", drink);
cmd.Parameters.Add("#Desert", desert);
cmd.Parameters.Add("#MainFood", mainfood);
cmd.Parameters.Add("#Salad", salad);
cmd.Parameters.Add("#TableFlower", tableflower);
cmd.Parameters.Add("#SaloonLighting", saloonlighting);
cmd.Parameters.Add("#Saloondesign", saloondesing);
cmd.Parameters.Add("#SloonCrew", salooncrew);
cmd.Parameters.Add("#Pastry", pastry);
cmd.Parameters.Add("#GiftCard", giftcard);
cmd.Parameters.Add("#customer_id", cis);
cmd.ExecuteNonQuery();
connection.Close();
Response.Redirect("ReservationSucces.aspx");
}
Your TIME(7) needs to be HH:MM:SS at a minimum, and HH:MM:SS.NNNNNNN maximum. So, add :00 on your string for your TIME to make the conversion work. The DATE should be fine as long as you are using YYYY-MM-DD. You WILL get this error if you are using YYYY-DD-MM.

Fetching Data from database as per details

string date = ddlShowDates.SelectedValue.ToString();
cmd = new SqlCommand("SELECT tbl_Shows.ShowTime FROM tbl_Shows INNER JOIN tbl_MovieTimings ON tbl_Shows.ShowId = tbl_MovieTimings.ShowId WHERE tbl_MovieTimings.Date='" + date + "'", con);
I want to display show time in dropdownlist as per date is selected.
Always use sql-parameters instead of string concatenation to prevent sql-injection.
I guess you have a second DropDownList which should be filled from the first:
DateTime date = DateTime.Parse(ddlShowDates.SelectedValue);
string sql = #"SELECT tbl_Shows.ShowTime
FROM tbl_Shows
INNER JOIN tbl_MovieTimings
ON tbl_Shows.ShowId = tbl_MovieTimings.ShowId
WHERE tbl_MovieTimings.Date=#Date";
using(var con = new SqlConnection("ConnectionString"))
using(var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#Date", SqlDbType.Date).Value = date;
con.Open();
using(var rd = cmd.ExecuteReader())
{
while(rd.Read())
{
TimeSpan time = rd.GetTimeSpan(0);
timeDropDownList.Items.Add(time.ToString());// change format as desired in TimeSpan.ToString
}
}
}

Retrieving multiple rows from stored procedures

My stored procedure proc_search returns only the name on execution and I have been using the following code in ASP.NET to display the value...
SqlCommand cmd = new SqlCommand("proc_search", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#branch", SqlDbType.VarChar).Value = branchidtext.Text;
cmd.Parameters.Add("#Acct", SqlDbType.VarChar).Value = accountidtext.Text;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
nametext.Text = reader[0].ToString();
}
If I have a procedure which returns multiple columns and multiple rows like Name, Address, Age... How do I display it in the text boxes? Please help.
If you know exact order of data you can say
while (reader.Read())
{
nametext.Text = reader[0].ToString();
agetext.Text = reader[1].ToString();
addresstext.Text = reader[2].ToString();
}
etc... If you don't know the ordering than say
while (reader.Read())
{
nametext.Text = reader["Name"].ToString();
agetext.Text = reader["Age"].ToString();
addresstext.Text = reader["Address"].ToString();
}
Use this kind of method. This will retun dataset having multiple rows and cols
public DataSet GetDataSet()
{
SqlConnection conn = new SqlConnection(con);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "proc_search";
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds);
conn.Close();
return ds;
}

Resources