Unable to send email update upon insertion of data - c#

I'm trying to allow my webapp to send an email update whenever a data is being inserted into the database like the codes i'll show below.
This is a btnAssign where it will update the relevant database table and column with data
protected void btnAssign_Click1(object sender, EventArgs e)
{
using (var connAdd = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
String assign = ddlpid1.SelectedValue;
connAdd.Open();
var sql = "Update MemberReport Set assignto ='" + assign + "', caseprogress = 'ongoing' where memberreportID='" + lbmemberreportid.Text + "'";
using (var cmdAdd = new SqlCommand(sql, connAdd))
{
cmdAdd.ExecuteNonQuery();
}
sql = "Insert into PoliceReport(memberreportid) values('" + lbmemberreportid.Text + "')";
// sql = "Update PoliceAccount Set handle ='" + assign + "' where policeid ='" + ddlpid1.SelectedValue + "' OR '" + ddlpid2.SelectedValue + "'";
using (var cmdAdd = new SqlCommand(sql, connAdd))
{
cmdAdd.ExecuteNonQuery();
}
sql = "Update PoliceAccount Set handle ='" + lbmemberreportid.Text + "' where policeid ='" + ddlpid1.SelectedValue + "'";
// sql = "Update PoliceAccount Set handle ='" + assign + "' where policeid ='" + ddlpid1.SelectedValue + "' OR '" + ddlpid2.SelectedValue + "'";
using (var cmdAdd = new SqlCommand(sql, connAdd))
{
cmdAdd.ExecuteNonQuery();
}
}
The insertion / updating of database part is working fine. When i addthe smtp codes to send email by selecting a column, it didnt work.
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
//SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
//con.Open();
// get the records matching the supplied username or email id.
cmd = new SqlCommand("select * from PoliceAccount where handle='" + lbmemberreportid.Text + "'", connAdd);
dr = cmd.ExecuteReader();
cmd.Dispose();
if (dr.HasRows)
{
dr.Read();
StringBuilder strBody = new StringBuilder();
//Passing emailid,username and generated unique code via querystring. For testing pass your localhost number and while making online pass your domain name instead of localhost path.
strBody.Append("<a>Please be notified that you've been assigned a case to handle. Please proceed to the scene with immediate effect.</a>");
// sbody.Append("&uCode=" + uniqueCode + "&uName=" + txtUserName.Text + ">Click here to change your password</a>");
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage("apr13mpsip#gmail.com", dr["email"].ToString(), "Case Pending", strBody.ToString());
//pasing the Gmail credentials to send the email
System.Net.NetworkCredential mailAuthenticaion = new System.Net.NetworkCredential("apr13mpsip#gmail.com", "Temasekpoly13");
System.Net.Mail.SmtpClient mailclient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
mailclient.EnableSsl = true;
mailclient.Credentials = mailAuthenticaion;
mail.IsBodyHtml = true;
mailclient.Send(mail);
dr.Close();
dr.Dispose();
cmd.ExecuteReader();
cmd.Dispose();
//con.Close();
lbmemberreportid.Text = "";
ddllocation.SelectedIndex = 0;
ddlnumber.SelectedIndex = 0;
ddlpid1.SelectedIndex = 0;
tbdetails.Text = "";
tbproperty.Text = "";
tbsuspect.Text = "";
ddlpid1.Visible = false;
LoadGrid();
lblmsg.ForeColor = System.Drawing.Color.Green;
lblmsg.Text = "MemberReportID" + Session["memberreportid"] + "has been successfully assigned";
}
connAdd.Close();
}
To make matter worse, the label where the message is suppose to appear did not appear. Which means after inserting the data, the code basically stop running. I added a txtFile in the link here if the code i pasted above is confusing.
I really still cant figure out why does my email not run after inserting the data into the database.
Regards.

you are reading dr["email"].ToString() but only select assignto column in your select sql statement . you can change the select sql statement to select both assignto and email columns .

Related

There is already an open Data Reader associated with this Command which must be closed first Exception

