DatagridView boolean values update to database - c#

I'm having an issue when I update values from a datagridview row to the database. The issue is that I have designed the table in the DB with certain fields as "bit" data type to store boolean value flags.
When i assign the datatable to the datagridview the system aytomatically displays these certain fields as checkboxes, which suits me just fine.
But when I try to update these values back to the database the boolean values go bananas.....Here is my code...
int fragileChk = (Convert.ToBoolean(aRow.Cells[12].Value) ? 1 : 0);
int inflamChk = (Convert.ToBoolean(aRow.Cells[13].Value) ? 1 : 0);
int biologicalChk = (Convert.ToBoolean(aRow.Cells[15].Value) ? 1 : 0);
int emergencyChk = (Convert.ToBoolean(aRow.Cells[16].Value) ? 1 : 0);
int usedChk = (Convert.ToBoolean(aRow.Cells[25].Value) ? 1 : 0);
int offerChk = (Convert.ToBoolean(aRow.Cells[27].Value) ? 1 : 0);
string err;
string sqlComm = "UPDATE [70_warehouse_lines] SET " +
"ProductDescr = '" + aRow.Cells[5].Value.ToString() + "', " +
"PartNumber = '" + aRow.Cells[6].Value.ToString() + "', " +
"SerialNumber = '" + aRow.Cells[7].Value.ToString() + "', " +
"Quanitity = " + aRow.Cells[8].Value + ", " +
"Weight = " + aRow.Cells[10].Value + ", " +
"FragileFlag = " + fragileChk + ", " +
"InflammableFlag =" + inflamChk + ", " +
"BiologicalFlag = " + biologicalChk + ", " +
"EmergencyFlag = " + emergencyChk + ", " +
"SpecialInstructions = '" + aRow.Cells[17].Value.ToString() + "', " +
"ShopCostPrice = " + aRow.Cells[19].Value + ", " +
"RetailPrice1 = " + aRow.Cells[20].Value + ", " +
"RetailPrice2 = " + aRow.Cells[21].Value + ", " +
"WholePrice1 = " + aRow.Cells[22].Value + ", " +
"WholePrice2 = " + aRow.Cells[23].Value + ", " +
"CalculatedPrice = " + aRow.Cells[24].Value + ", " +
"UsedParts = " + usedChk + ", " +
"TimesProcessed = " + aRow.Cells[26].Value + ", " +
"OnOffer = " + offerChk + ", " +
"NotesPerPart = '" + aRow.Cells[28].Value.ToString() + "' " +
"WHERE WarehouseLineID = '" + aRow.Cells[0].Value.ToString() + "'";
myConn.ExecSqlCmd(sqlComm, out err);
any ideas ? (I have declared int values just for diagnostic purposes. Thank you in advance for your help.

Always use parameterised query, Using parameters helps prevent SQL Injection attacks when the database is used in conjunction with a program interface.
also you can specify datatype in parameterised query that will helpfull in your case.
string sqlComm = "UPDATE [70_warehouse_lines] SET " +
"ProductDescr = #ProductDescr " +
"PartNumber = #PartNumber " +
"SerialNumber = #SerialNumber " +
"Quanitity = #Quanitity" +
"Weight = #Weight" +
"FragileFlag = #FragileFlag" +
"InflammableFlag = #InflammableFlag" +
"BiologicalFlag = #BiologicalFlag" +
"EmergencyFlag = #EmergencyFlag" +
"SpecialInstructions = #SpecialInstructions " +
"ShopCostPrice = #ShopCostPrice" +
"RetailPrice1 = #RetailPrice1" +
"RetailPrice2 = #RetailPrice2 " +
"WholePrice1 = #WholePrice1 " +
"WholePrice2 = #WholePrice2 " +
"CalculatedPrice = #CalculatedPrice " +
"UsedParts = #UsedParts " +
"TimesProcessed = #TimesProcessed " +
"OnOffer = #OnOffer " +
"NotesPerPart = #NotesPerPart" +
"WHERE WarehouseLineID = #WarehouseLineID ";
MySqlCommand cmd = new MySqlCommand(sqlComm);
cmd.Parameters.Add("#FragileFlag", MySqlDbType.Bit).Value = (Convert.ToBoolean(aRow.Cells[12].Value) ? 1 : 0);
cmd.Parameters.Add("#InflammableFlag", MySqlDbType.Bit).Value=(Convert.ToBoolean(aRow.Cells[13].Value) ? 1 : 0);
cmd.Parameters.Add("#BiologicalFlag", MySqlDbType.Bit).Value=(Convert.ToBoolean(aRow.Cells[15].Value) ? 1 : 0);
cmd.Parameters.Add("#EmergencyFlag", MySqlDbType.Bit).Value = (Convert.ToBoolean(aRow.Cells[16].Value) ? 1 : 0);
....................................
....................................
....................................
and so on
cmd.ExecuteNonQuery();

Related

How to return IQueryable from an SQL expression?

I am getting the following error trying to query from my database using C#:
LINQ to Entities does not recognize the method 'MyProject.Models.DB.Department getDepartment()' method, and this method cannot be translated into a store expression.
In my controller I have:
var query = db.Activities.AsQueryable();
query = query.Where(x => rs.department.Contains(x.getDepartment().id));
In my model I have the following method which returns the correct Department for an Activity. I know the problem is that I am executing the query when I do the .First(), but I can't find a way to return this as a IQueryable result:
public partial class Activity
{
public Department getDepartment()
{
return db.Departments.SqlQuery( "" +
"SELECT * FROM " +
"[snt].[Departments] " +
"INNER JOIN( " +
"SELECT " +
"[Users].departments_id AS id " +
"FROM " +
"[snt].[Users], " +
"[snt].[People], " +
"[snt].[EventPerson], " +
"[snt].[EventPersonTask], " +
"[snt].[Tasks], " +
"[snt].[Events], " +
"[snt].[Activities] " +
"WHERE " +
"[snt].[Activities].id = {0} AND " +
"[snt].[Events].id = [snt].[Activities].events_id AND " +
"[snt].[EventPerson].events_id = [snt].[Events].id AND " +
"[snt].[EventPerson].people_id = [snt].[People].id AND " +
"[snt].[EventPersonTask].tasks_id = [snt].[Tasks].id AND " +
"[snt].[EventPersonTask].eventperson_id = [snt].[EventPerson].id AND " +
"[snt].[Tasks].name = 'owner' AND " +
"[snt].[Users].is_active = 1 AND " +
"[snt].[Users].people_id = [snt].[People].id" +
" ) AS x " +
"ON " +
"x.id = [Departments].id", this.id).First();
}
}

HttpClient put issue in Angular

I'm developing an Angular app with Web api.
I have created a service (sellerService) in which I can update some data in my database with HttpClient put.
Above works but it update all the data of my table, something like follows;
Before I update my seller:
After I update my seller:
My sellerService code:
updateSeller(user: string, nbsales: number, pVote: number, nVote: number, idUser: number): Observable<any> {
return this.http.put('http://localhost:50867/api/seller_user/', {
'username': user,
'nbSales': nbsales,
'positiveVote': pVote,
'negativeVote': nVote,
'idUser': idUser
});
}
My update query (DAO (c#)):
public static readonly string UPDATE = "update " + TABLE_NAME + " set "
+ COLUMN_USERNAME + " =#username"
+ ", " + COLUMN_NB_SALES + "=#nbSales"
+ ", " + COLUMN_POSITIVE_VOTE + "=#positiveVote"
+ ", " + COLUMN_NEGATIVE_VOTE + " =#negativeVote"
+ ", " + COLUMN_ID_USER + "=#idUser";
//Update a seller_user
public static bool Update(Seller_user todo)
{
bool state = false;
using (SqlConnection connection = DataBase.GetConnection())
{
connection.Open();
SqlCommand command = new SqlCommand(UPDATE, connection);
//command.Parameters.AddWithValue("#idSeller", todo.idSeller);
command.Parameters.AddWithValue("#username", todo.username);
command.Parameters.AddWithValue("#nbSales", todo.nbSales);
command.Parameters.AddWithValue("#positiveVote", todo.positiveVote);
command.Parameters.AddWithValue("#negativeVote", todo.negativeVote);
command.Parameters.AddWithValue("#idUser", todo.idUser);
state = command.ExecuteNonQuery() != 0;
}
return state;
}
Thanks in advance ;)
You missed where clause in SQL query. So it will update all records.
public static readonly string UPDATE = "update " + TABLE_NAME + " set "
+ COLUMN_USERNAME + " =#username"
+ ", " + COLUMN_NB_SALES + "=#nbSales"
+ ", " + COLUMN_POSITIVE_VOTE + "=#positiveVote"
+ ", " + COLUMN_NEGATIVE_VOTE + " =#negativeVote"
+ ", " + COLUMN_ID_USER + "=#idUser"
+ "WHERE " + COLUMN_ID_USER + "=" + "= #idUser";

How to populate treenode from SQL using C#

I inherited a project that is populating TreeNode from SQL. I want to add three columns but syntax checker doesn't like what I'm adding but appears consistent with examples in blogs.
TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString()); // current working code
TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString() + " - " + rdr["FieldType"].ToString() + " - " + rdr["PointsToFileNumber"].ToString() + " - " + rdr["FieldLength"].ToString()); //possible replacement code that works but I would have to parse it later
TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString(), rdr["FieldType"].ToString(), rdr["PointsToFileNumber"].ToString(), rdr["FieldLength"].ToString()); //bad syntax beginning at first comma
Method:
private void getFileManFields(TreeNode node)
{
node.Nodes.Clear();
String fileNumber = node.Tag.ToString();
String sta3n = cbRegionSites.SelectedItem.ToString().Substring(1, 3);
SqlConnection cdw = new SqlConnection(ConfigurationManager.ConnectionStrings["CDW"].ConnectionString);
cdw.Open();
//SqlCommand cmd = new SqlCommand("SELECT VistaFieldNumber,VistaFieldName,MultipleFileNumber FROM CDWWork.Dim.VistaField WHERE Sta3n=" + sta3n + " AND VistaFileNumber='" + fileNumber + "' ORDER BY CAST(VistaFieldNumber As NUMERIC(30,10))", cdw);
SqlCommand cmd = new SqlCommand("SELECT VistaFieldNumber,VistaFieldName,MultipleFileNumber,FieldType,PointsToFileNumber,FieldLength FROM CDWWork.Dim.VistaField WHERE Sta3n=" + sta3n + " AND VistaFileNumber='" + fileNumber + "' ORDER BY CAST(VistaFieldNumber As NUMERIC(30,10))", cdw);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString());
//TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString() + " - " + rdr["FieldType"].ToString() + " - " + rdr["PointsToFileNumber"].ToString() + " - " + rdr["FieldLength"].ToString());
TreeNode field = new TreeNode(rdr["VistaFieldNumber"].ToString() + " - " + rdr["VistaFieldName"].ToString(), rdr["FieldType"].ToString(), rdr["PointsToFileNumber"].ToString(), rdr["FieldLength"].ToString());
field.Tag = rdr["VistaFieldNumber"].ToString();
if (rdr["MultipleFileNumber"].ToString().Length > 0)
{
field.Tag = rdr["MultipleFileNumber"].ToString();
field.Nodes.Add("RemoveNode");
}
node.Nodes.Add(field);
}
rdr.Close();
rdr.Dispose();
cmd.Dispose();
cdw.Close();
cdw.Dispose();
}

