<asp:TextBox ID="txtstartdate" class="form-control" autocomplete="off" CssClass="datepicker1" runat="server"></asp:TextBox>
<asp:TextBox ID="txtenddate" class="form-control" autocomplete="off" CssClass="datepicker2" runat="server"></asp:TextBox>
<asp:TextBox id="txtreason" TextMode="multiline" runat="server" />
<asp:Button ID="submit" CssClass="login" runat="server" Text="Submit" OnClick="Submit_click" />
Using the Submit_click I want to insert data into table between the 2 dates selected on txtstartdate and txtenddate. txtreason should repeat for all the dates on the table.
For example if select dates 07/30/2018 and 08/04/2018 on txtstartdate and txtenddate and enter "hello" as reason for txtreason, I should get all the dates between 07/30/2018 and 08/04/2018 in the ldate column on the data table and hello should be repeated on reason column for 6 times for each individual dates.
The below method works like a charm if you change date format.
protected void Submit_click(object sender, EventArgs e)
{
DateTime startdate = Convert.ToDateTime(txtstartdate.Text);
DateTime enddate = Convert.ToDateTime(txtenddate.Text);
for (DateTime date = startdate; date <= enddate; date = date.AddDays(1))
{
try
{
string MyConString = "SERVER=localhost;DATABASE=mydb;UID=myid;PASSWORD=abc123;";
MySqlConnection connection = new MySqlConnection(MyConString);
string cmdText = "INSERT INTO approved(agentlogin ,leavetype ,date ,time, reason)VALUES ( #login, #type, #date, 'Full day', #reason)";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.Parameters.AddWithValue("#login", Label1.Text);
cmd.Parameters.AddWithValue("#type", ddlleavetype.Text);
cmd.Parameters.AddWithValue("#date", date);
cmd.Parameters.AddWithValue("#reason", txtreason.Text);
connection.Open();
int result = cmd.ExecuteNonQuery();
connection.Close();
//lblError.Text = "Data Saved";
}
catch (Exception)
{
Console.Write("not entered");
//lblError.Text = ex.Message;
}
}
}
This is why you should use models, and utilise the proper types rather than keep everything a string.
While not perfect, a step in the right direction would be something like this :
(Keep in mind that i haven't solved every single problem. there is plenty of room for improvement)
public class DateRangeModel
{
public DateTime From {get; set;}
public DateTime To {get; set;}
public IEnumerable<DateTime> DaysInRange {
get{
for(DateTime date = StartDate; date.Date <= EndDate.Date; date = date.AddDays(1))
{
yield date;
}
}
}
public DateRangeModel(string from, string to)
{
From = GetDate(from);
To = GetDate(to);
}
private static DateTime GetDate(string string_date)
{
DateTime dateValue;
if (DateTime.TryParse(string_date, out dateValue))
return dateValue;
else
throw new Exception("Unable to convert '{0}' to a date.", string_date);
}
}
protected void Submit_click(object sender, EventArgs e)
{
DateRangeModel dateRange = new DateRangeModel(txtstartdate.Text, txtenddate.Text);
OleDbConnection scn = new OleDbConnection();
scn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=/mysource;";
foreach(var dt in dateRange.DaysInRange)
{
OleDbCommand scmd = new OleDbCommand("Insert query", scn);
scmd.CommandType = CommandType.Text;
scmd.Parameters.Clear();
scmd.Parameters.AddWithValue("#date1", dt);
scmd.Parameters.AddWithValue("reason", txtreason);
//etc (finish your insert stmt here).
}
}
Use the below method to change the date format. Hope this helps
protected void Submit_click(object sender, EventArgs e)
{
DateTime startdate = Convert.ToDateTime(txtstartdate.Text);
DateTime enddate = Convert.ToDateTime(txtenddate.Text);
for (DateTime date = startdate; date <= enddate; date = date.AddDays(1))
{
try
{
var shtdate = date.ToShortDateString();
string MyConString = "SERVER=localhost;DATABASE=mydb;UID=myid;PASSWORD=abc123;";
MySqlConnection connection = new MySqlConnection(MyConString);
string cmdText = "INSERT INTO approved(agentlogin ,leavetype ,date ,time, reason)VALUES ( #login, #type, #date, 'Full day', #reason)";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.Parameters.AddWithValue("#login", Label1.Text);
cmd.Parameters.AddWithValue("#type", ddlleavetype.Text);
cmd.Parameters.AddWithValue("#date", shtdate);
cmd.Parameters.AddWithValue("#reason", txtreason.Text);
connection.Open();
int result = cmd.ExecuteNonQuery();
connection.Close();
//lblError.Text = "Data Saved";
}
catch (Exception)
{
Console.Write("not entered");
//lblError.Text = ex.Message;
}
}
}
Related
I'm creating a leave calendar for employees, And for that I'm populating some data onto the calendar using dataset, but it takes too long to load the data.
I'm using multiple MySqlDataReader and connections to read the data from MySql table for each row of the calendar table. Maybe using multiple connections and readers might be the cause of slowing down but I'm not sure. The below is the code I use to populate the data.
class Sample
{
public DateTime Date { get; set; }
public string SlotAvailable { get; set; }
public string Pending { get; set; }
public string HeadCount { get; set; }
}
DateTime firstDate { get; set; }
DateTime lastDate { get; set; }
List<Sample> samples = new List<Sample>();
protected DataSet dsleaveplanner;
protected void FillLeaveplannerDataset()
{
cal2.VisibleDate = cal2.TodaysDate;
DateTime firstDate = new DateTime(cal2.VisibleDate.Year, cal2.VisibleDate.Month, 1).AddDays(-6);
DateTime lastDate = new DateTime(cal2.VisibleDate.Date.AddMonths(1).Year, cal2.VisibleDate.Date.AddMonths(1).Month, 1).AddDays(7);
dsleaveplanner = GetCurrentMonthData(firstDate, lastDate);
}
protected DateTime GetFirstDayOfNextMonth()
{
int monthNumber, yearNumber;
if (cal2.VisibleDate.Month == 12)
{
monthNumber = 1;
yearNumber = cal2.VisibleDate.Year + 1;
}
else
{
monthNumber = cal2.VisibleDate.Month + 1;
yearNumber = cal2.VisibleDate.Year;
}
DateTime lastDate = new DateTime(yearNumber, monthNumber, 1);
return lastDate;
}
protected DataSet GetCurrentMonthData(DateTime firstDate, DateTime lastDate)
{
string site = lblsite.Text;
string skill = lblskill.Text;
string shift = lblshift.Text;
DataSet dsMonth = new DataSet();
string MyConString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(MyConString);
string caldate = "Select * From setshrinkage Where date >= #firstDate And date <= #lastDate And site=#site And skill=#skill And shift=#shift Group By date";
MySqlCommand cmd = new MySqlCommand(caldate, con);
cmd.Parameters.AddWithValue("#firstDate", firstDate);
cmd.Parameters.AddWithValue("#lastDate", lastDate);
cmd.Parameters.AddWithValue("#site", site);
cmd.Parameters.AddWithValue("#skill", skill);
cmd.Parameters.AddWithValue("#shift", shift);
MySqlDataAdapter mysqlDataAdapter = new MySqlDataAdapter(cmd);
try
{
mysqlDataAdapter.Fill(dsMonth);
con.Close();
}
catch { }
return dsMonth;
}
public void caldisp(DayRenderEventArgs e)
{
Environment.NewLine.ToString();
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p></p>Slot available:"));
e.Cell.Controls.Add(new LiteralControl(samples.Where(x => x.Date == e.Day.Date).FirstOrDefault().SlotAvailable.ToString()));
e.Cell.Controls.Add(new LiteralControl("<p></p>Pending:"));
e.Cell.Controls.Add(new LiteralControl(samples.Where(x => x.Date == e.Day.Date).FirstOrDefault().Pending.ToString()));
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
DateTime nextDate;
//e.Day.IsSelectable = false;
if (dsleaveplanner != null)
{
foreach (DataRow dr in dsleaveplanner.Tables[0].Rows)
{
nextDate = (DateTime)dr["date"];
var hcount = (dr["headCount"].ToString());
Int32 hcount1 = Convert.ToInt32(hcount);
string MyConString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection conn = new MySqlConnection(MyConString);
string cntdate = "SELECT COUNT(date) FROM approved WHERE date = #date And site=#site And skill=#skill And shift=#shift And status=#status";
string cntdate2 = "SELECT COUNT(date) FROM approved WHERE date = #date And site=#site And skill=#skill And shift=#shift And status=#status";
MySqlCommand cmd2 = new MySqlCommand(cntdate, conn);
MySqlCommand cmd3 = new MySqlCommand(cntdate2, conn);
cmd2.Parameters.AddWithValue("#date", nextDate);
cmd2.Parameters.AddWithValue("#site", lblsite.Text);
cmd2.Parameters.AddWithValue("#skill", lblskill.Text);
cmd2.Parameters.AddWithValue("#shift", lblshift.Text);
cmd2.Parameters.AddWithValue("#status", "auto-approved");
cmd3.Parameters.AddWithValue("#date", nextDate);
cmd3.Parameters.AddWithValue("#site", lblsite.Text);
cmd3.Parameters.AddWithValue("#skill", lblskill.Text);
cmd3.Parameters.AddWithValue("#shift", lblshift.Text);
cmd3.Parameters.AddWithValue("#status", "pending");
string chklog = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd1 = new MySqlCommand(chklog, conn);
cmd1.Parameters.AddWithValue("#date", nextDate);
cmd1.Parameters.AddWithValue("#login", Label1.Text);
cmd1.Parameters.AddWithValue("#stat", "auto-approved");
conn.Open();
string count = cmd2.ExecuteScalar().ToString();
string count2 = cmd3.ExecuteScalar().ToString();
var slot2 = Convert.ToInt32(count);
Int32 slot3 = hcount1 - slot2;
string slot4 = slot3.ToString();
MySqlDataReader dr1 = cmd1.ExecuteReader();
MySqlConnection con = new MySqlConnection(MyConString);
string chklog1 = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd4 = new MySqlCommand(chklog1, con);
cmd4.Parameters.AddWithValue("#date", nextDate);
cmd4.Parameters.AddWithValue("#login", Label1.Text);
cmd4.Parameters.AddWithValue("#stat", "pending");
con.Open();
MySqlDataReader dr2 = cmd4.ExecuteReader();
MySqlConnection con2 = new MySqlConnection(MyConString);
string chklog2 = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd5 = new MySqlCommand(chklog2, con2);
cmd5.Parameters.AddWithValue("#date", nextDate);
cmd5.Parameters.AddWithValue("#login", Label1.Text);
cmd5.Parameters.AddWithValue("#stat", "rejected");
con2.Open();
MySqlDataReader dr3 = cmd5.ExecuteReader();
MySqlConnection con3 = new MySqlConnection(MyConString);
string chklog3 = "SELECT date FROM approved WHERE date = #date And agentlogin=#login And status=#stat";
MySqlCommand cmd6 = new MySqlCommand(chklog3, con3);
cmd6.Parameters.AddWithValue("#date", nextDate);
cmd6.Parameters.AddWithValue("#login", Label1.Text);
cmd6.Parameters.AddWithValue("#stat", "agent-withdrawn");
con3.Open();
MySqlDataReader dr4= cmd6.ExecuteReader();
if (nextDate == e.Day.Date)
{
if (dr1.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.LightGreen;
}
else if (dr2.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.Gold;
}
else if (dr3.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.Tomato;
}
else if (dr4.HasRows)
{
e.Cell.BackColor = System.Drawing.Color.DarkTurquoise;
}
}
conn.Close();
con.Close();
con2.Close();
con3.Close();
samples.Add(new Sample { Date = nextDate, SlotAvailable = slot4, Pending = count2 });
}
if (samples.Any(x => x.Date == e.Day.Date))
{
string weekoff = lblweekoff.Text;
List<string> offday = (lblweekoff.Text).Split(',').ToList();
if (offday.Contains(e.Day.Date.ToString("ddd")))
{
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p>Week-Off </p>"));
}
else
{
caldisp(e);
}
}
else
{
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p>Target not set! </p>"));
}
}
}
How can I make this process faster? Any help is appreciated, Thanks in advance!
You have 6 SQL queries into foreach statement, if you have 10 rows in dsleaveplanner the program will execute 60 SQL queries. this number of SQL queries will have a negative impact on performance.
try to retrieve all data before your foreach statement and stock data into lists (memory) then use it within your foreach
I have an sql table that returns financial year start_date and end_date, so now i want to use that query to dropdownlist of months starting from april until march.
And based on the selected month i get the revenue for that month.So the query for calculating financial year only return 2018/04/01 as start_date and 2019/03/31 as end_date, so bare in mind it's not months, just a date .Of course i will be connected to a server and choose my database and table. see what i tried below.
public class Fyear
{
public string FiscalY_Start { get; set; }
public string FiscalY_End { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
//Data Source=cntrra02-sql-rs;Initial Catalog=Training_Database;Integrated Security=True
DateTime start_date;
DateTime end_date;
List<Fyear> list = new List<Fyear>();
if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection(#"Data Source=serv_name;Initial Catalog=Database_name;Integrated Security=True");
SqlCommand cmd = new SqlCommand(#"SELECT [ST_FI], [END_FY] FROM [FiscalYear]", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
start_date = Convert.ToDateTime(rdr["ST_FI"]);
end_date = Convert.ToDateTime(rdr["END_FY"]);
//DropDownList1.Items.Add(start_date.ToString());
//int count = 0;
while (start_date <= end_date)
{
//count++;
//list.Add(new Fyear{ FiscalY_Start = start_date.ToString("MMMM")});
start_date = start_date.AddMonths(1);
DropDownList1.Items.Add(start_date.ToString());
}
}
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
// DropDownList1.DataSource = dt;
// DropDownList1.DataBind();
}
I have an asp calendar linked to datasource and it fetches the count of number of times a date has repeated in the data table and display it on the calendar. but if there are 2 dates of the same month is on the mysql table then the labels appears twice and thrice if there are 3 dates and so on as shown in the image below.
The code for this is shown below
protected void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
cal2.VisibleDate = DateTime.Today;
FillLeaveplannerDataset();
}
}
protected void FillLeaveplannerDataset()
{
cal2.VisibleDate = cal2.TodaysDate;
DateTime firstDate = new DateTime(cal2.VisibleDate.Year, cal2.VisibleDate.Month, 1).AddDays(-6);
DateTime lastDate = new DateTime(cal2.VisibleDate.Date.AddMonths(1).Year, cal2.VisibleDate.Date.AddMonths(1).Month, 1).AddDays(7);
dsleaveplanner = GetCurrentMonthData(firstDate, lastDate);
}
protected DateTime GetFirstDayOfNextMonth()
{
int monthNumber, yearNumber;
if (cal2.VisibleDate.Month == 12)
{
monthNumber = 1;
yearNumber = cal2.VisibleDate.Year + 1;
}
else
{
monthNumber = cal2.VisibleDate.Month + 1;
yearNumber = cal2.VisibleDate.Year;
}
DateTime lastDate = new DateTime(yearNumber, monthNumber, 1);
return lastDate;
}
protected DataSet GetCurrentMonthData(DateTime firstDate, DateTime lastDate)
{
DataSet dsMonth = new DataSet();
MySqlConnection con = new MySqlConnection("Server=localhost;Database=mydb;Uid=myid;Pwd=abc123;");
string caldate = "Select date From approved Where date >= #firstDate And date <= #lastDate Group By date";
MySqlCommand cmd = new MySqlCommand(caldate, con);
cmd.Parameters.AddWithValue("#firstDate", firstDate);
cmd.Parameters.AddWithValue("#lastDate", lastDate);
MySqlDataAdapter mysqlDataAdapter = new MySqlDataAdapter(cmd);
try
{
mysqlDataAdapter.Fill(dsMonth);
}
catch { }
return dsMonth;
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
DateTime nextDate;
if (dsleaveplanner != null)
{
foreach (DataRow dr in dsleaveplanner.Tables[0].Rows)
{
nextDate = (DateTime)dr["date"];
MySqlConnection conn = new MySqlConnection("Server=localhost;Database=mydb;Uid=myid;Pwd=abc123;");
string cntdate = "SELECT COUNT(date) FROM approved WHERE date = #date";
string cntdate2 = "SELECT COUNT(date) FROM pending WHERE date = #date";
MySqlCommand cmd2 = new MySqlCommand(cntdate, conn);
MySqlCommand cmd3 = new MySqlCommand(cntdate2, conn);
cmd2.Parameters.AddWithValue("#date", nextDate);
cmd3.Parameters.AddWithValue("#date", nextDate);
conn.Open();
string count = cmd2.ExecuteScalar().ToString();
string count2 = cmd3.ExecuteScalar().ToString();
var slot2 = Convert.ToInt32(count);
Int32 slot3 = 10 - slot2;
string slot4 = slot3.ToString();
conn.Close();
if (nextDate == e.Day.Date)
{
e.Cell.BackColor = System.Drawing.Color.Orange;
Environment.NewLine.ToString();
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p></p>Slot available:"));
e.Cell.Controls.Add(new LiteralControl(slot4));
e.Cell.Controls.Add(new LiteralControl("<p></p>Pending:"));
e.Cell.Controls.Add(new LiteralControl(count2));
}
else
{
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p>Slot available: 10</p>"));
e.Cell.Controls.Add(new LiteralControl("<p></p>Pending: 0"));
}
}
}
}
protected void Calendar1_VisibleMonthChanged(object sender,
MonthChangedEventArgs e)
{
DateTime firstDate = e.NewDate.AddDays(-7);
DateTime lastDate = e.NewDate.AddMonths(1).AddDays(7);
dsleaveplanner = GetCurrentMonthData(firstDate, lastDate);
}
What I want is if there is no data for a date i want the default value Slot avalable: 10 and Pending: 0 to be displayed. And I want the slot available and pending to be displayed only once in each date. What am I missing here?
Thanks in advance
First of all create one sample class with your name
class Sample
{
public DateTime Date { get; set; }
public int SlotAvailable { get; set; }
public int Pending { get; set; }
}
And create a List<Sample>
List<Sample> samples = new List<Sample>();
Then change your foreach like
foreach (DataRow dr in dsleaveplanner.Tables[0].Rows)
{
nextDate = (DateTime)dr["date"];
MySqlConnection conn = new MySqlConnection("Server=localhost;Database=mydb;Uid=myid;Pwd=abc123;");
string cntdate = "SELECT COUNT(date) FROM approved WHERE date = #date";
string cntdate2 = "SELECT COUNT(date) FROM pending WHERE date = #date";
MySqlCommand cmd2 = new MySqlCommand(cntdate, conn);
MySqlCommand cmd3 = new MySqlCommand(cntdate2, conn);
cmd2.Parameters.AddWithValue("#date", nextDate);
cmd3.Parameters.AddWithValue("#date", nextDate);
conn.Open();
string count = cmd2.ExecuteScalar().ToString();
string count2 = cmd3.ExecuteScalar().ToString();
var slot2 = Convert.ToInt32(count);
Int32 slot3 = 10 - slot2;
string slot4 = slot3.ToString();
conn.Close();
samples.Add(new Sample { Date = nextDate, SlotAvailable = slot4, Pending = count2 });
}
And then simply check if the e.Day.Date is present in our date in List<Sample>s date like
if (samples.Any(x => x.Date == e.Day.Date))
{
e.Cell.BackColor = System.Drawing.Color.Orange;
Environment.NewLine.ToString();
e.Cell.ForeColor = System.Drawing.Color.Red;
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p></p>Slot available:"));
e.Cell.Controls.Add(new LiteralControl(samples.Where(x => x.Date == e.Day.Date).FirstOrDefault().SlotAvailable.ToString()));
e.Cell.Controls.Add(new LiteralControl("<p></p>Pending:"));
e.Cell.Controls.Add(new LiteralControl(samples.Where(x => x.Date == e.Day.Date).FirstOrDefault().Pending.ToString()));
}
else
{
e.Cell.Font.Size = 9;
e.Cell.Controls.Add(new LiteralControl("<p>Slot available: 10</p>"));
e.Cell.Controls.Add(new LiteralControl("<p></p>Pending: 0"));
}
Output:
when reading SQl Date time field , only i can take the date with time ..how to get only date in to text box from Ajax or some method.
this is what i need to do
http://i.stack.imgur.com/n0fgG.jpg
that's how I'm taking the date to text box.
protected void ddlBatch_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["CBConnectionString"].ConnectionString;
const String strQuery = "select ItemIdentityCode, Qty, PurchasingPrice, ExpireDate, DiscountRate, IssueMode, Principle, Force from DEL_PurchasesLines where BatchNumber = #BatchNumber";
SqlConnection conPR = new SqlConnection(strConnString);
SqlCommand cmdPR = new SqlCommand();
cmdPR.Parameters.AddWithValue("#BatchNumber", ddlBatch.SelectedItem.Value);
cmdPR.CommandType = CommandType.Text;
cmdPR.CommandText = strQuery;
cmdPR.Connection = conPR;
try
{
conPR.Open();
SqlDataReader sdr = cmdPR.ExecuteReader();
while (sdr.Read())
{
tHFExpiaryDate.Text = sdr["ExpireDate"].ToString();
}
}
catch (Exception ex)
{
//throw ex;
}
finally
{
conPR.Close();
conPR.Dispose();
}
}
Don't convert the raw value to a string in the first place - it should already be a DateTime:
DateTime date = (DateTime) dsr["ExpireDate"];
Then you can convert it into whatever format you're interested in:
// TODO: Consider specifying the culture too, or specify a standard pattern.
tHFExpiaryDate.Text = date.ToString("MM/d/yyyy");
It's important to separate the question of "How can I get the data from the database in an appropriate type?" from "How should I present the data to the user?"
Try something like:
DateTime.ParseExact(sdr["ExpireDate"].ToString(), "MM/d/yyyy", CultureInfo.InvariantCulture)
In your sample:
tHFExpiaryDate.Text = DateTime.ParseExact( ((DateTime)dt.Rows[0][0]).ToString("MM/d/yyyy"), "MM/d/yyyy", System.Globalization.CultureInfo.CurrentCulture).ToString("MM/d/yyyy"));
This always works for me
protected String getDate(string date)
{
DateTime dDate;
string sdate = null;
if (!string.IsNullOrEmpty(date.ToString()))
{
dDate = DateTime.Parse(date.ToString());
sdate = dDate.ToString("dd/MM/yyyy");
sdate = dDate.ToLongDateString();
}
return sdate;
}
Other date format example http://www.dotnetperls.com/datetime-format
I need some assistance regarding to how to auto update StartDate and EndDate for next execution. At this moment, I manually add the StartDate and EndDate in sql database and if I didn’t change the StartDate and EndDate, my report will be generating using same StartDate and EndDate. Appreciate if you all can give any idea or suggestion about that. Thanks.
static void Main(string[] args)
{
DateTime start = System.DateTime.Now.AddMinutes(1);
Schedule.PeriodicSchedules schedule =
new Schedule.PeriodicSchedules(start,
Schedule.PeriodicSchedules.Frequency.Minutely);
schedule.Elapsed += new System.Timers.ElapsedEventHandler(GenerateReport);
schedule.Enabled = true;
Console.ReadLine();
}
static void GenerateReport(object sender, EventArgs e)
{
if (TypeOfReport == "BillingReport")
{
DateOfExecution = DateTime.Parse(strDOE);
Schedule.PeriodicSchedules s =
new Schedule.PeriodicSchedules(DateOfExecution,
Schedule.PeriodicSchedules.Frequency.Weekly);
crRpt.Load(BillingReport);
ReportLogin(crRpt);
while (ThisReader.Read())
{
//StartDate and EndDate >>next execution?
crRpt.SetParameterValue("#CollectionStartDate", StartDate);
crRpt.SetParameterValue("#CollectionEndDate", EndDate);
crRpt.SetParameterValue("#SpokeCode", SpokeCode);
}
}
if (TypeOfReport == "ImageReport")
{
DateOfExecution = DateTime.Parse(strDOE);
Schedule.PeriodicSchedules s =
new Schedule.PeriodicSchedules(DateOfExecution,
Schedule.PeriodicSchedules.Frequency.Monthly);
crRpt.Load(ImageReport);
ReportLogin(crRpt);
crRpt.SetParameterValue("#CollectionStartDate", StartDate);
crRpt.SetParameterValue("#CollectionEndDate", EndDate);
crRpt.SetParameterValue("#SpokeCode", SpokeCode);
}
}
I manage to do it by call another method to auto update my DateOfExecution. Let me know if someone have another way. :)
static void GenerateReport(object sender, EventArgs e)
{
if (TypeOfReport == "BillingReport")
{
......
DateOfExecution = DateTime.Parse(strDOE);
Schedule.PeriodicSchedules s = new Schedule.PeriodicSchedules(DateOfExecution, Schedule.PeriodicSchedules.Frequency.Minutely);
//weekly
DateTime StartDate = DateOfExecution.AddDays(-7);
DateTime EndDate = DateOfExecution.AddDays(-1);
..........
UpdateWeekly(DateOfExecution, strReportType);
}
}
static void UpdateWeekly(DateTime DateOfExecution, String strReportType)
{
DateOfExecution = DateOfExecution.AddMinutes(2);
SqlConnection thisConnection = new SqlConnection(SQLConnection);
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
//thisCommand.CommandText = "INSERT INTO dbo.Schedules (DateOfExecution)" + "Values('"+DateOfExecution+"')";
thisCommand.CommandText = "UPDATE dbo.Schedule set DateOfExecution = '" + DateOfExecution + "' WHERE TypeOfReport = '" + strReportType + "'";
thisCommand.ExecuteNonQuery();
}