I am getting an exception called There is already an open Data Reader Associated with this command which must be closed first, I tried to look up solution on Google I tried using MARS=true in connection string and also kept everything inside USING but it didn't solved the problem.
i get an Exception in line
cm.ExecuteNonQuery();
public void UpdateActionSchedule(string actionScheduleKey, string note, string PEOPLE_CODE_ID)
{
using (SqlConnection con = new SqlConnection("server=123; database=abc; user id=qwe; password=qwe;"))
{
con.Open();
if (note == "" || note == null)
{
string UPDATE_COMPLETE = String.Format("UPDATE ACTIONSCHEDULE SET EXECUTION_DATE = '" + DateTime.Now + "', COMPLETED = 'Y', REVISION_OPID='WFLOW' where UNIQUE_KEY = '" + actionScheduleKey + "' and people_org_code_id='" + PEOPLE_CODE_ID + "'");
SqlCommand cd = new SqlCommand(UPDATE_COMPLETE, con);
cd.ExecuteNonQuery();
cd.Dispose();
}
else
{
string oriNote = "";
string GET_NOTE = String.Format("SELECT NOTE FROM ACTIONSCHEDULE WHERE people_org_code_id='{0}' and UNIQUE_KEY='{1}'", PEOPLE_CODE_ID, actionScheduleKey);
using (SqlCommand cmd = new SqlCommand(GET_NOTE, con))
{
// SqlDataReader dr = cmd.ExecuteReader();
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
oriNote = dr["NOTE"].ToString();
}
note = oriNote + " " + note;
}
//string UPDATE = String.Format("UPDATE ACTIONSCHEDULE SET Note = '" + note + "' where UNIQUE_KEY = '" + actionScheduleKey + "' and people_org_code_id='" + PEOPLE_CODE_ID + "'");
//SqlCommand cm = new SqlCommand(UPDATE, con);
//cm.ExecuteNonQuery();
//cm.Dispose();
string UPDATE_COMPLETE = String.Format("UPDATE ACTIONSCHEDULE SET EXECUTION_DATE = '" + DateTime.Now + "',Note = '" + note + "', COMPLETED = 'Y', REVISION_OPID='WFLOW' where UNIQUE_KEY = '" + actionScheduleKey + "' and people_org_code_id='" + PEOPLE_CODE_ID + "'");
SqlCommand cmw = new SqlCommand(UPDATE_COMPLETE, con);
cmw.ExecuteNonQuery();
cmw.Dispose();
}
}
}
}
}
In the second half of the code, you have a loop over cmd / dr, and inside that loop, you use cmw with ExecuteNonQuery. That means you're trying to execute two commands at once. Since you've already completed the loop: just move that code outside the using on the dr.
However, it looks like you could also do all of this in a single round trip with better SQL.

SqlCommand doesn't UPDATE and DELETE database when used in ASP.NET

I am having trouble with UPDATE and DELETE data in database when working with ASP.NET web form, the code work well with Windows form so I don't know what I did wrong. The code is suppose to update the Gridview with new edited data but when I click edit button, nothing happen to the gridview as well as the datatable.
This is just an exercise that there is no security requirement so I just want to know how to make it work first.
protected void Edit_btn_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand command = new SqlCommand();
command.Connection = sqlCon;
command.CommandText = ("UPDATE WareHouse SET [Name] = '" + Name_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Number] = '" + Number_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Storage] = '" + Storage_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Shelf] = '" + Shelf_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Brand] = '" + Brand_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM WareHouse", sqlCon);
DataTable ds = new DataTable();
ad.Fill(ds); // Fill t with data from Adapter a
GridView1.DataSource = ds; // Get data from Source t
GridView1.DataBind();
}
and for delete data
protected void Remove_btn_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand command = new SqlCommand();
command.Connection = sqlCon;
command.CommandText = "DELETE FROM WareHouse WHERE [Name] = '" + Name_Field.Text + "' AND [Number] = '" + selectedNumber + "' AND [Storage] = '" + selectedStorage + "' AND [Shelf] = '" + selectedShelf + "' AND [Brand] = '" + selectedBrand + "'";
command.ExecuteNonQuery();
clear();
showData();
}
Aside these 2 function, there are other two that do adding and searching from database which also use SqlCommand and they work fine without problem. Is there any problem with my query?
Storage, Shelf and Brand wouldn't be updated since you are updating [Number] to have the value of Number_Field.Text and then comparing with selectedName in where clause.
It will help you a great deal to put all this SQL code in SP with parameters and call it from ASP.Net code.
Ok.I also faced this issue back when I was learning ASP.NET.
But i had a little different env.
I had a datagrid to play with and any updates in datagrid content should reflect back in DB table upon clicking update button.
So I had below query to populate the grid.
Try
Dim UpperCase As String = UCase(HostnameTextBox.Text)
Dim sql As String = "select * from HOST_DETAILS where upper(HOSTNAME) like '%" + UpperCase + "%'"
da = New OracleDataAdapter(sql, conn)
ds.Clear()
da.Fill(ds, "TEST")
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
And the below one to update the table on the Update button click.
conn.Open()
Try
Dim ocb As New OracleCommandBuilder
ocb = New OracleCommandBuilder(da)
da.Update(ds, "TEST")
MessageBox.Show("Information Updated")
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
conn.Close()
Also make sure DataAdapter da is global and is defined right after public class so it can be accessed from both.
Dim da As New OracleDataAdapter
Hope this helps.

