I have been working on a software which uses database which is shared with multiple PCs. The project is all about to store missing baggage information. We have given a facility to copy the newly inserted record into the master DB.
Now what here happens is when multiple users are trying to update the db at the same time single item get stored for multiple time in the global DB.
So I have tried to use TableLock using serializable but I got nothing here.
Edit
query = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;BEGIN TRANSACTION;";
insertdata(query); //using cmd.ExecuteNonQuery();
query = "select * from Goods WITH (TABLOCKX)" ;
DataSet dsGoods = getdata(query, "config");//Function to get the data
updateitem();
query = "COMMIT TRANSACTION";
insertdata(query);//using cmd.ExecuteNonQuery();
And the updateitem() is as follow
public static void updateitem()
{
string query = "select * from config where param='lastsync'";
DataSet ds = dataaccess.getdata(query, "config");
query = "select isonlive,associateid,itemid,founddate,regdate,status,foundbyname,categoryid,subcatid,item,model,color,foundwhere,returnedtoname,showonline,officeid,isdeleted,(select username from [user] where userid=registeredby) as reguser,(select username from [user] where userid=returnby) as returnedby,notes,returneddate from item ";
String updatedDate =ds.Tables[0].Rows[0]["value"].ToString();
if (updatedDate != "")
{
query = "select isonlive,associateid,itemid,founddate,regdate,foundbyname,status,categoryid,subcatid,item,model,color,foundwhere,returnedtoname,officeid,showonline,isdeleted,(select username from [user] where userid=registeredby) as reguser,(select username from [user] where userid=returnby) as returnedby,notes,returneddate from item where updateat >= #updateat";
}
System.Data.SqlClient.SqlCommand cmd = new SqlCommand(query);
if (updatedDate != "")
{
cmd.Parameters.AddWithValue("#updateat",DateTime.ParseExact(updatedDate,"dd-MM-yyyy HH:mm:ss",null,System.Globalization.DateTimeStyles.None));
}
DataRow dr;
ds = dataaccess.getdata(cmd, "item");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
try
{
int status = 0;
dr = ds.Tables[0].Rows[i];
if (dr["status"].ToString() == "Transferred")
{
status = 2;
}
else if (dr["status"].ToString() != "Received")
{
status = 1;
}
DateTime regdate = Convert.ToDateTime(dr["regdate"]);
DateTime founddate = Convert.ToDateTime(dr["founddate"]);
//returndatetime = String.Format("MMM dd yyyy H:mm:ss", returndate);
if (dr["showonline"].ToString() == "False")
{
status = 1;
}
if (dr["isdeleted"].ToString() == "true")
{
insertdata("delete from goods where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "'");
continue;
}
if (dr["isonlive"].ToString() == "true")
{
query = "update goods set Status='" + status + "',officeid='" + dr["officeID"] + "', notes='" + dr["notes"].ToString().Replace("'", "''") + "',ReturnedTo='" + dr["returnedtoname"].ToString().Replace("'", "''") + "',founddate=#founddate,ReturnedDate=#returndate,ReturnedBy='" + dr["returnedby"].ToString().Replace("'", "''") +
"',Model='" + dr["model"].ToString().Replace("'", "''") + "',ColorID='" + dr["color"].ToString().Replace("'", "''") + "',FoundWhere='" + dr["foundwhere"].ToString().Replace("'", "''") + "',MainCat='" + dr["categoryid"] + "',SubCat='" + dr["subcatid"] + "',ItemID='" + dr["item"] + "' where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "'";
}
else
{
query = "select * from goods where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "' and MainCat='" + dr["categoryid"] + "' and SubCat='" + dr["subcatid"] + "' and ItemID='" + dr["item"] + "'";
DataSet dsItems = getdata(query, "config");
if(dsItems.Tables[0].Rows.Count==0)
{
query = "insert into goods (AssociateID,ID,DateReg,Status,MainCat,SubCat,ItemID,Model,ColorID,FoundWhere,RegBy,FoundBy,ReturnedTo,ReturnedDate,ReturnedBy,Notes,IP,founddate,officeid) values('" + dr["associateid"] + "','" + dr["itemid"] + "',#regdate,'" + status + "'," +
"'" + dr["categoryid"] + "','" + dr["subcatid"] + "','" + dr["item"] + "','" + dr["model"].ToString().Replace("'", "''") + "','" + dr["color"].ToString().Replace("'", "''") + "'," +
"'" + dr["foundwhere"].ToString().Replace("'", "''") + "','" + dr["reguser"].ToString().Replace("'", "''") + "','" + dr["reguser"].ToString().Replace("'", "''") + "','" + dr["returnedtoname"].ToString().Replace("'", "''") + "',#returndate," +
"'" + dr["returnedby"].ToString().Replace("'", "''") + "','" + dr["notes"].ToString().Replace("'", "''") + "','',#founddate,'" + dr["officeID"].ToString() + "')";
}
}
SqlCommand sce = new SqlCommand(query);
if (dr["returneddate"].ToString() != "")
{
sce.Parameters.AddWithValue("#returndate", Convert.ToDateTime(dr["returneddate"]));
}
else
{
sce.Parameters.Add("#returndate", SqlDbType.DateTime).Value = DBNull.Value;
}
sce.Parameters.AddWithValue("#regdate", regdate);
sce.Parameters.AddWithValue("#founddate", founddate);
insertdata(sce);
query = "update item set isonlive = 'true',updateat=#updateDate where itemid = '" + dr["itemid"] + "'";
sce = new SqlCommand(query);
sce.Parameters.AddWithValue("#updateDate", DateTime.Now);
dataaccess.insertdata(sce);
}
catch (Exception ex)
{
App.writelog(ex.Message + "\n" + ex.StackTrace);
}
}
}
P.S.: I want it to be done though ASP.Net.
Related
string TJOBCODE1 = ddlJobCode.SelectedItem.Value;
string abc = ddlJobCode.SelectedItem.ToString();
string TJob_Name = abc.Substring(0, abc.IndexOf('['));
string TRo_Name = abc.Substring(abc.LastIndexOf('[') + 1);
TRo_Name = TRo_Name.Replace("]", "");
string TJOBCODE = TJOBCODE1;
SqlCommand fsql = new SqlCommand("SELECT COUNT(*) AS REC FROM [MTS_TV_RO_TC_FINAL] where JOB_CODE='" + TJOBCODE + "' AND AGENCY_CODE in( select agency_code FROM " + tmptvrlbktbl + ")", Global.con1);
SqlDataAdapter Fda1 = new SqlDataAdapter(fsql);
DataTable Fdt1 = new DataTable();
Fda1.Fill(Fdt1);
int DD = Convert.ToInt32(Fdt1.Rows[0].ItemArray.GetValue(0).ToString());
if (DD == 0)
{
string INSQURY = " insert into [MTS_TV_RO_TC_FINAL] ([DATE],[CAPTION_NAME],[IST],[DURATION],[AMOUNT],[CRID],[JOB_CODE],[AGENCY_CODE],[STATUS],[TBAND_IN],[TBAND_OUT],[DATE_FROM],[DATE_TO],[CREATE_DATE],[USER_NAME],[REMARKS],[Ro_Name],[Job_Name]) SELECT [DATE],[CAPTION],[IST],[DURATION],[AMOUNT],[CRID],'" + TJOBCODE + "',[Agency_code],[STAT],[TBAND_IN],[TBAND_OUT],'" + COMP_FROM + "','" + COMP_TO + "',GETDATE() AS DT,'" + Global.uname + "' ,[REMARKS],'" + TRo_Name + "','" + TJob_Name + "' FROM " + tmptvrlbktbl + " ORDER BY DATE";
SqlCommand cmd1 = new SqlCommand(INSQURY, Global.con1);
cmd1.ExecuteNonQuery();
Alert.show1("Data Saved Successfully", this);
}
else
{
Alert.show1("Data Already Saved", this);
return;
}
The code was perfectly fine, there was an issue with the excel sheet. i changed the query to parametrized and changed the excel sheet as well and it worked.
Change insQury to
string INSQURY = " insert into [MTS_TV_RO_TC_FINAL] ([DATE],[CAPTION_NAME],[IST],[DURATION],[AMOUNT],[CRID],[JOB_CODE],[AGENCY_CODE],[STATUS],[TBAND_IN],[TBAND_OUT],[DATE_FROM],[DATE_TO],[CREATE_DATE],[USER_NAME],[REMARKS],[Ro_Name],[Job_Name]) SELECT [DATE],[CAPTION],[IST],[DURATION],[AMOUNT],[CRID],'" + TJOBCODE + "',[Agency_code],[STAT],[TBAND_IN],[TBAND_OUT],COMP_FROM, COMP_TO,GETDATE() AS DT,'" + Global.uname + "' ,[REMARKS],'" + TRo_Name + "','" + TJob_Name + "' FROM " + tmptvrlbktbl + " ORDER BY DATE";
If COMP_FROM and COMP_TO are dates already you don't need to surround them with single quotation marks.
So I have been given administration on a website that is basically a company conference room reservation system, it is connected to an access database for room details and vacancies. Problem is, AppScan source is showing a risk of XSS and SQL Injection. This is the complete function in where it is indicating the occurrence of these errors.
protected void btnReserve_Click(object sender, System.EventArgs e)
{
string start_slot, end_slot, event_desc, room_id, emp_nid;
string[] date;
start_slot = ddlStart.SelectedValue;
end_slot = ddlEnd.SelectedValue;
event_desc = txtEventDesc.Text;
room_id = Server.HtmlEncode(Request.QueryString["room_id"]);
emp_nid = Regex.Replace(Request.ServerVariables["LOGON_USER"], #"^.*\\(.*)$", "$1").ToUpper();
date = Request.QueryString["date"].Split('/');
DateTime dt = new DateTime(Convert.ToInt32(date[2]),Convert.ToInt32(date[0]),Convert.ToInt32(date[1]));
string sCmdCheckConflict = #"
SELECT count(*)
FROM t_msc_event
WHERE (event_date = #" +DateTime.Parse(Request.QueryString["date"]).ToString() + #"# )
AND (room_id = " + room_id + #") AND
(
(" + start_slot + #" BETWEEN start_slot AND end_slot) OR
(" + end_slot + #" BETWEEN start_slot AND end_slot) OR
(start_slot BETWEEN " + start_slot + #" AND " + end_slot + #") OR
(end_slot BETWEEN " + start_slot + #" AND " + end_slot + "))";
OleDbCommand cmdConflictCounter = new OleDbCommand(sCmdCheckConflict, cn);
int n;
int event_id;
try
{
cn.Open();
n = (int) cmdConflictCounter.ExecuteScalar();
string Msg;
if (n>0)
{
Msg = "<script language=javascript>alert('Chosen time is not possible due to a conflict.');</script>";
}
else
{
#region MS Access related region
OleDbCommand cmdgetMaxId = new OleDbCommand("select max(event_id) from t_msc_event", cn);
string sCmdInsert;
OleDbCommand cmdInsertEvent = null;
event_id = 0; bool success = false; int trials = 0;
do
{
try
{
event_id = (int) cmdgetMaxId.ExecuteScalar() + 1;
}
catch
{
event_id = 0;
}
sCmdInsert = #"
insert into t_msc_event (event_id,
emp_nid, event_desc, event_date,
start_slot, end_slot, room_id
) values (" + event_id + #",
'" + Server.HtmlEncode(emp_nid) + "', '" + Server.HtmlEncode(event_desc.Replace("'", "''")) + "', #" + dt.ToShortDateString() + "#, " +
start_slot + ", " + end_slot + ", " + room_id + ")";
cmdInsertEvent = new OleDbCommand(sCmdInsert, cn);
cmdInsertEvent.ExecuteNonQuery();
success = true;
} while ((!success) && (trials <=5));
OleDbDataAdapter daGetSlots = new OleDbDataAdapter("select slot_id, left(slot_desc,5) as slot_start, right(slot_desc,5) as slot_end from t_msc_slot order by slot_id", cn);
DataTable dtSlotInfo = new DataTable();
daGetSlots.Fill(dtSlotInfo);
OleDbCommand cmdGetRoolTitle = new OleDbCommand("select room_title from t_msc_room where room_id=" + Server.HtmlEncode(room_id), cn);
string room_title = (string) cmdGetRoolTitle.ExecuteScalar();
string msg = "Dear " + emp_nid +
",<br><br>This is to confirm your reservation of " +
room_title +
" on " + dt.ToShortDateString() + " from " +
dtSlotInfo.Rows[Convert.ToInt32(start_slot)]["slot_start"].ToString() + " to " +
dtSlotInfo.Rows[Convert.ToInt32(end_slot)]["slot_end"].ToString() + "." +
"<br><br>In case you want to cancel, go to " +
"<a href='" + Regex.Replace(Request.Url.ToString(), #"^(.*)/.*\.aspx\?*.*$", "$1/MyReservations.aspx") + "'>" +
"MS Conference Rooms Reservation -> MyReservatios</a>";
#endregion
string subject = "MS Conference Room Reservation Confirmation [id=" + event_id + "]";
try
{
SendEmail(emp_nid, subject, msg);
Msg = "<script language=javascript>alert('Room successfully reserved. You should receive a confirmation email shortly.'); if (opener) {opener.__doPostBack('" + Request.QueryString["btnGetScheduleID"].Replace("_","$") + "', '');} window.close();</script>";
}
catch
{
Msg = "<script language=javascript>alert('Room successfully reserved.'); if (opener) {opener.__doPostBack('" + Request.QueryString["btnGetScheduleID"].Replace("_","$") + "', '');} window.close();</script>";
}
}
Response.Write(Msg);
}
catch (Exception x)
{
Response.Write(x.ToString());
string Msg;
Msg = "<script language=javascript>alert('Error: " + x.ToString() + "');</script>";
Response.Write(Msg);
}
finally
{
cn.Close();
}
}
Sorry for having to show you the whole function as I have really no idea what I need to do here, this isn't my app.
what I did do is 1) Enable Request Validation in ASP.NET 2) encode user input by using Server.HtmlEncode(); but it is still reporting the same thing. Note that both start_slot and end_slot are DDLs so I thought I wouldn't need to encode/check them before sending. Would you please help me in modifying this code to neglect harmful user input? Thank you loads.
The correct way to use parameterized SQL query is
string commandText = "UPDATE ProductDetails
SET ProductQuantity = #quantity WHERE ProductId = #productId";
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.AddWithValue("#productId", "P123");
command.Parameters.AddWithValue("#quantity", 10);
You can safely replace the "P123" with user provided input now.
I get the Syntax Error in UPDATE statement whenever I try to update information in my Access database. I have tried moving things around and adding commas or taking away commas. I am stuck, any suggestions as to what I could do? The error is attached to the second cmd.ExecuteNonQuery(); at the bottom.
if (txtdateId.Text != "")
{
if (txtdateId.IsEnabled == true)
{
cmd.CommandText =
"insert into tbEmp(DateofService, AssociateName, DeviceType, DeviceModel, Serial, Issue, Part1, Part2, Part3, RepairedBy, Campus) Values('" +
txtdateId.Text + "','" + txtEmpName.Text + "','" + txtContact.Text + "','" + txttype.Text +
"','" + txtserial.Text + "','" + txtAddress.Text + "','" + txtpart1.Text + "','" + txtpart2.Text +
"','" + txtpart3.Text + "','" + txtrepaired.Text + "','" + txtcampus.Text + "')";
cmd.ExecuteNonQuery();
BindGrid();
MessageBox.Show("Device Added Successfully");
ClearAll();
}
else
{
cmd.CommandText = "update tbEmp set DateofService = ,'" + txtdateId.Text + ",AssociateName = '" + txtEmpName.Text + ",DeviceType = '" + txtContact.Text + ",DeviceModel = '" + txttype.Text + ",Serial = '" + txtserial.Text + ",Issue = '" + txtAddress.Text + ",Part1 = '" + txtpart1.Text + ",Part2 = '" + txtpart2.Text + ",Part3 = '" + txtpart3.Text + ",RepairedBy = '" + txtrepaired.Text + "where Campus = '" + txtcampus.Text;
cmd.ExecuteNonQuery();
BindGrid();
MessageBox.Show("Device updated");
ClearAll();
}
}
You missed several ' in you statement also you have one extra ' after DateofService. Your statement should be like this:
cmd.CommandText = "update tbEmp set DateofService = '" + txtdateId.Text + "',AssociateName = '" + txtEmpName.Text + "' , ...
Also I strongly recommend you to use parameterized queries to avoid SQL Injection like this:
In SQL:
cmd.CommandText = "update tbEmp set DateofService = #txtdateId ,...";
cmd.Parameters.AddWithValue("txtdateId",txtdateId.Text);
And for Access and OleDB:
cmd.CommandText = "update tbEmp set DateofService = ? , ....";
cmd.Parameters.AddWithValue("DateofService ",txtdateId.Text);
Although specify the type directly and use the Value property is more better than AddWithValue. Check this: Can we stop using AddWithValue() already?
This is solution of your problem, but I'll prefer you do some add validation for SQL injection. First take the textbox value validate it then pass it query.
cmd.CommandText = "update tbEmp set DateofService = '" + txtdateId.Text + "' ,AssociateName = '" + txtEmpName.Text + "' ,DeviceType = '" + txtContact.Text + "',DeviceModel = '" + txttype.Text + "',Serial = '" + txtserial.Text + "',Issue = '" + txtAddress.Text + "',Part1 = '" + txtpart1.Text + "',Part2 = '" + txtpart2.Text + "' ,Part3 = '" + txtpart3.Text + "' ,RepairedBy = '" + txtrepaired.Text + "' where Campus = '" + txtcampus.Text + "'";
Hi first here is my code:
OleDbConnection conexao = new OleDbConnection();
try
{
OleDbCommand comando = new OleDbCommand();
comando.Connection = conexao;
string query2 = "update Utilizador set Nome='" + nomeTextBox.Text + "' , DiaNascimento='" + diaNascimentoComboBox.Text + "' ,MesNascimento='" + mesNascimentoComboBox.Text + "' ,AnoNascimento='" + anoNascimentoComboBox.Text + "' , Altura='" + alturaTextBox.Text + "' , Sexo='" + sexoComboBox.Text + "' , Peso='" + pesoTextBox.Text + "' , CodGenetica='" + codGeneticaTextBox1.Text + "', Login='" + loginTextBox.Text + "' , Password='" + passwordTextBox.Text + "' where CodUtilizador= " + codutilizaor.Text + "";
string id = codutilizaor.Text;
string command = "update Utilizador set Nome= '" + nomeTextBox.Text + "' , Login= " + loginTextBox.Text + " where CodUtilizador= '" + id + "' ";
conexao.Open();
conexao.Close();
this.Close();
}
catch (Exception ex)
{
MessageBox.Show("Ya" + ex);
}
I want to update all the fields but it doesn´t work, i saw many solutions here and in youtube but none solved my problem, and I tried very hard from myself to do it but it still doesn ´t work , please may you help mesolving this problem?
you missing a quote on query2:
...where CodUtilizador= '" + codutilizaor.Text + "";
you also have to execute the query with ExecuteNonQuery(); :
...
comando.Text=command;
comando.ExecuteNonQuery();
Last but not least consider using parameters, because you are exposed to SQL injection.
e.g:
string command = "update Utilizador set Nome= #None , Login=#Login where CodUtilizador=#ID";
comando.Parameters.AddWithValue("#Nome", nomeTextBox.Text);
comando.Parameters.AddWithValue("#Login", loginTextBox.Text);
comando.Parameters.AddWithValue("#ID", id);
Looks like you forgot to add the query to the command. You also forgot to actually execute it.
OleDbConnection conexao = new OleDbConnection("Add your connection string here");
try
{
string query = "update Utilizador set Nome='" + nomeTextBox.Text + "' , DiaNascimento='" + diaNascimentoComboBox.Text + "' ,MesNascimento='" + mesNascimentoComboBox.Text + "' ,AnoNascimento='" + anoNascimentoComboBox.Text + "' , Altura='" + alturaTextBox.Text + "' , Sexo='" + sexoComboBox.Text + "' , Peso='" + pesoTextBox.Text + "' , CodGenetica='" + codGeneticaTextBox1.Text + "', Login='" + loginTextBox.Text + "' , Password='" + passwordTextBox.Text + "' where CodUtilizador='" + codutilizaor.Text + "'";
conexao.Open();
var commandOne = new OleDbCommand(query, conexao);
commandOne.ExecuteNonQuery()
conexao.Close();
this.Close();
}
catch (Exception ex)
{
MessageBox.Show("Ya" + ex);
}
What's wrong with this SQL UPDATE statement?
try
{
int ageValue = Int32.Parse(age.Text);
string updateQuery = "Update \nMyTable \nSet \nFName = '" + fname.Text.ToString() + "',\nLName = '" + lname.Text.ToString() + "',\nAge = " + ageValue + ",\nCome = '" + from.Text.ToString() + "',\nTo = '" + to.Text.ToString() + "' Where Age=" + ageValue + ";";
MessageBox.Show(updateQuery);
OleDbConnection con = new OleDbConnection("provider=Microsoft.JET.OLEDB.4.0; Data Source = Database5.mdb");
OleDbCommand com = new OleDbCommand(updateQuery, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
}
I received that error
Syntax error in Update statement
What is wrong in that SQL Update?
Tools:
Microsoft Access 2003
Microsoft Visual Studio 2010 C#
Please help and thanks in advance
Try getting rid of the \n junk.
string updateQuery = "Update MyTable Set FName = '" + fname.Text.ToString() + "',LName = '" + lname.Text.ToString() + "',Age = " + ageValue + ",Come = '" + from.Text.ToString() + "',To = '" + to.Text.ToString() + "' Where Age=" + ageValue;
Output the result of the concatination and try to run it. If that doesn't work, post the result of the concatination here and someone should be able to help. Without knowing the result of the concatination, it's difficult to know what's wrong.
Try changing the query like this (removing \ns and the final ;)
string updateQuery = "Update MyTable Set FName = '" + fname.Text.ToString() +
"', LName = '" + lname.Text.ToString() + "', Age = " + ageValue +
", Come = '" + from.Text.ToString() + "', To = '" + to.Text.ToString() +
"' Where Age=" + ageValue;
I would suggest you put the Sql Profiler on and trace your update query because it is easy to read the concatenated query string
Hello you can try with this code
StringBuilder stringBuilder = new StringBuilder() ;
stringBuilder.Append("Update MyTable Set FName = ") ;
stringBuilder.Append(fname.Text.ToString()) ;
stringBuilder.Append(",\nLName = ") ;
stringBuilder.Append(lname.Text.ToString()) ;
stringBuilder.Append(",\nAge = ") ;
stringBuilder.Append(ageValue) ;
stringBuilder.Append(",\nCome = ") ;
stringBuilder.Append(from.Text.ToString()) ;
stringBuilder.Append(",\nTo = ") ;
stringBuilder.Append(to.Text.ToString()) ;
stringBuilder.Append(" Where Age=") ;
stringBuilder.Append(ageValue) ;
stringBuilder.Append(";") ;
var result = stringBuilder.ToString();
This is how I write my inline SQL in C sharp:
string strSQL = "";
strSQL += " Update MyTable Set ";
strSQL += " FName = '" + fname.Text.ToString() + "' ";
strSQL += " ,LName = '" + lname.Text.ToString() + "' ";
strSQL += " ,Age = '" + ageValue + "' ";
strSQL += " ,Come = '" + from.Text.ToString() + "' ";
strSQL += " ,To = '" + to.Text.ToString() + "' ";
strSQL += " Where Age = '" + ageValue + "' ";
Easy to read and works fine.
You can also add this just below your query before you connent to your database:
Response.Write(strSQL);
return;
this will show you whats being posted to the server and makes it a little easier to find errors.