inertion of date time combobox value into database - c#

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.

Related

Need to find ID number from database using string in c#

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 + "%'";

input string was not in a correct format c# datetimepicker

private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (_action == "edit")
{
update(_id, int.Parse(cbSupplier.ValueMember), dtpTRXdate.Value.ToString("yyyy-MM-dd"), dtpDUEdate.Value.ToString("yyyy-MM-dd"), txtRemarks.Text.ToString(), _conn);
}
else
{
insert(int.Parse(cbSupplier.ValueMember), dtpTRXdate.Value.ToString("yyyy-MM-dd"), dtpDUEdate.Value.ToString("yyyy-MM-dd"), txtRemarks.Text.ToString(), _conn);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void insert(int sup_ID, string TRX_date, string DUE_date, string remarks, MySqlConnection conn)
{
MessageBox.Show(sup_ID.ToString() + " " + TRX_date + " " + DUE_date + " " + remarks);
MySqlCommand command = new MySqlCommand();
command.Connection = conn;
command.CommandText = "INSERT INTO PO_HEADER VALUES(null," + sup_ID + ",'" + TRX_date + "','" + DUE_date + "','" + remarks + "')";
command.ExecuteNonQuery();
}
public void update(int id, int sup_id, string trx_date, string due_date, string remarks, MySqlConnection conn)
{
MySqlCommand command = new MySqlCommand();
command.Connection = conn;
command.CommandText = "UPDATE PO_HEADER SET SUPPLIER_ID=" + sup_id + ", TRX_DATE='" + trx_date + "', DUE_DATE='" + due_date + "', REMARKS='" + remarks + "' WHERE ID=" + id;
command.ExecuteNonQuery();
}
dtpTRXdate it's datetimepicker
the problem at : dtpTRXdate.Value.ToString("yyyy-MM-dd") and dtpDUEdate.Value.ToString("yyyy-MM-dd")
when i click button save and run the function, it say "input string was not in a correct format"
i messagebox the string it's true, example : "2012-12-12"
have any idea???
Problem : You are sending the Date value selected from DateTimePicker control after converting into string as yyyy-MM-dd, but in database table the datatype might be Date so it takes Date and Time both.
Solution : you need to convert Date Selected from DateTimePicker control into into Date and Time instead of converting into Date only.
Try This:
dtpTRXdate.Value.ToString("yyyy-MM-dd HH:mm:ss")
Suggestion : by using parameterised queries you do not need to worry about the types being passed as it will be taken care by default.
by using parameterised queries you can avoid SQL Injection Attacks
Complete Code: using parameterised queries
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (_action == "edit")
{
update(_id, int.Parse(cbSupplier.ValueMember), dtpTRXdate.Value, dtpDUEdate.Value, txtRemarks.Text.ToString(), _conn);
}
else
{
insert(int.Parse(cbSupplier.ValueMember), dtpTRXdate.Value, dtpDUEdate.Value, txtRemarks.Text.ToString(), _conn);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void insert(int sup_ID, DateTime TRX_date, DateTime DUE_date, string remarks, MySqlConnection conn)
{
MessageBox.Show(sup_ID.ToString() + " " + TRX_date.ToShortDateSTring() + " " + DUE_date.ToShortDateSTring() + " " + remarks);
MySqlCommand command = new MySqlCommand();
command.Connection = conn;
command.CommandText = "INSERT INTO PO_HEADER VALUES(#value1,#sup_ID,#TRX_date,# DUE_date,#remarks)";
command.Parameters.AddWithValue("#value1",DBNull.Value);
command.Parameters.AddWithValue("#sup_ID",sup_ID);
command.Parameters.AddWithValue("#TRX_date",TRX_date);
command.Parameters.AddWithValue("#DUE_date",DUE_date);
command.Parameters.AddWithValue("#remarks",remarks);
command.ExecuteNonQuery();
}
public void update(int id, int sup_id, string trx_date, string due_date, string remarks, MySqlConnection conn)
{
MySqlCommand command = new MySqlCommand();
command.Connection = conn;
command.CommandText = "UPDATE PO_HEADER SET SUPPLIER_ID=#sup_id,TRX_DATE=#trx_date,DUE_DATE=#due_date,REMARKS=#remarks WHERE ID=#id";
command.Parameters.AddWithValue("#sup_ID",sup_ID);
command.Parameters.AddWithValue("#trx_date",trx_date);
command.Parameters.AddWithValue("#due_date",due_date);
command.Parameters.AddWithValue("#remarks",remarks);
command.Parameters.AddWithValue("#sup_ID",id);
command.ExecuteNonQuery();
}

How to achieve a search for a certain year & amount using C#

Here is a small demo of a SQL database, where one can add, update delete members from a SQL server.
There are two tables in a single SQL Server DB, one is “members” second is “overview”.
In members there is distinct ID column and members personal info like name, address telephone etc.
In overview there are only three columns which are dID, year & amount.
There is one single windows form, language is c# and project is built in Visual Studio 2010, and of course data base in SQL Server 2010.
The windows form has a “reset, insert, update & delete” buttons.
There is one more button besides the dID text box where a distinct ID can be inserted and after clicking Search button the last entry made about the member shows by filling all the text boxes where name address telephone appear. This serves the function that member full info can be seen and changes can be made or can be removed from dB.
There are two text boxes in particular, which are Year & Amount, which shows that the member has paid a certain amount for the certain year.
But as I mentioned in the text boxes you can only see the last entry made. What function I want to achieve is that after inserting dID of person x I could only in the year text box able to insert lets say any previous year and the press search which should like normally fill all the text boxes with info, and in the amount text box should show me the entry from the dB that according to the year I entered how much amount is there or there is nothing which means that may be member has not paid for a certain year.
I need help in achieving this logic programmatically therefore I would like to request assistance.
The present program is as follows :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SQLDatabase
{
public partial class SQLDBDisplay : Form
{
SqlConnection con = new SqlConnection("Data Source=JG-PC\\SQLEXPRESS;Initial Catalog=TEST;Integrated Security=True");
public SQLDBDisplay()
{
InitializeComponent();
}
SqlDataAdapter da;
DataSet ds = new DataSet();
private void btnSearch_Click(object sender, EventArgs e)
{
SqlDataReader reader;
SqlCommand cmd = new SqlCommand();
try
{
string sql = "SELECT * FROM members where dID = '" + txtdID.Text + "' ";
txtYear.Text = sql;
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtID.Text = reader["ID"].ToString();
txtName.Text = reader["Name"].ToString();
txtAddress.Text = reader["Address"].ToString();
txtMobile.Text = reader["Mobile"].ToString();
txtEmail.Text = reader["Email"].ToString();
txtdID.Text = reader["dID"].ToString();
}
con.Close();
sql = "SELECT * FROM Overview where dID = '" + txtdID.Text + "' ";
txtYear.Text = txtYear.Text + " : " + sql;
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtYear.Text = reader["Year"].ToString();
txtAmount.Text = reader["Amount"].ToString();
txtdID.Text = reader["dID"].ToString();
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnReset_Click(object sender, EventArgs e)
{
txtdID.Text = ""; txtName.Text = ""; txtAddress.Text = "";
txtMobile.Text = ""; txtEmail.Text = ""; txtYear.Text = "";
txtAmount.Text = "";
}
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
string Sql = "INSERT INTO members (dID, Name, Address, Email, Mobile) VALUES ( '" + txtdID.Text+ "','" + txtName.Text + "','"
+ txtAddress.Text + "', '" + txtEmail.Text + "', '" + txtMobile.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "INSERT INTO Overview (dID, Year, Amount) VALUES ('"+ txtdID.Text +"' ,'" + txtYear.Text + "','" + txtAmount.Text +
"')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Scuessfully!!!");
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "Update members set Name = '" + txtName.Text + "', Address = '" + txtAddress.Text + "', Email = '" +
txtEmail.Text + "', Mobile = '" + txtMobile.Text + "' WHERE dID = '"
+ txtdID.Text + "'";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "Update overview set Year = '" + txtYear.Text + "', Amount = '" + txtAmount.Text + "' WHERE dID = '"+ txtdID.Text+"'";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Data Scuessfully Updated");
con.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "DELETE FROM members WHERE dID = '"+ txtdID.Text +"'";
con.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "DELETE FROM overview WHERE dID = '" + txtdID.Text + "'";
cmd.ExecuteNonQuery();
da = new SqlDataAdapter(cmd);
MessageBox.Show("Record Scuessfully Deleted !");
con.Close();
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
} }
To add a solution to the comments people have made regarding parameters and sql injection, i tend to use the code below when connecting to any database.
using(SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING"))
{
try
{
using(SqlCommand command = new SqlCommand())
{
command.CommandText = "SELECT * FROM members where dID = #MyId";
command.Connection = connection;
// Set the SqlDbType to your corresponding type
command.Parameters.Add("#MyId", SqlDbType.VarChar).Value = txtdID.Text;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtID.Text = reader["ID"].ToString();
txtName.Text = reader["Name"].ToString();
txtAddress.Text = reader["Address"].ToString();
txtMobile.Text = reader["Mobile"].ToString();
txtEmail.Text = reader["Email"].ToString();
txtdID.Text = reader["dID"].ToString();
}
}
}
finally
{
connection.Close();
}
}
You need to group your SELECT on the Amount column. A simple answer to your question would be to modify your second select query like this:
sql = "SELECT Year, dID, SUM(Amount) as Amount FROM Overview where dID = '" + txtdID.Text + "' AND Year = " + txtYear.Text + "GROUP BY amount";
Probably, you would like to use the txtYear.Text value for an SQL parameter, so:
txtYear.Text = sql;
and
txtYear.Text = txtYear.Text + " : " + sql;
don't make too much sense in your code.
Of course, this is not the correct way, as it is prone to SQL Injection. I would recommend you to use SQL Stored Procedures, which are definitely safer regarding SQL Injection.
Another improvement to the code quality would be that you should use using statements to enclose the SQLConnection, SQLCommand and SQLDataReader objects initializations.

Data gets Truncated from database

I am designing a Window based application in C# using VS2010 and SqlServer2008-r2. I am
using a service Based Database(.mdf),in it there is a table having four fields, if i Store
data in the table and close the application and re-run the application the data gets Lost.
Why so and how to get rid of it.
I am Using Following routine for saving
private void Save(object sender, EventArgs e)
{
Program.connection.Close();
bool k = srchpreventry();
try
{
if (k)
{
string query = " update orderform set Enrolment_Expected = " + textBox2.Text + ", Stock_on_Hand=" + textBox3.Text + ", Number_Required = "+ textBox4.Text + " where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
cmd.ExecuteNonQuery();
Program.connection.Close();
}
else
{
// Program.connection.Open();
string query = "insert into orderform(Name,Enrolment_Expected,Stock_on_Hand,Number_Required) values('" + textBox1.Text + "', '" + textBox2.Text + "', ' " + textBox3.Text + "',' " + textBox4.Text + "')";
SqlCommand cmd = new SqlCommand(query, Program.connection);
cmd.ExecuteNonQuery();
Program.connection.Close();
}
}
catch (Exception ae)
{
string str = ae.ToString();
MessageBox.Show(str);
}
finally
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox1.Enabled = false;
textBox2.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
Program.connection.Close();
}
}
public bool srchpreventry()
{
Program.connection.Open();
string query = " Select name from orderform where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read() == true)
{
dtr.Close();
return true;
}
else
{
dtr.Close();
return false;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Program.connection.Close();
Program.connection.Open();
string query = " Select * from orderform where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read() == true)
{
textBox2.Text = dtr[1].ToString();
textBox3.Text = dtr[2].ToString();//GetString(2);
textBox4.Text = dtr[3].ToString();
}
else
{
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
public static SqlConnection connection = null;
static string appath = Library_Records.Program.app_path;
string connectionstring = string.Format(#"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;User Instance=True", appath);
static string dbfiles = null;
internal static string app_path
{
get { return dbfiles = "|Datadirectory|\\records.mdf"; }
}
/*******************datagrid code********************/
Program.connection.Open();
string query = "select * from orderform";
SqlDataAdapter MyDA = new SqlDataAdapter();
MyDA.SelectCommand = new SqlCommand(query, Program.connection);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
Check to see if you can increase the characters allowed in the column for example nvarchar(max) cause now it could be nvarchar(200) - this is just an example
In Visual Studio?
You are not by chane having VIsual Studio load the same empty database again every time you start debug?
and close the application and re-run the application the data gets Lost.
Either someone ignores errors that get thrown on insert, does not commit a transaction or tvisal studio just ocpies the same rdatabase template into the directory every time you start.
I strongly (emphasis on strongly) suggest that you start using stored procedures (either in code or in the database), but besides that.. you don't start a transaction or something similar?
Or post the Program.Connection class code into the question.

code executing date 1st jan on 31st jan DateTime.Add

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() + "'";

Categories

Resources