C# SQLite Database During Update

My SQLite query hangs then locks during my ExecuteNonQuery() in WriteToDB() below. It only seems to lock during the UPDATE and has no problem with the INSERT. This is only running in a single thread. When it hangs, I can see the journal being created in the SQLite database directory as if it keeps trying to write. It throws a SQLiteException with ErrorCode=5, ResultCode=Busy.
public String WriteToDB()
{
String retString = "";
//see if account exists with this email
String sql = "";
bool aExists = AccountExists();
if (!aExists)
{
sql = "INSERT INTO accounts (email, password, proxy, type, description) VALUES ('" + Email + "', '" + Password + "', '" + Proxy + "', 'dev', '" + Description + "');";
retString = "Added account";
}
else
{
sql = "UPDATE accounts SET password='" + Password + "', proxy='" + Proxy + "', description='" + Description + "' WHERE (email='" + Email + "' AND type='dev');";
retString = "Updated account";
}
using (SQLiteConnection dbconn = new SQLiteConnection("Data Source=" + Form1.DBNAME + ";Version=3;"))
{
dbconn.Open();
using (SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbconn))
{
sqlcmd.ExecuteNonQuery(); //this is where it locks. Only on update.
}
}
return retString;
}
//Test to see if Email exists as account
public bool AccountExists()
{
int rCount = 0;
String sql = "SELECT COUNT(email) FROM accounts WHERE email='" + Email + "' AND type='dev';";
using (SQLiteConnection dbconn = new SQLiteConnection("Data Source=" + Form1.DBNAME + ";Version=3;"))
{
dbconn.Open();
using (SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbconn))
{
rCount = Convert.ToInt32(sqlcmd.ExecuteScalar());
}
}
if (rCount > 0)
return true;
return false;
}
Oh man I feel dumb. I thought I posted all relevant code but all the code I posted works just fine. I had:
SQLiteDataReader dbReader = sqlcmd.ExecuteReader()
instead of
using (SQLiteDataReader dbReader = sqlcmd.ExecuteReader())
In another function. I thought it was an issue with the UPDATE because that was the place where the lock took place. Thanks for the responses and hopefully this reminds reminds everyone to use using() blocks with SQLite the first time!

my update c# code is not working,can i update two relational table at once?

