HttpClient put issue in Angular - c#

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";

Related

Error ORA-00907 Right parenthesis missing

Hello i have a long SQL Query for Oracle DB. My Problem is i'm searching for arround 2 hours to get the error fixed. On all Queries i have the same error with parenthesis.
Here is my class where i get the error inside the command of OracleDB Query. I didnt find the error. The Query shown below is working on Delphi without problems. The only thing i change are the quotation marks at the beginning and at the end of each line which a normally single quoted.
using System;
using System.Windows.Forms;
using Oracle.ManagedDataAccess.Client;
namespace RawBinderLabel
{
public partial class Rawbinder_Manually : Form
{
private database_conn db_conn = new database_conn();
private OracleConnection OraConn = new OracleConnection();
public Rawbinder_Manually()
{
InitializeComponent();
get_rawbinder_data();
}
public void get_rawbinder_data()
{
string rcs = db_conn.connection();
using (OracleConnection OraConn = new OracleConnection(rcs))
{
using (OracleCommand OraCmd = OraConn.CreateCommand())
{
try
{
OraConn.Open();
OraCmd.BindByName = true;
//SQL Command to retrieve manual binder that ar OK
OraCmd.CommandText = "SELECT l.a_layer_pos, " +
" l.a_serial, " +
" P_ROHBINDER_ETIKETTEN.GET_BARCODE (mb.a_serial,''M'') Barcode, " +
" mb.a_splitted," +
" mb.a_dlam, " +
" l.a_order_id, " +
" l.a_section_id, " +
" P_ROHBINDER_ETIKETTEN.GET_MANUALPOSITIONS (mb.a_serial) Positionen, " +
" P_ROHBINDER_ETIKETTEN.GET_MANUALABBUND (mb.a_serial) abbund, " +
" P_ROHBINDER_ETIKETTEN.GET_MANUALQUALITY (mb.a_prodquality_id) qualitaet, " +
" to_char(lt.LIEFERTERMIN, ''dd.mm.yyyy'') liefertermin, " +
" ''1'' a_beam_pos, " +
" P_ROHBINDER_ETIKETTEN.GET_MAXMANUALLENGTH (l.a_serial) max_a_length, " +
" substr(c.a_cust_name,1,40) kunde, " +
" l.a_dimter_start_date, " +
" l.a_dimter_end_date, " +
" p.a_prod_date, " +
" p.a_destheight, " +
" p.a_description, " +
" dl.a_layer_serial, " +
" dl.a_width, " +
" dl.a_lamellaheight, " +
" dl.A_RAWWIDTH, " +
" dl.A_RAWLAMELLAHEIGHT, " +
" dl.A_GLUE_DESCRIPTION, " +
" dl.A_COLOR_DESCRIPTION, " +
" dl.a_pressproc_description, " +
" dl.a_pressproc_description ||' - ' || p.a_description || '' - ('' ||p.a_destlength || '')'' pressbett, " +
" mb.a_serial beam_serial," +
" mb.a_prodquality_id," +
" FROM t_manual_layer l," +
"t_manual_pressproc p, " +
"t_dimter_layer dl, " +
"t_manualbeam mb, " +
"v_liefertermin lt, " +
"t_order o, " +
"t_customer c " +
" WHERE to_char(p.a_prod_date,''DD.MM.YYYY'') = ''' :rawbinder_date '''" +
" and p.a_pressproc_id = l.a_pressproc_id " +
" AND l.A_SERIAL = dl.A_SERIAL " +
" AND mb.A_LAYER_SERIAL = l.a_serial " +
" AND lt.PROJEKTNR = l.a_order_id " +
" AND lt.GPID = l.a_section_id " +
" AND o.a_order_id = l.a_order_id " +
" and c.a_customer_id = o.a_customer_id " +
" order by l.A_SERIAL, l.a_layer_pos";
//Assign Parameters to Date selected in Overview Form
OracleParameter rawbinder_date = new OracleParameter("rawbinder_date", RawBinder_Overview.rawbinder_date);
OraCmd.Parameters.Add(rawbinder_date);
//Execute the command and display it using DataReader
OracleDataReader OraDataRead = OraCmd.ExecuteReader();
while (OraDataRead.Read())
{
Console.WriteLine("Manually Implemented" + OraDataRead.GetString(0));
}
}
catch (OracleException ex)
{
switch (ex.Number)
{
case 1:
MessageBox.Show("Fehler beim Einfügen der Daten");
break;
case 12560:
MessageBox.Show("Die Datenbank ist nicht erreichbar.");
break;
default:
MessageBox.Show("Datenbankfehler: " + ex.Message.ToString());
break;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
OraConn.Dispose();
}
}
}
}
}
}
Does someone has an Idea how to fix that Problem?
I think there are multiple issues:
2 times single quotes are not required everywhere
comma after " mb.a_prodquality_id," + is not required as it is the last expression of SELECT clause
as mentioned in the comment by #crowcoder, single quotes around parameters are not required. Means around this: :rawbinder_date
Try to solve all this problems and check if it executes properly.

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();
}
}