header and footer in text file using c#

I am newbie to c# I want to have headers and footers when saving the text file which is generated on the data grid view.
when I run a sql query it should generate 3 column values as headers and 3 columns values as footers.
headers recordtype,cpcnumber,filesequence number;
footers record type,no of requests,total court fee,claim amount; I don't how to get these records when i run this command as headers/footers. Any help would be greatly appreciated..
private void btnGetData_Click(object sender, EventArgs e)
{
this.btnGetData.Enabled = false;
Application.DoEvents();
string stringSql = " SELECT distinct " +
"'" + comboBox6.Text + "' as RecordType" +
" , left([CPC No] +' ',30) " +
" , space(1983) " +
",'" + comboBox6.Text + " 'as RecordType" +
, left(t.t_reference + ' ' ,24 ) as ClaimantReference " +
" , left([Claim Number] +' ',30) " +
" , " + comboBox4.Text + " as CourtCode" +
" ,left(ta_title +' ',30) as Title " +
" ,left(ta_surname +' ',30) as Surname " +
", space(180), bat.PCN_Charge as ClaimAmount " +
",[Court Fee] " +
",[Solictors Fees]" +
", (bat.PCN_Charge + [Court Fee]) as TotalAmount" +
",[POC1]" +
",'" + textBox2.Text + "' as RequestType" +
//",'" + comboBox1.Text + "' as RecordType" +
",'" + textBox3.Text + "' as TotalCourtFee" +
",'" + textBox4.Text + "' as TotalClaimAmount" +
" , space(1966) " +
" FROM tickets t " +
" LEFT OUTER JOIN " +
"( " +
" SELECT ticket_addresses.ta_system_ref, ta_title, ta_othername, ta_surname, ta_house_number, ta_address_1, ta_address_2, " +
" ta_address_3, ta_address_4, ta_post_code, ta_telephone, ta_organisation " +
" FROM ticket_addresses " +
" INNER JOIN " +
" ( " +
" SELECT ticket_addresses.ta_system_ref, MAX(ta_address_code) AS ta_address_code " +
" FROM ticket_addresses " +
" GROUP BY ta_system_ref " +
" ) ad " +
" ON (ticket_addresses.ta_system_ref=ad.ta_system_ref AND ticket_addresses.ta_address_code=ad.ta_address_code) " +
")ta " +
"ON (t.t_number=ta.ta_system_ref) " +
" " +
" Inner JOIN " +
" ticket_hold_record b " +
" ON ( t.t_number = b.thr_system_ref) " +
" " +
"Inner JOIN " +
"Rpt_PCNBalance_ALLTickets bat " +
"ON (t.t_number = bat.t_number) " +
" " +
"Inner JOIN " +
"hold_reasons ch " +
"ON (b.thr_hold_type = ch.hr_code) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[Courtfees] cf " +
" ON (bat.Payments >= cf. [Min ClaimAmount]) and (bat.Payments <= cf.[Max Claim Amount]) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[sites] s " +
" ON (t.t_contract = s.Contract) " +
" " +
"Inner JOIN " +
" [VCS].[dbo].[claim info] cc " +
" ON (cc.Code COLLATE DATABASE_DEFAULT = t.t_offence_code COLLATE DATABASE_DEFAULT) " +
" and t.t_reference IN {where} ";
//Generate list of Ticket IDS for SQL Where Clause
string whereClause = "";
string[] tempArray = new string[this.txt.Lines.Length];
tempArray = this.txt.Lines;
if (this.txt.Lines.Length == 0)
{
return;
}
for (int counter = 0; counter <= tempArray.Length-1; counter++)
{
if (tempArray[counter].Trim().Length > 0)
{
whereClause = whereClause + "'" + tempArray[counter] + "'" + ", ";
}
}
whereClause = whereClause.TrimEnd(' ', ',');
whereClause = "(" + whereClause + ")";
stringSql = stringSql.Replace("{where}", whereClause);
myDataset = new DataSet("SQL");
SqlConnection myConn = new SqlConnection();
SqlCommand myCommand = new SqlCommand();
myCommand.CommandType = CommandType.Text;
myCommand.CommandText = stringSql;
myCommand.Connection = myConn;
SqlDataAdapter myAdapter = new SqlDataAdapter();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(myDataset);
this.dataGridView1.DataSource = myDataset.Tables[0];
for (int counter = 0; counter < myDataset.Tables[0].Columns.Count; counter++)
{
this.dataGridView1.Columns[counter].SortMode = DataGridViewColumnSortMode.NotSortable;
}
this.dataGridView1.Refresh();
myConn.Close(); this.btnGetData.Enabled = true;
this.btnSave.Enabled = true;
Application.DoEvents();
}

