I have this code for sending birthday reminder e-mail. It is executing fine for every date other than 1st jan of every year. The E-mail which is to be sent on 1st jan is actually sent on 31 jan even when in database it is 1 jan and also variable is reading it as 1 jan and not 31 jan.
Code is:
public void birthdayReminder(string month)
{
try
{
SqlConnection con;
SqlCommand cmdReminder;
SqlDataReader userReminder;
bool result = false;
string todaydate = "";
DateTime now = DateTime.Now.AddDays(1);
todaydate = now.ToString("dd", CultureInfo.InvariantCulture);
con = new SqlConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
con.Open();
cmdReminder = con.CreateCommand();
cmdReminder.CommandText = "select staffid, staffmonth, staffdate from tbstaff where staffmonth='" + month + "' and staffdate='" + todaydate + "' and staffcurrstatus='Active'";
userReminder = cmdReminder.ExecuteReader();
//userReminder.Read();
result = userReminder.HasRows;
while (userReminder.Read())
{
try
{
SqlConnection con1;
con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
con1.Open();
SqlDataReader rdr;
SqlCommand cmdRemUpd = con1.CreateCommand();
cmdRemUpd.CommandText = "select * from tbl_BirthdayReminder where staffid='" + userReminder.GetInt32(0) + "' and year='" + DateTime.Today.Year.ToString() + "'";
rdr = cmdRemUpd.ExecuteReader();
bool res = rdr.HasRows;
if(!res)
sendBirthdayEmail(userReminder.GetInt32(0));
con1.Close();
}
catch (Exception e1) { }
}
userReminder.Close();
con.Close();
}
catch (SqlException ex) { }
}
protected void sendBirthdayEmail(int id)
{
DataTable dt = new DataTable();
try
{
SqlDataAdapter adp = new SqlDataAdapter("select * from tbstaff where staffid='" + id + "'", ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
adp.Fill(dt);
string name=dt.Rows[0]["stafffname"].ToString()+' '+dt.Rows[0]["stafflname"].ToString();
string acmng = dt.Rows[0]["staffacmng"].ToString();
SqlConnection con;
SqlCommand cmd;
con = new SqlConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "select emailAddress from tbuser where firstName='" + acmng + "'";
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
string to= dr.GetValue(0).ToString();
con.Close();
Configuration configurationFile = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~\\Web.config");
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
string username = "";
string password = "";
string fromAddress = "";
int port = 0;
string host = "";
if (mailSettings != null)
{
port = mailSettings.Smtp.Network.Port;
host = mailSettings.Smtp.Network.Host;
password = mailSettings.Smtp.Network.Password;
username = mailSettings.Smtp.Network.UserName;
fromAddress = username;
}
string Aliasname = System.Configuration.ConfigurationManager.AppSettings["Alias"].ToString();
string body = "";
SmtpClient emailclient = new SmtpClient();
string path = "http://www.columbuscorp.com/sat/images/happybirthday.jpg";
body += "<html><body>";
body += "Hello <br /><br />";
body += "Please send birthday Card to " + name + " as his/her Birthday Date is on " + dt.Rows[0]["staffmonth"].ToString() + " " + dt.Rows[0]["staffdate"].ToString() + "<br/>";
body +="<img src=" + path;
body += " width=672 height=491></img>";
body += "<br /><br />Thanks from SAT Admin";
body += "</body></html>";
try
{
SqlConnection con1;
con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString);
con1.Open();
SqlCommand cmdRemUpd = con1.CreateCommand();
cmdRemUpd.CommandText = "insert into tbl_BirthdayReminder(staffid,year) values('" + id + "','" + DateTime.Today.Year.ToString() + "')";
cmdRemUpd.ExecuteNonQuery();
con1.Close();
}
catch (Exception e1) { }
The date you are looking at is always one day in the future:
DateTime now = DateTime.Now.AddDays(1);
That means on December 31st you are looking at a date in the next year. On the other hand this will use the "old" year, not the new one
cmdRemUpd.CommandText = "select * from tbl_BirthdayReminder where staffid='" + userReminder.GetInt32(0) + "' and year='" + DateTime.Today.Year.ToString() + "'";
So you are looking up a record that indeed does exist (last year's birthday reminder) hence the birthday reminder is not sent - it should be the same date as above I assume, so rather:
cmdRemUpd.CommandText = "select * from tbl_BirthdayReminder where staffid='" + userReminder.GetInt32(0) + "' and year='" + now.Year.ToString() + "'";
Related
Iam trying to get a DateTime out of an textBox, where it allready is in Format of MySql DateTime. The column in the DB is also DateTime format.
However, when i press my button to save the Dates in the DB, the whole row is gonna get emptyed.
I tried around with different formats und DataTypes in DB without anny effect
private void button4_Click(object sender, EventArgs e)
{
MySqlConnection conn = DBUtils.GetDBConnection();
conn.Open();
string startzeit = textBoxstartzeit.Text.ToString();
DateTime start = DateTime.Parse(startzeit);
string stopzeit = textBoxstopzeit.Text.ToString();
DateTime stop = DateTime.Parse(stopzeit);
string pstartzeit = textBoxstopzeit.Text.ToString();
DateTime pstart = DateTime.Parse(pstartzeit);
string pstopzeit = textBoxstopzeit.Text.ToString();
DateTime pstop = DateTime.Parse(pstopzeit);
MySqlCommand cmdnew = conn.CreateCommand();
cmdnew.CommandType = CommandType.Text;
cmdnew.CommandText = "UPDATE arbeitszeiten SET astart = '" + start + "', astop = '" + stop + "', pstart = '" + pstart + "', pstop = '" + pstop + "' WHERE id = '" + dataGridView.CurrentCell.Value + "'";
cmdnew.ExecuteNonQuery();
conn.Close();
}
private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
MySqlConnection conn = DBUtils.GetDBConnection();
conn.Open();
MySqlCommand feedstartzeit = conn.CreateCommand();
feedstartzeit.CommandText = "SELECT astart FROM arbeitszeiten WHERE id = '" + dataGridView.CurrentCell.Value + "'";
DateTime start = Convert.ToDateTime(feedstartzeit.ExecuteScalar());
textBoxstartzeit.Text = start.ToString("yyyy-MM-dd HH:mm:ss");
MySqlCommand feedstopzeit = conn.CreateCommand();
feedstopzeit.CommandText = "SELECT astop FROM arbeitszeiten WHERE id = '" + dataGridView.CurrentCell.Value + "'";
DateTime stop = Convert.ToDateTime(feedstopzeit.ExecuteScalar());
textBoxstopzeit.Text = stop.ToString("yyyy-MM-dd HH:mm:ss");
MySqlCommand feedstartpause = conn.CreateCommand();
feedstartpause.CommandText = "SELECT pstart FROM arbeitszeiten WHERE id = '" + dataGridView.CurrentCell.Value + "'";
DateTime startpause = Convert.ToDateTime(feedstartpause.ExecuteScalar());
textBoxstartpause.Text = startpause.ToString("yyyy-MM-dd HH:mm:ss");
MySqlCommand feedstoppause = conn.CreateCommand();
feedstoppause.CommandText = "SELECT pstop FROM arbeitszeiten WHERE id = '" + dataGridView.CurrentCell.Value + "'";
DateTime stoppause = Convert.ToDateTime(feedstoppause.ExecuteScalar());
textBoxstoppause.Text = stoppause.ToString("yyyy-MM-dd HH:mm:ss");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Bitte ID auswählen", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Button4 is the upload new data and the dataGridView part is filling the textBoxes with a preformated datetime that later get uploaded by button4
Your date time format should be your server date time format, if you want to use datetime then you should use datetime picker so you don't need to convert into datetime.
Allright, the by Jon Skeet suggested parametered sql request solved the problem.
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();
}
}
I need to get data from label which i had got back from previous page using Sessions from that label i need to use it to find ID for that data for example if Label contain word 'IT' it need to find its ID in database D_ID=5 code is given below
public partial class FinalFeedback1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetDataFromSession();
GetDID();
AddDynamicLabels();
}
public void GetDID()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader1 = null;
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
SqlCommand cmd1 = new SqlCommand(depart, connection);
myReader1 = cmd1.ExecuteReader(); // i am getting error here "Invalid column name 'IT'"
while (myReader1.Read())
{
Label9.Text = myReader1["D_ID"].ToString();
}
}
}
public void AddDynamicLabels()
{
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataReader myReader2 = null;
string CmdString = "Select Q_ID,Question_Data FROM QuestionTable where D_ID=" + Label9.Text + "";
SqlCommand cmd = new SqlCommand(CmdString, connection);
myReader2 = cmd.ExecuteReader();
while (myReader2.Read())
{
QID1.Text = myReader2["Q_ID"].ToString();
if (QID1.Text == ("1"))
{
Question1.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text ==("2"))
{
Question2.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("3"))
{
Question3.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("4"))
{
Question4.Text = myReader2["Question_Data"].ToString();
}
else if (QID1.Text == ("5"))
{
Question5.Text = myReader2["Question_Data"].ToString();
}
}
}
}
private void GetDataFromSession()
{
Label2.Text = Session["SNL"].ToString();
Label4.Text = Session["SNB"].ToString();
Label6.Text = Session["EMPID"].ToString();
Label8.Text = Session["DNAME"].ToString();
}
}
Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to this line
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
See the single quotes in the second line. Your string value is not in single quotes and this is the reason.
EDIT: Your code is open for SQL Injection Attack. You should use the SqlParameter instead of concatenating the query.
For More reading you can use this link:
http://www.w3schools.com/sql/sql_injection.asp
As simple as missing the quotations of your sql.
sql-> "where D_Name = 'somevalue'
... So the fix for your code would be
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
Change this line.
string depart = "select D_ID from Department where D_Name= " + Label8.Text + "";
to
string depart = "select D_ID from Department where D_Name like '" + Label8.Text + "'";
or faster search
string depart = "select D_ID from Department where D_Name= '" + Label8.Text + "'";
or for search similar string change to
string depart = "select D_ID from Department where D_Name like '%" + Label8.Text + "%'";
string c = "";
string s = "";
string d = "";
string t = "";
if (CarNameCombo.SelectedIndex >= 0 && SourceCombo.SelectedIndex >= 0 && DestinationCombo.SelectedIndex >= 0 && NumberOfPassengers.SelectedIndex >= 0)
c = CarNameCombo.Items[CarNameCombo.SelectedIndex].ToString();
s = SourceCombo.Items[SourceCombo.SelectedIndex].ToString();
d = SourceCombo.Items[DestinationCombo.SelectedIndex].ToString();
t = NumberOfPassengers.Items[NumberOfPassengers.SelectedIndex].ToString();
MessageBox.Show(""+c+s+d+t);
string date = dateTimePicker1.Text;
string date1 = dateTimePicker2.Text;
string x = richTextBox1.Text;
string y = richTextBox2.Text;
MessageBox.Show("" +date +date1);
SqlConnection conn = new SqlConnection("Data Source=PRAVEEN\\SQLEXPRESS;Initial Catalog=travelbooking;Integrated Security=True");
SqlCommand cmd = new SqlCommand("insert into BookDetails(CarName,Source,Destination,Date,FromAddress,ToAddress,Time,Numberpassengers)VALUES('" + c + "','" + s + "','" + d + "','" + date + "','" + x + "','" + y + "' '"+ date1 + "','" + t + "'", conn)");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
//cmd.Parameters.AddWithValue("#CarName", c);
//cmd.Parameters.AddWithValue("#Source", s);
//cmd.Parameters.AddWithValue("#Destination", d);
//cmd.Parameters.AddWithValue("#Date", date);
//cmd.Parameters.AddWithValue("#FromAddress", richTextBox1.Text);
//cmd.Parameters.AddWithValue("#ToAddress", richTextBox2.Text);
//cmd.Parameters.AddWithValue("#Time", date1);
//cmd.Parameters.AddWithValue("#Numberpassengers", t);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
I am working in a windows forms project with c# and ado. I get and exception thrown saying cannot convert date and or time from character to string, i specified the datatype in my database as time(7) and date as date....do i need to do something extra??? and this is the meesage "Conversion failed when converting date and/or time from character string"under label sql exception was unhandled.
find this
namespace First_Csharp_app
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String gender; //we have to define this
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(str);
String str = "server=MUNESH-PC;database=windowapp;UID=sa;password=123";
String query = "insert into data (E.id,name,surname,age,gender,DOB) values ('"+this.eid_txt.text+"','"+this.nametxt.text+"','"+this.surname_txt.text+"','"+this.age_txt.text+"' , '"+this.gender+"' , '"+this.DateTimePicker1.Text+"')";
SqlCommand cmd = new sqComamnd(query,con);
SqlDataReader dbr;
try
{
con.open();
dbr = cmd.ExecuteReader();
MessageBox.Show("saved");
while(dbr.read())
{
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
private void rediobutton1.checked(object sender, EventArgs e)
{
gender = "male";
}
private void rediobutton1.checked(object sender, EventArgs e)
{
gender = "female";
}
}
}
Use the DateTimePicker.Value instead of DateTimePicker.Text and create a parameterized query that accepts this DateTime value instead of a text string, eg:
DateTime date = dateTimePicker1.Value;
DateTime date1 = dateTimePicker2.Value;
...
SqlCommand cmd = new SqlCommand(
"insert into BookDetails(CarName,Source,Destination,Date,FromAddress,ToAddress,Time,Numberpassengers) " +
" VALUES(#CarName,#Source,#Destination,#Date,#FromAddress,#ToAddress, " +
" #Time,#NumPassengers)", conn)");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#CarName", c);
cmd.Parameters.AddWithValue("#Source", s);
cmd.Parameters.AddWithValue("#Destination", d);
cmd.Parameters.AddWithValue("#Date", date);
cmd.Parameters.AddWithValue("#FromAddress", richTextBox1.Text);
cmd.Parameters.AddWithValue("#ToAddress", richTextBox2.Text);
cmd.Parameters.AddWithValue("#Time", date1);
cmd.Parameters.AddWithValue("#Numberpassengers", t);
The original code failed because you passed a date formatted in an arbitrary format instead of an actual date value. SQL Server tried to interpret this string using the column's collation which didn't match the end user's locale.
I am trying to get date from my database into a string and comparing it with the today's date to perform some operation.
What I did as a solution but still the label isn't displaying the messages.
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("Files/" + FileName));
string FilePath = "Files/" + FileName;
//SqlCommand cmd = new SqlCommand();
DAL obj = new DAL();
using (SqlConnection conn = obj.openCon())
{
String sql = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like '" + AssignmentTitle + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
DateTime duedate = new DateTime() ;
if (dr != null && dr.HasRows)
{
while (dr.Read())
{
duedate = dr.GetDateTime(0);
}
dr.Close();
// now check if today greater than due date and update
if (duedate != null && today.Date > duedate)
{
sql = "Insert into tbl_AssignmentSubmit( Name ,AridNumber, Shift , Degree , Course , FileName ,FilePath ) values ('" + txt_Name.Text + "' , '" + txt_AridNumber.Text + "', '" + shift + "', '" + Degree + "', '" + Course + "','" + FileName + "','" + FilePath + "')";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
else
{
lbl_uploaded.Text = "Assignment can not be Submitted.You crossed the due date.";
}
}
}
}
You have to get DueDate from tbl_AssignmentUpload1 .
For example :
string strSQL = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like #AssignmentTitle ";
(SqlCommand myCommand = new SqlCommand(strSQL, cnn)) // Cnn is your sql connection
{
myCommand.Parameters.AddWithValue("#AssignmentTitle", AssignmentTitle );
using (SqlDataReader reader = myCommand.ExecuteReader())
{
while (reader.Read())
{
DateTime today1 = Convert.ToDateTime(reader["DueDate "].ToString());
}
}
}
After this you can do your insert statement
Try something like this. Ok updated with the fix for duedate.
using (SqlConnection conn = SQL.GeSQLConnection())
{
String sql = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like '" + AssignmentTitle + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
DateTime duedate = new DateTime();
if (dr != null && dr.HasRows)
{
while (dr.Read())
{
duedate = dr.GetDateTime(0);
}
dr.Close();
// now check if today greater than due date and update
if(duedate != null && DateTime.Today > duedate)
{
sql = "Insert into tbl_AssignmentSubmit( Name ,AridNumber, Shift , Degree , Course , FileName ,FilePath ) values ('" + txt_Name.Text + "' , '" + txt_AridNumber.Text + "', '" + shift +"', '" + Degree + "', '" + Course + "','" + FileName + "','" + FilePath + "')";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
else
{
lbl_uploaded.Text = "Assignment can not be Submitted.You crossed the due date.";
}
}
else
{
lbl_uploaded.Text = "No Due date was selected for the given assesment title";
}
}