Error with SQL Server request using data.sqlclient in UWP

I am trying to run a SQL query on my UWP code. I don't use Linq or EF. The connection to the base work and the simple requests work. This causes me problems: in a first time i populate a listview with the result of a simple request, i choose an element and i click on a searchin button. This request is call with an error:
static public ObservableCollection GetGaz(string connectionString,
string selectedOrder)
{
string GetGazQuery =
"SELECT " +
"tbl_607_gaz_type.gaz_type," +
"tbl_607_theorical_content.theorical_content," +
"tbl_607_made_tolerance.made_tolerance," +
"tbl_607_order_details.gaz_lifetime," +
"tbl_607_gaz.gaz_comments," +
"tbl_607_order_details.FK_ID_order," +
"tbl_607_order_details.poste_number, " +
"tbl_607_order.order_number" +
"FROM " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider " +
"join tbl_607_order_details on tbl_607_order.ID = tbl_607_order_details.FK_ID_order" +
"join tbl_607_gaz on tbl_607_order_details.FK_ID_gaz = tbl_607_gaz.ID " +
"join tbl_607_gaz_type on tbl_607_gaz.FK_ID_gaz_type = tbl_607_gaz_type.ID " +
"join tbl_607_made_tolerance on tbl_607_gaz.FK_ID_made_tolerence = tbl_607_made_tolerance.ID " +
"join tbl_607_theorical_content on tbl_607_gaz.FK_ID_theorical_content = tbl_607_theorical_content.ID " +
"WHERE " +
"tbl_607_order.order_number" + " LIKE " + "'%" + selectedOrder + "%'";
ObservableCollection GazList = new ObservableCollection();
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = GetGazQuery;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Gaz gaz = new Gaz
{
Gaz_type = reader.GetString(0),
Theorical_content = reader.GetString(1),
Made_tolerance = reader.GetDouble(2),
Gaz_lifetime = reader.GetInt32(3),
Gaz_comments = reader.GetString(4),
Poste_number = reader.GetInt32(6)
};
GazList.Add(gaz);
}
}
}
}
}
return GazList;
}
catch (Exception eSql)
{
Debug.WriteLine("Exception: " + eSql.Message);
}
return null;
}
}
private string selectedOrder;
public Gestion_Stock()
{
this.InitializeComponent();
SelectOrders.ItemsSource = OrdersDataHelper.GetOrders(connectionString: (Windows.UI.Xaml.Application.Current as App).ConnectionString);
}
private void Search_Click(object sender, RoutedEventArgs e)
{
Affichage_Stock_Gaz.ItemsSource = GazDataHelper.GetGaz((Windows.UI.Xaml.Application.Current as App).ConnectionString, selectedOrder);
}
private void SelectOrders_SelectionChanged (object sender, SelectionChangedEventArgs e)
{
ListView selectOrders = sender as ListView;
Orders orders = SelectOrders.SelectedItem as Orders;
selectedOrder = orders.Order_Number;
}
The output:
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.SqlClient.dll
Exception: Incorrect syntax near the keyword 'join'
This simple request is working, i don't use a variable and "where" command.
This work:
static public ObservableCollection GetOrders(string connectionString)
{
const string GetOrdersQuery = "" +
"select " +
"tbl_607_order.start_date," +
"tbl_607_order.end_date," +
"tbl_607_provider.provider_name," +
"tbl_607_order.order_number," +
"tbl_607_order.shipping_request_active," +
"tbl_607_order.item_reception_active " +
"from " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider "
;
Someone would have any idea?
Thanks a lot!
Add the missing space by changing
"SELECT " +
"tbl_607_gaz_type.gaz_type," +
"tbl_607_theorical_content.theorical_content," +
"tbl_607_made_tolerance.made_tolerance," +
"tbl_607_order_details.gaz_lifetime," +
"tbl_607_gaz.gaz_comments," +
"tbl_607_order_details.FK_ID_order," +
"tbl_607_order_details.poste_number, " +
"tbl_607_order.order_number" +
"FROM " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider " +
"join tbl_607_order_details on tbl_607_order.ID = tbl_607_order_details.FK_ID_order" +
"join tbl_607_gaz on tbl_607_order_details.FK_ID_gaz = tbl_607_gaz.ID " +
"join tbl_607_gaz_type on tbl_607_gaz.FK_ID_gaz_type = tbl_607_gaz_type.ID " +
"join tbl_607_made_tolerance on tbl_607_gaz.FK_ID_made_tolerence = tbl_607_made_tolerance.ID " +
"join tbl_607_theorical_content on tbl_607_gaz.FK_ID_theorical_content = tbl_607_theorical_content.ID " +
"WHERE " +
"tbl_607_order.order_number" + " LIKE " + "'%" + selectedOrder + "%'";
to
"SELECT " +
"tbl_607_gaz_type.gaz_type," +
"tbl_607_theorical_content.theorical_content," +
"tbl_607_made_tolerance.made_tolerance," +
"tbl_607_order_details.gaz_lifetime," +
"tbl_607_gaz.gaz_comments," +
"tbl_607_order_details.FK_ID_order," +
"tbl_607_order_details.poste_number, " +
"tbl_607_order.order_number" +
"FROM " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider " +
"join tbl_607_order_details on tbl_607_order.ID = tbl_607_order_details.FK_ID_order " + // note the missing space added here
"join tbl_607_gaz on tbl_607_order_details.FK_ID_gaz = tbl_607_gaz.ID " +
"join tbl_607_gaz_type on tbl_607_gaz.FK_ID_gaz_type = tbl_607_gaz_type.ID " +
"join tbl_607_made_tolerance on tbl_607_gaz.FK_ID_made_tolerence = tbl_607_made_tolerance.ID " +
"join tbl_607_theorical_content on tbl_607_gaz.FK_ID_theorical_content = tbl_607_theorical_content.ID " +
"WHERE " +
"tbl_607_order.order_number" + " LIKE " + "'%" + selectedOrder + "%'";

DatagridView boolean values update to database

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();

C# adding every table row to textbox from database

I've been working a bit with binding database tables to text boxes and I've encountered a problem. The code I have here gets all the columns I need from the table, but only 1 row's worth of data shows up. Is there a simple way to make every single row from the table appear in a text box? Or some other sort of text list?
SqlConnection cn = new SqlConnection("SERVER=myserver;DATABASE=mydb;Trusted_Connection=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr = null;
cmd.Connection = cn;
cn.Open();
cmd.CommandText = "SELECT DisasterID,DisasterType,Location,CurrentStatus,IntensityLevel,Latitude,Longitude FROM Disasters";
dr = cmd.ExecuteReader();
if (dr.Read()) {
txtFeeds.Text = dr["DisasterID"].ToString() + " " + dr["DisasterType"].ToString() + " " + dr["Location"].ToString() + " " + dr["CurrentStatus"].ToString() + " " + dr["IntensityLevel"].ToString() + " " + dr["Latitude"].ToString() + " " + dr["Longitude"].ToString();
}
cn.Close();
You need while loop and append each line to textbox by txtFeeds.Text +=
while(dr.Read()) {
txtFeeds.Text += dr["DisasterID"].ToString() + " "
+ dr["DisasterType"].ToString() + " "
+ dr["Location"].ToString() + " "
+ dr["CurrentStatus"].ToString() + " "
+ dr["IntensityLevel"].ToString() + " "
+ dr["Latitude"].ToString() + " " + dr["Longitude"].ToString();
}
If you need more performance you can use StringBuilder to append text and finally set textbox text using StringBuilder.ToString method.
Edit.
StringBuilder sb = new StringBuilder();
while (dr.Read())
{
sb.AppendLine(dr["DisasterID"].ToString() + " "
+ dr["DisasterType"].ToString() + " "
+ dr["Location"].ToString() + " "
+ dr["CurrentStatus"].ToString() + " "
+ dr["IntensityLevel"].ToString() + " "
+ dr["Latitude"].ToString() + " " + dr["Longitude"].ToString());
}
txtFeeds.Text = sb.ToString();
First of all its a bad idea trying display records from a table in a single textbox.
If you still want to do it,
Use a while loop instead of IF condition
while(dr.Read())
{
}
Use a string builder and append all your column values to it and after while loop exists use the values in the string builder and set it to the field.
StringBuilder values = new StringBuilder();
while(dr.Read()) {
values.Append( dr["DisasterID"].ToString() + " " + dr["DisasterType"].ToString() + " " + dr["Location"].ToString() + " " + dr["CurrentStatus"].ToString() + " " + dr["IntensityLevel"].ToString() + " " + dr["Latitude"].ToString() + " " + dr["Longitude"].ToString());
}
txtFeeds.Text = values.ToString();

Categories