Updating a Image field in SQL server - c#

I am trying to update mu existing image field in one of my table and I am getting error saying "A generic error occurred in GDI+". Please help.
private void Add_Records()
{
int i = check_for_null();
if (i == 1)
{
DateTime Nw = DateTime.Now;
int user = Form_Common_Login.user_id;
int ref_lc = 0;
ref_lc = Convert.ToInt16(cbo_emp_cat.SelectedValue);
try
{
string query = #"INSERT INTO tbl_Labour_Employee_Reg
(Ref_IDLC,First_Name,Last_Name,Emp_Image,Designation,NIC_No,Emp_Address,Previous_WorkPlaces,Phone_Number_Mobile,Phone_Number_Residential,Account_Number,Employee_Number,Remarks,Accessed_By,Accessed_Time,Is_Deleted,Is_Active)
VALUES ('" + ref_lc + "','" + txt_Fname.Text + "','" + txt_Lname.Text + "',#image_array,'" + txt_designation.Text + "','" + txt_nic.Text + "','" + txt_address.Text + "','" + txt_previous_wp.Text + "','" + txt_Mnumber.Text + "','" + txt_Lnumber.Text + "','" + txt_account_number.Text + "','" + txt_emp_number.Text + "','" + txt_remarks.Text + "','" + user + "','" + Nw + "',0,1)";
clz_Common_SqlConnection con = new clz_Common_SqlConnection();
SqlCommand cmd = new SqlCommand(query ,con.ActiveCon ());
MemoryStream ms = new MemoryStream ();
pic_box_employee.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] image_array = ms.ToArray();
cmd.Parameters.AddWithValue("#image_array", image_array);
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else { MessageBox.Show("Please enter Valid Data"); }
}
my update code here
private void Update_Records()
{
int i = check_for_null();
if (i == 1)
{
DateTime Nw = DateTime.Now;
int user = Form_Common_Login.user_id;
int ref_lc = 0;
ref_lc = Convert.ToInt16(cbo_emp_cat.SelectedValue);
try
{
string update_query = "UPDATE tbl_Labour_Employee_Reg"+
"SET Ref_IDLC ='"+ref_lc+"',First_Name = ,'" + txt_Fname.Text + "',Last_Name='" + txt_Lname.Text + "',Emp_Image = #image_array,Designation = '" + txt_designation.Text + "',NIC_No='" + txt_nic.Text + "',Emp_Address = '" + txt_address.Text + "'"+
",Previous_WorkPlaces = '" + txt_previous_wp.Text + "', Phone_Number_Mobile = '" + txt_Mnumber.Text + "',Phone_Number_Residential='" + txt_Lnumber.Text + "', Account_Number= '" + txt_account_number.Text + "',Employee_Number='" + txt_emp_number.Text + "'"+
",Remarks='" + txt_remarks.Text + "',Accessed_By='" + user + "',Accessed_Time= '" + Nw + "',Is_Deleted=0,Is_Active=1";
clz_Common_SqlConnection con = new clz_Common_SqlConnection();
SqlCommand cmd = new SqlCommand(update_query, con.ActiveCon());
MemoryStream ms = new MemoryStream();
pic_box_employee.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] image_array = ms.ToArray();
cmd.Parameters.AddWithValue("#image_array", image_array);
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully Updated");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else { MessageBox.Show("Please enter Valid Data"); }
}
Insert function is properly working but the update is not. I am really struck in here. If you have better way to insert & update a image field please explain.

First of all move your answer to your question. Its not an answer. Its just a new question.
try using the following, I personally update images as follows;
Image img = Image.FromFile(#"C:\Users\Awais\Desktop\image.png");
byte[] arr;
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
arr = ms.ToArray();
}
int dr = 0;
SqlConnection con = new SqlConnection("data source=.; initial catalog=database; uid=sa;pwd=password;");
SqlCommand cmd = new SqlCommand("update table set I1 = #img", con);
cmd.Parameters.AddWithValue("#img", arr);
con.Open();
using (con)
{
dr = cmd.ExecuteNonQuery();
}

Related

How can i insert from DataGridView to database when you have Columns with Date

I'm trying to enter data into the database from a DataGridView. I have 3 columns that contain Date.
When I try to insert to database I get the error:
Conversion failed when converting date and/or time from character string
With this I format the columns that show the date:
private void Import()
{
if (textBox4.Text.Trim() != string.Empty)
{
try
{
DataTable dt = GetDataTable(textBox4.Text);
dataGridView2.DataSource = dt.DefaultView;
dataGridView2.Columns[6].DefaultCellStyle.Format = "dd/mm/yyyy";
dataGridView2.Columns[8].DefaultCellStyle.Format = "dd/mm/yyyy";
dataGridView2.Columns[15].DefaultCellStyle.Format = "dd/mm/yyyy";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
With this part, I enter the data in the database from a DatagridView:
string constring = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
if (con.State == ConnectionState.Closed)
con.Open();
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
try
{
SqlCommand sqlCmd = new SqlCommand("insert into abonament (nr, serie, cui, client, sim, data_inst, activare, data_exp, telefon, nr_activat, nr_zile, ob, tip_client, email, datacurenta1, semnatura) values ('" + dataGridView1.Rows[i].Cells[0].Value + "','" + dataGridView1.Rows[i].Cells[1].Value + "','" + dataGridView1.Rows[i].Cells[2].Value + "','" + dataGridView1.Rows[i].Cells[3].Value + "','" + dataGridView1.Rows[i].Cells[4].Value + "','" + dataGridView1.Rows[i].Cells[5].Value + "','" + dataGridView1.Rows[i].Cells[6].Value + "','" + dataGridView1.Rows[i].Cells[7].Value + "','" + dataGridView1.Rows[i].Cells[8].Value + "','" + dataGridView1.Rows[i].Cells[9].Value + "','" + dataGridView1.Rows[i].Cells[10].Value + "','" + dataGridView1.Rows[i].Cells[11].Value + "','" + dataGridView1.Rows[i].Cells[12].Value + "','" + dataGridView1.Rows[i].Cells[13].Value + "','" + dataGridView1.Rows[i].Cells[14].Value + "','" + dataGridView1.Rows[i].Cells[15].Value + "')", con);
sqlCmd.ExecuteNonQuery();
MessageBox.Show("ok");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "error");
}
}
this was my solution
for (int i = 0; i < dataGridView2.RowCount; i++)
{
DateTime d1 = Convert.ToDateTime(dataGridView2.Rows[i].Cells[6].Value.ToString());
string format = "s";
DateTime d2 = Convert.ToDateTime(dataGridView2.Rows[i].Cells[8].Value.ToString());
DateTime d3 = Convert.ToDateTime(dataGridView2.Rows[i].Cells[15].Value.ToString());
try
{
SqlCommand sqlCmd = new SqlCommand("insert into abonament (nr, serie, cui, client, sim, data_inst, activare, data_exp, telefon, nr_activat, nr_zile, ob, tip_client, email, datacurenta1, semnatura) values ( #nr, #serie, #cui, #client, #sim, #data_inst, #activare, #data_exp, #telefon, #nr_activat, #nr_zile, #ob, #tip_client, #email, #datacurenta1, #semnatura)", con);
sqlCmd.Parameters.AddWithValue("#mode", "Add");
sqlCmd.Parameters.AddWithValue("#id", 0);
sqlCmd.Parameters.AddWithValue("#nr ", dataGridView2.Rows[i].Cells[1].Value);
sqlCmd.Parameters.AddWithValue("#serie ", dataGridView2.Rows[i].Cells[2].Value);
sqlCmd.Parameters.AddWithValue("#cui ", dataGridView2.Rows[i].Cells[3].Value);
sqlCmd.Parameters.AddWithValue("#client ", dataGridView2.Rows[i].Cells[4].Value);
sqlCmd.Parameters.AddWithValue("#sim ", dataGridView2.Rows[i].Cells[5].Value);
sqlCmd.Parameters.AddWithValue("#data_inst ", d1.Date.ToString(format));
sqlCmd.Parameters.AddWithValue("#activare ", dataGridView2.Rows[i].Cells[7].Value);
sqlCmd.Parameters.AddWithValue("#data_exp ", d2);
sqlCmd.Parameters.AddWithValue("#telefon ", dataGridView2.Rows[i].Cells[9].Value);
sqlCmd.Parameters.AddWithValue("#nr_activat ", dataGridView2.Rows[i].Cells[10].Value);
sqlCmd.Parameters.AddWithValue("#nr_zile ", dataGridView2.Rows[i].Cells[11].Value);
sqlCmd.Parameters.AddWithValue("#ob ", dataGridView2.Rows[i].Cells[12].Value);
sqlCmd.Parameters.AddWithValue("#tip_client ", dataGridView2.Rows[i].Cells[13].Value);
sqlCmd.Parameters.AddWithValue("#email ", dataGridView2.Rows[i].Cells[14].Value);
sqlCmd.Parameters.AddWithValue("#datacurenta1 ", d3);
sqlCmd.Parameters.AddWithValue("#semnatura ", dataGridView2.Rows[i].Cells[16].Value);
sqlCmd.ExecuteNonQuery();
}

else condition not working when reader hasrows is false

Can somebody tell me why the else condition is not working in the code below.
The link button in asp.net web application has following code in code behind: a parameterized SqlCommand fetch a row from a SQL Server database, the SqlDataReader rdr1.HasRows in if condition is working fine but else condition did not work.
Code updated
protected void LinkButton1_Click(object sender, EventArgs e)
{
string comid = DropDownList4.SelectedValue.ToString();
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("Select * from Commercials Where id =" + comid, con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string dur = rdr["duration"].ToString();
Char delimiter = '/';
string[] dd = DateTime.Parse(rdr["rodate"].ToString()).ToString("dd/MM/yyyy").Split(delimiter);
if (DropDownList3.SelectedValue.ToString().Contains("BOL NEWS") == true && DropDownList1.SelectedValue.ToString().Contains("After Headlines") == true)
{
SqlConnection con0 = new SqlConnection(cs);
string sql01 = "Select * from CTS Where air_time=(Select max(air_time) from CTS where air_date=#airdate and air_time Like #airtime and channel=#channel and Slot=#slot) and air_date=#airdate1";
con0.Open();
SqlCommand cmd1 = new SqlCommand(sql01, con0);
cmd1.Parameters.AddWithValue("#airdate", TextBox1.Text);
cmd1.Parameters.AddWithValue("#channel", DropDownList3.SelectedValue.ToString());
cmd1.Parameters.AddWithValue("#airtime", DropDownList2.SelectedValue.ToString().Substring(0, 2) + "%");
cmd1.Parameters.AddWithValue("#slot", DropDownList1.SelectedValue.ToString().Remove(0, 3));
cmd1.Parameters.AddWithValue("#airdate1", TextBox1.Text);
SqlDataReader rdr1 = cmd1.ExecuteReader();
while (rdr1.Read())
{
string startTime0 = rdr1["air_time"].ToString();
string addsec = rdr1["duration"].ToString();
if (rdr1.HasRows)
{
DateTime startTime1 = DateTime.ParseExact(startTime0, "HH:mm:ss", null);
string startHeadlines_ = startTime1.AddSeconds(int.Parse(addsec)).ToString("HH:mm:ss");
using (SqlConnection con2 = new SqlConnection(cs))
{
string type = "Commercial";
string year = dd[2].ToString().Substring(dd[2].ToString().Length - 2);
string HouseId = "CH1COM001" + rdr["rono"] + rdr["duration"] + "S" + dd[1] + dd[0] + year;
string sql1 = "Insert into CTS(air_date,air_time,HouseNumber,rono,Title,duration,Slot,type,channel)Values('" + TextBox1.Text + "','" + startHeadlines_ + "','" + HouseId + "','" + rdr["rono"] + "','" + rdr["slug"] + "','" + rdr["duration"] + "','" + DropDownList1.SelectedValue.Remove(0, 3) + "','" + type + "','" + DropDownList3.SelectedValue.ToString() + "')";
con2.Open();
SqlCommand InsertCmd = new SqlCommand(sql1, con2);
InsertCmd.ExecuteNonQuery();
con2.Close();
}
}
else
{
DateTime startTime = DateTime.ParseExact(DropDownList2.SelectedValue.ToString(), "HH:mm:ss", null);
string startHeadlines = startTime.AddSeconds(210).ToString("HH:mm:ss");
using (SqlConnection con1 = new SqlConnection(cs))
{
string type = "Commercial";
string year = dd[2].ToString().Substring(dd[2].ToString().Length - 2);
string HouseId = "CH1COM001" + rdr["rono"] + rdr["duration"] + "S" + dd[1] + dd[0] + year;
string sql = "Insert into CTS(air_date,air_time,HouseNumber,rono,Title,duration,Slot,type,channel)Values('" + TextBox1.Text + "','" + startHeadlines + "','" + HouseId + "','" + rdr["rono"] + "','" + rdr["slug"] + "','" + rdr["duration"] + "','" + DropDownList1.SelectedValue.ToString().Remove(0, 3) + "','" + type + "','" + DropDownList3.SelectedValue.ToString() + "')";
con1.Open();
SqlCommand InsertCmd = new SqlCommand(sql, con1);
InsertCmd.ExecuteNonQuery();
con1.Close();
}
}
}
con0.Close();
}
}
con.Close();
}
}

C# SQLite database locked

I've tried all the solutions I could find to this problem, but for some reason I still get an exception stating the database I'm using is locked.
My code is as follows:
string connectionString = "Data Source=D:\\CCIW\\LCM\\Organisational Database\\OrganisationalDB;" +
"MultipleActiveResultSets=True";
using (SQLiteConnection OriginatorDBConnection = new SQLiteConnection(connectionString))
{
string originatorName, originatorOrganisation, originatorAddress, originatorCellNumber, originatorTelNumber, originatorEmail;
originatorName = originatorNameTextBox.Text;
originatorOrganisation = originatorOrganisationTextBox.Text;
originatorAddress = originatorAddressRichTextBox.Text;
originatorCellNumber = originatorCellTextBox.Text;
originatorTelNumber = originatorTelTextBox.Text;
originatorEmail = originatorEmailTextBox.Text;
OriginatorDBConnection.Open();
string originatorINSERT = "INSERT INTO Originator (Name, Organisation, Address, CellphoneNumber, TelephoneNumber, Email) VALUES ('" + originatorName + "', '" + originatorOrganisation + "', '" + originatorAddress + "', '" + originatorCellNumber + "', '" + originatorTelNumber + "', '" + originatorEmail + "');";
using (SQLiteCommand originatorCommand = new SQLiteCommand(originatorINSERT, OriginatorDBConnection))
{
originatorCommand.ExecuteNonQuery();
}
OriginatorDBConnection.Close();
}
The closest solution on here that I could find to the problem was here: SQLite Database Locked exception
It didn't seem to work on my problem, however.
What am I doing wrong?
I have an additional function wherein I use the connection:
public AdminForm()
{
//Initialise AdminForm components.
InitializeComponent();
//Establish and open connection to ObservationDB.
string connectionString = "Data Source=D:\\CCIW\\LCM\\Organisational Database\\OrganisationalDB;" +
"MultipleActiveResultSets=True";
ObservationDBConnection = new SQLiteConnection(connectionString);
ObservationDBConnection.Open();
//Query database to find all originators
string originatorSELECT = "SELECT * FROM Originator;";
string ECPNumberSELECT = "SELECT * FROM ECP";
SQLiteCommand command = new SQLiteCommand(originatorSELECT, ObservationDBConnection);
SQLiteDataReader reader = command.ExecuteReader();
SQLiteCommand command2 = new SQLiteCommand(ECPNumberSELECT, ObservationDBConnection);
SQLiteDataReader reader2 = command2.ExecuteReader();
//Populate OriginatorName combobox with names of existing originators.
List<string> originatorNames = new List<string>();
while (reader.Read())
{
originatorNames.Add(Convert.ToString(reader["Name"]));
}
OriginatorNameComboBox.DataSource = originatorNames;
//Populate ECP combobox with numbers of existing ECP.
List<string> ECPNumbers = new List<string>();
while (reader2.Read())
{
ECPNumbers.Add(Convert.ToString(reader2["Number"]));
}
ECPNumComboBox.DataSource = ECPNumbers;
//Populate TC Decision combobox with options.
List<string> TCDecision = new List<string>();
TCDecision.Add("Rework");
TCDecision.Add("Reject");
TCDecision.Add("Approve");
TCDecisionComboBox.DataSource = TCDecision;
ObservationDBConnection.Close();
}
And here:
private void SaveButton_Click(object sender, EventArgs e)
{
ObservationDBConnection.Open();
...
string ImpactTypeINSERT = "INSERT INTO ImpactType (ImpactType, Description) VALUES ('" + impactType + "', '" + impactDescription + "');";
SQLiteCommand ImpactTypeCommand = new SQLiteCommand(ImpactTypeINSERT, ObservationDBConnection);
//SQLiteDataReader ImpactTypeReader = ImpactTypeCommand.ExecuteReader();
ImpactTypeCommand.ExecuteNonQuery();
...
string TCDecisionINSERT = "INSERT INTO TCDecision (Decision, Description) VALUES ('" + TechnicalCommitteeDecision + "', '" + TechnicalCommitteeDescription + "');";
SQLiteCommand TCDecisionCommand = new SQLiteCommand(TCDecisionINSERT, ObservationDBConnection);
SQLiteDataReader TCDecisionReader = ImpactTypeCommand.ExecuteReader();
TCDecisionCommand.ExecuteNonQuery();
...
string OperationalDecisionINSERT = "INSERT INTO OperationalDecision (Decision, Description) VALUES ('" + operationalDecision + "', '" + operationalDescription + "');";
SQLiteCommand OperationalDecisionCommand = new SQLiteCommand(OperationalDecisionINSERT, ObservationDBConnection);
//SQLiteDataReader OperationalDecisionReader = OperationalDecisionCommand.ExecuteReader();
OperationalDecisionCommand.ExecuteNonQuery();
...
...
string OriginatorIDSELECT = "SELECT * FROM Originator WHERE Name='" + OriginatorNameComboBox.Text + "';";
SQLiteCommand OriginatorIDCommand = new SQLiteCommand(OriginatorIDSELECT, ObservationDBConnection);
SQLiteDataReader OriginatorIDReader = OriginatorIDCommand.ExecuteReader();
originatorIDOBS = OriginatorIDReader.GetOrdinal("ID");
//ImpactType
string impactTypeSELECT = "SELECT * FROM ImpactType WHERE ImpactType='" + impactType + "';";
SQLiteCommand impactTypeOBSCommand = new SQLiteCommand(impactTypeSELECT, ObservationDBConnection);
SQLiteDataReader impactTypeOBSReader = impactTypeOBSCommand.ExecuteReader();
impactTypeOBS = impactTypeOBSReader.GetOrdinal("ID");
string operationalDecisionOBSSELECT = "SELECT * FROM OperationalDecision WHERE Decision='" + operationalDecision + "';";
SQLiteCommand operationalDecisionOBSCommand = new SQLiteCommand(operationalDecisionOBSSELECT, ObservationDBConnection);
SQLiteDataReader operationalDecisionOBSReader = operationalDecisionOBSCommand.ExecuteReader();
operationalDecisionOBS = operationalDecisionOBSReader.GetOrdinal("ID");
...
string ECPOBSSELECT = "SELECT * FROM ECP WHERE Number='" + ECPNumComboBox.Text + "';";
SQLiteCommand ECPCommand = new SQLiteCommand(ECPOBSSELECT, ObservationDBConnection);
SQLiteDataReader ECPReader = ECPCommand.ExecuteReader();
ECPOBS = ECPReader.GetOrdinal("ID");
string CNISObservationINSERT = "INSERT INTO CNISObservation (Title, ReceiveDate, TableDate, OriginatorID, OriginatorReference, OriginatorDate, ObservationNumber, RevisionNumber, Description, Status, ImpactDescription, ImpactType, OperationalRequirementDescription, OperationalImpact, OperationalDecision, ProposedAction, TCDecision, ECP, SolutionOperationalImpact, TechnicalSolutionImpact) VALUES ('" +
titleOBS + "','"
+ receiveDateOBS + "','"
+ tableDateOBS + "','"
+ originatorIDOBS + ",'"
+ originatorReferenceOBS +"','"
+ originatorDateOBS + "','"
+ observationNumberOBS + "',"
+ revisionNumberOBS + ",'"
+ descriptionOBS + "',"
+ statusOBS + ",'"
+ impactDescriptionOBS + "',"
+ impactTypeOBS + ",'"
+ operationalRequirementDescriptionOBS + "','"
+ operationalImpactOBS + "',"
+ operationalDecisionOBS + ",'"
+ TCDecisionOBS + ","
+ ECPOBS + ",'"
+ solutionOperationalImpactOBS + "','"
+ technicalSolutionImpactOBS + "');";
...
string obsOBSSELECT = "SELECT * FROM CNISObservation ORDER BY ID DESC LIMIT 1;";
SQLiteCommand CNISObservationIDCommand = new SQLiteCommand(obsOBSSELECT, ObservationDBConnection);
SQLiteDataReader CNISObservationIDReader = CNISObservationIDCommand.ExecuteReader();
observationID = CNISObservationIDReader.GetOrdinal("ID");
...
foreach (var capabilityID in capabilitiesSelected)
{
string ObservationOperationalCapabilitiesINSERT = "INSERT INTO ObservationOperationalCapabilities (CapabilityID, ObservationID) VALUES (" + capabilityID + "," + observationID + ");";
SQLiteCommand ObservationOperationalCapabilitiesCommand = new SQLiteCommand(ObservationOperationalCapabilitiesINSERT, ObservationDBConnection);
// SQLiteDataReader ObservationOperationalCapabilitiesReader = ObservationOperationalCapabilitiesCommand.ExecuteReader();
ObservationOperationalCapabilitiesCommand.ExecuteNonQuery();
}
...
string CNISObservationIDSELECT = "SELECT * FROM CNISObservation ORDER BY ID DESC LIMIT 1;";
SQLiteCommand CNISObservationCommand = new SQLiteCommand(CNISObservationIDSELECT, ObservationDBConnection);
SQLiteDataReader CNISObservationReader = CNISObservationCommand.ExecuteReader();
CNISObservationID = CNISObservationReader.GetOrdinal("ID");
string CNISReleaseINSERT = "INSERT INTO CNISSection VALUES (" + CNISObservationID + "," + CNISRelease + "," + chapter + ",'" + paragraph + "','" + section + "','" + page +"');";
SQLiteCommand CNISReleaseCommand = new SQLiteCommand(CNISReleaseINSERT, ObservationDBConnection);
//SQLiteDataReader CNISReleaseReader = CNISReleaseCommand.ExecuteReader();
CNISReleaseCommand.ExecuteNonQuery();
ObservationDBConnection.Close();
}
I know I'm a lot late to the game, but it looks like you're not closing you reader variables in AdminForm() constructor. Consider wrapping the DataReaders in a using().
Wrapping around Command and Reader did work for me:
using (SqliteCommand cmd = new SqliteCommand(sQuery, m_Conn))
{
using (SqliteDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
ret_type = reader.GetInt32(0);
}
}
}
Please be aware to click on Write changes on SQLite browser if it is running and there are any unsaved changes!
In my case it was very stupid of me, I was making changes in SQLite browser and did not click on write changes, which locked the DB to be modified by the services. After I clicked the Write changes button, all the post request worked as expected.
According to #Rohan Shenoy in this topic: SQLite Database Locked exception

MySQL update +- amount

I got this update thing i cant figure out. The save button seems to be working, its updating the table. I cant seem to figure out the SaveToStock method. It throws me this error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''90' at line 1
I tried putting a breakpoint, got this. Break data
Save button
protected void saveButton_Click(object sender, EventArgs e)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySQLParser parser = new MySQLParser(connection);
int nonsoldamount = 0;
if (parser.hasRows("SELECT * FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'"))
{
nonsoldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'", "amount"));
if (editing)
{
oldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_sale where dpfSaleID = " + IDdpfSale, "amount"));
nonsoldamount = nonsoldamount + oldamount;
}
if (nonsoldamount < Convert.ToInt32(TextBoxAmount.Text))
{
ErrorMessage.Controls.Add(new LiteralControl("<span class=\"error\">There are only " + nonsoldamount + " in stock with the selected attributes</span>"));
return;
}
}
else
{
ErrorMessage.Controls.Add(new LiteralControl("<span class=\"error\">There are 0 in stock with the selected attributes</span>"));
return;
}
string sql_query = "";
if (editing)
{
oldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_sale where dpfSaleID = " + IDdpfSale, "amount"));
sql_query = "UPDATE dpf_sale SET orderNo = ?orderNo, fk_operatorID = ?operator, status = ?status, amount = ?amount, geometry = ?geometry, length = ?length, CPSI = ?CPSI " +
"WHERE dpfSaleID = ?IDdpfSale";
}
else
{
sql_query = "INSERT INTO dpf_sale (orderNo, fk_operatorID, amount, geometry, length, CPSI, status) " +
"VALUES (?orderNo, ?operator, ?amount, ?geometry, ?length, ?CPSI, ?status)";
}
MySqlCommand myCommand = new MySqlCommand(sql_query, connection);
myCommand.Parameters.AddWithValue("?IDdpfSale", IDdpfSale);
myCommand.Parameters.AddWithValue("?orderNo", TextBoxOrderNo.Text);
myCommand.Parameters.AddWithValue("?operator", DropDownListOperator.SelectedValue);
myCommand.Parameters.AddWithValue("?geometry", DropDownListGeometry.SelectedValue);
myCommand.Parameters.AddWithValue("?length", DropDownListLength.SelectedValue.Replace(',', '.'));
myCommand.Parameters.AddWithValue("?status", DropDownListStatus.SelectedValue);
myCommand.Parameters.AddWithValue("?CPSI", DropDownListCPSI.SelectedValue);
myCommand.Parameters.AddWithValue("?amount", TextBoxAmount.Text);
myCommand.ExecuteNonQuery();
saveToStock();
}
editing = false;
IDdpfSale = 0;
Response.Redirect("dpf_sale.aspx");
}
Stock Change
private void saveToStock()
{
connection = new MySqlConnection(connectionString);
parser = new MySQLParser(connection);
connection.Open();
string sql_stock = "";
string sql_log = "";
int newsaleID;
if (editing == true)
{
sql_stock = "UPDATE dpf_stock SET amount = amount + " + oldamount + " - " + TextBoxAmount.Text + " WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue;
sql_log = "UPDATE dpf_stock_log SET amount = " + TextBoxAmount.Text + " WHERE sale = 1 and id = " + IDdpfSale;
}
else
{
newsaleID = Convert.ToInt32(parser.readSelectCommand("SELECT MAX(dpfSaleID) id FROM dpf_sale", "id"));
sql_log = "INSERT INTO dpf_stock_log (id, assembly, sale, amount) VALUES (" + newsaleID + ", 0, 1, " + TextBoxAmount.Text + ")";
if (parser.hasRows("SELECT * FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'"))
{
sql_stock = "UPDATE dpf_stock SET amount = amount - " + TextBoxAmount.Text + " WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue;
}
else
{
return;
}
}
MySqlCommand myCommand1 = new MySqlCommand(sql_stock, connection);
myCommand1.ExecuteNonQuery();
MySqlCommand myCommand2 = new MySqlCommand(sql_log, connection);
myCommand2.ExecuteNonQuery();
connection.Close();
}

How can i get the rotated image in file

as of now i can upload my image in the database the problem is when i rotate the image.
the uploaded image is not the rotated one, its still the image that i upload that i didnt rotate.
how can i upload the rotated image ?
Stream FileStream = File.OpenRead(ServerPath + Filename);
// Stream FileStream = FileUpload1.PostedFile.InputStream;
// System.Drawing.Image.FromFile(ServerPath + Filename);
//System.Drawing.Bitmap postedimage = new System.Drawing.Bitmap(FileStream);
objImage = ScaleImage(PostedImage, 73);
if (FileType != "jpg" && FileType != "JPG")
{
objImage.Save(ServerPath + jpgFileName, ImageFormat.Jpeg);
}
else
{
//objImage.Save(ServerPath + Filename);
}
img = new byte[FileStream.Length];
contentlength = FileStream.Length;
if (contentlength > 506000)
{
ClientScript.RegisterClientScriptBlock(typeof(Page), "ClosePopup", "File is to large! Maximum size is 8kb", true);
}
else if (contentlength <= 506000)
{
//ImageConverter converter = new ImageConverter();
//byte[] bytestr = (byte[])converter.ConvertTo(objImage, typeof(byte[]));
//fs.InputStream.Read(img, 0, fs.ContentLength);
byte[] bytestr = null;
var fsm = ToStream(objImage, ImageFormat.Jpeg);
//Stream fsm = ScaleImage(objImage, 73);
BinaryReader br = new BinaryReader(fsm);
bytestr = br.ReadBytes((int)fsm.Length);
SqlCommand cmd = new SqlCommand("Select * FROM tblphotoupload where mem_cardno = '" + sParameter + "'", connection);
SqlDataReader alinan_veri3;
alinan_veri3 = cmd.ExecuteReader();
if (alinan_veri3.Read())
{
int sct = 2;
int a = Convert.ToInt32(alinan_veri3["upload_count"]);
if (sct == 2)
{
if (a >= 2) a = 2;
sql = "update tblphotoupload set mem_photo" + Convert.ToString(a + 1) + " = #img, upload_date" + Convert.ToString(a + 1) + " = '" + sDateTime + "', mem_contenttype" + Convert.ToString(a + 1) + " = '" + FileType + "', mem_photofile" + Convert.ToString(a + 1) + " = '" + Filename + "', upload_count='" + (a + 1) + "' where mem_cardno = '" + sParameter + "'";
connection.Close();
SqlConnection connection2 = new SqlConnection(ConfigurationManager.ConnectionStrings["EKConn"].ConnectionString);
connection2.Open();
SqlCommand cmd2 = new SqlCommand(sql, connection2);
cmd2.Parameters.Add(new SqlParameter("#img", bytestr));
cmd2.ExecuteNonQuery();
connection2.Close();
}
}
else
{
//string ole;
sql = "insert into tblphotoupload (mem_cardno, mem_photo1, upload_date1, upload_count, mem_contenttype1, mem_photofile1) values ('" + sParameter + "', #img, '" + sDateTime + "','1','" + FileType + "','" + Filename + "')";
connection.Close();
SqlConnection connection2 = new SqlConnection(ConfigurationManager.ConnectionStrings["EKConn"].ConnectionString);
connection2.Open();
SqlCommand cmd2 = new SqlCommand(sql, connection2);
cmd2.Parameters.Add(new SqlParameter("#img", bytestr));
cmd2.ExecuteNonQuery();
connection2.Close();
}
}
}
First of all make sure that your file is saved on the disk and then save the file into DB.
If this will not help you probably will have to either:
rotate it properly, rotation might be saved only by the image viewer without changing the image on the disk, i have encountered the issue with Picassa
rotate it in the code (rotate bytes)

Categories

Resources