i was trying to update two tables at once, but i got some syntax error on update code could u give me some idea? the insert code works perfect and i tried to copy the insert code and edit on update button clicked
here is my code
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\user\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String AR = txtAr.Text.ToString();
String Wereda = txtWereda.Text.ToString();
String Kebele = txtKebele.Text.ToString();
String House_No = txtHouse.Text.ToString();
String P_O_BOX = txtPobox.Text.ToString();
String Tel = txtTel.Text.ToString();
String Fax = txtFax.Text.ToString();
String Email = txtEmail.Text.ToString();
String Item = txtItem.Text.ToString();
String Dep = txtDep.Text.ToString();
String k = "not renwed";
String Remark = txtRemark.Text.ToString();
String Type = txtType.Text.ToString();
String Brand = txtBrand.Text.ToString();
String License_No = txtlicense.Text.ToString();
String Date_issued = txtDate.Text.ToString();
String my_querry = "update crtPro set Name='" + Name + "',AR='" + AR + "',Wereda='" + Wereda + "',Kebele='" + Kebele + "',House_No='" + House_No + "',P_O_BOX='" + P_O_BOX + "',Tel='" + Tel + "',Fax='" + Fax + "',Email='" + Email + "',Item='" + Item + "',Dep='" + Dep + "','" + k + "',Remark='" + Remark + "' where Name='" + Name + "' ";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
String my_querry1 = "SELECT max(PID) FROM crtPro";
OleDbCommand cmd1 = new OleDbCommand(my_querry1, conn);
string var = cmd1.ExecuteScalar().ToString();
String ki = txtStatus.Text.ToString();
String my_querry2 = "update crtItemLicense set PID=" + var + ",Type='" + Type + "',Brand='" + Brand + "',License_No='" + License_No + "',Date_issued='" + Date_issued + "' where PID=" + var + "";
OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);
cmd2.ExecuteNonQuery();
MessageBox.Show("Message added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
The most likely problem based on the little information given (what database are you using for example - SQL Server 2012?), is that the datatype you are providing in the concatenated dynamic sql does not match the datatype of the column in the database. You've surrounded each value with quotes - which means it will be interpreted as a varchar. If you've got a date value in the wrong format (ie if Date_Issued is a date column) or if it is a number column, then it will error.
The solution is to replace your dynamic SQL with a parameterized query eg:
String my_querry = "update crtPro set Name=#name, AR=#ar, Wereda=#Wereda, etc ...";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#myParam", Convert.ToDateTime(txtDate.Text.Trim()));
...
cmd.ExecuteNonQuery();
You can read about it further here
PS Make sure your parameters are in the same order as they are used in the SQL, because oledbcommand doesn't actually care what you call them. see here

Insert multiple value from one column attributes to another

I have this assignation function where the admin can assign a police ID to a selected memberreportID. Firstly, the admin will select the case, select the location and choose the number of officers needed for this case. For example if the admin chose 2 officers, it would then display 2 dropdownlist all binded to list down the policeID available.
protected void ddllocation_SelectedIndexChanged(object sender, EventArgs e)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "Select policeid from PoliceAccount where status ='available' and handle ='offcase' and postedto='" + ddllocation.SelectedValue + "'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
ddlpid1.Items.Clear();
ddlpid1.DataSource = ds2;
ddlpid1.DataTextField = "policeid";
ddlpid1.DataValueField = "policeid";
ddlpid1.DataBind();
ddlpid1.Items.Insert(0, new ListItem("Police ID", ""));
ddlpid1.SelectedIndex = 0;
ddlpid2.Items.Clear();
ddlpid2.DataSource = ds2;
ddlpid2.DataTextField = "policeid";
ddlpid2.DataValueField = "policeid";
ddlpid2.DataBind();
ddlpid2.Items.Insert(0, new ListItem("Police ID", ""));
ddlpid2.SelectedIndex = 0;
}
}
The first SQL command is how i insert them into the assignto column of the selected memberreportID in my database. I'm inserting both policeID i have assigned into the same column, assignto.
protected void btnAssign_Click1(object sender, EventArgs e)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
String assign = ddlpid1.SelectedValue + ", " + ddlpid2.SelectedValue + ";
connAdd.Open();
var sql = "Update MemberReport Set assignto ='" + assign + "' where memberreportID='" + lbmemberreportid.Text + "'";
using (var cmdAdd = new SqlCommand(sql, connAdd))
{
cmdAdd.ExecuteNonQuery();
}
sql = "Update PoliceAccount Set handle ='" + assign + "' where policeid ='" + ddlpid1.SelectedValue + "' OR '" + ddlpid2.SelectedValue + "'";
using (var cmdAdd = new SqlCommand(sql, connAdd))
{
cmdAdd.ExecuteNonQuery();
}
connAdd.Close();
}
}
However i'm also trying to input this policeID into a table called policeaccount by including the 2nd sql command. This policeaccount has a column called handle which is suppose to show the memberreportID he is handling at the moment. I'm trying to let each policeID's account to receive the selected memberreportID into their handle column by using the OR function. I'm pretty sure there's a OR function for sql syntax. But when i tried to insert i got this error instead
An expression of non-boolean type specified in a context where a condition is expected, near ''.
it should be as below
sql = "Update PoliceAccount Set handle ='" + assign + "' where policeid ='" + ddlpid1.SelectedValue + "' OR policeid = '" + ddlpid2.SelectedValue + "'";
Syntax is
UPDATE tblName Set col1 ='value'
WHERE col2 ='value2'
OR col2 ='value3'

Categories