"Attempted to read or write protected memory" when filling a DataTable

I am developing some reports using ReportViewer and at certain point I have to connect to an Oracle database to retrieve some data and store it in a DataTable.
When the DataAdapter executes the Fill method I get this error:
"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
Here's the code(unfortunatelly I can't put that sql code inside a procedure or something):
OleDbConnection objConn = new OleDbConnection(ConfigurationManager.ConnectionStrings["Premio"].ConnectionString);
OleDbCommand objCmd = new OleDbCommand();
DataTable objDt = new DataTable();
int vTipoTerr = LoadTipoTerritorio(ReportParameter.ReportData.Parameters.Item("pTerritorio").Value.ToString());
string vDataParametroDataFinal = ReportParameter.ReportData.Parameters.Item("pMesAnoCompetencia").Value.ToString();
int vDataInicial = int.Parse(vDataParametroDataFinal.Substring(0, 4));
vDataInicial = vDataInicial - 1;
vDataInicial = int.Parse(vDataInicial.ToString() + vDataParametroDataFinal.Substring(4, 2));
objCmd.CommandText = "SELECT T.Nome, " +
" T.Prontuario, " +
" C.Cobertura, " +
" Cn.Mesano_competencia, " +
" G.Grupo, " +
" T.Territorio, " +
" N.Negocio " +
" FROM Calculo C " +
" Inner Join Territorio T " +
" ON C.Id_Territorio = T.Id_Territorio " +
" Inner Join Grupo G " +
" ON C.Id_Grupo = G.Id_Grupo " +
" Inner Join Cenario Cn " +
" On Cn.Id_cenario = C.Id_cenario " +
" Inner Join Negocio N " +
" On Cn.Id_negocio = N.Id_negocio " +
" Where Cn.Mesano_competencia Between :p1 And :p2 --datas " +
" And G.Grupo = :p3 " +
" And Sub_terr(T.Territorio, Decode(:p4, 1, 'SETOR', 2, 'DISTRITO', 3, 'REGIONAL')) = :p5 " +
" And (Cn.Flag_cenario_disp = 1 Or Cn.Flag_cenario_disp_rec = 1) " +
" And N.Negocio = :p6 " +
" And Cn.Flag_recuperacao = 0 " +
" Order By Cn.Mesano_competencia; " +
"union all " +
"SELECT T.Nome, " +
" T.Prontuario, " +
" C.Cobertura, " +
" Cn.Mesano_competencia, " +
" G.Grupo, " +
" T.Territorio, " +
" N.Negocio " +
" FROM Calculo_Rec C " +
" Inner Join Territorio T " +
" ON C.Id_Territorio = T.Id_Territorio " +
" Inner Join Grupo G " +
" ON C.Id_Grupo = G.Id_Grupo " +
" Inner Join Cenario Cn " +
" On Cn.Id_cenario = C.Id_cenario " +
" Inner Join Negocio N " +
" On Cn.Id_negocio = N.Id_negocio " +
" Where Cn.Mesano_competencia Between :p1 And :p2 " +
" And G.Grupo = :p3 " +
" And Sub_terr(T.Territorio, Decode(:p4, 1, 'SETOR', 2, 'DISTRITO', 3, 'REGIONAL')) = :p5 " +
" And (Cn.Flag_cenario_disp = 1 Or Cn.Flag_cenario_disp_rec = 1) " +
" And N.Negocio = :p6 " +
" And Cn.Flag_recuperacao = 1 " +
" Order By Cn.Mesano_competencia ";
objCmd.Parameters.Add(new OleDbParameter("p1", OleDbType.Integer)).Value = vDataInicial;
objCmd.Parameters.Add(new OleDbParameter("p2", OleDbType.Integer)).Value = int.Parse(vDataParametroDataFinal);
objCmd.Parameters.Add(new OleDbParameter("p3", OleDbType.VarChar, 30)).Value = ReportParameter.ReportData.Parameters.Item("pGrupo").Value.ToString();
objCmd.Parameters.Add(new OleDbParameter("p4", OleDbType.Integer)).Value = vTipoTerr;
objCmd.Parameters.Add(new OleDbParameter("p5", OleDbType.VarChar, 30)).Value = ReportParameter.ReportData.Parameters.Item("pTerritorio").Value.ToString();
objCmd.Parameters.Add(new OleDbParameter("p6", OleDbType.VarChar, 30)).Value = ReportParameter.ReportData.Parameters.Item("pNegocio").Value.ToString();
OleDbDataAdapter objAdapter = new OleDbDataAdapter(objCmd);
objConn.Open();
objAdapter.Fill(objDt);
objConn.Close();
Thank you very much (:
Try using OracleCommand and OracleConnection objects instead:
OracleConnection objConn = new OracleConnection (ConfigurationManager.ConnectionStrings["Premio"].ConnectionString);
OracleCommand objCmd = new OracleCommand ();

Categories