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
Related
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:
I want to create the attached task scheduler using asp.net and C#.
In SQL Server I have a table with these columns:
InstituteId, InstituteName, Address,
CareerDay2017 (date), CareerDay2018 (date), CareerDay2019 (date)
Dropdown list has values 2017, 2018, 2019. A button should be next to the dropdownlist.
When we select the year from dropdown list and click the button particular data should be retrieved and displayed as the image.
The career day details should be retrieved and colored the particular cell.
This is what I have tried, but it is incorrect. Hope you have taken my idea and help me.
SqlConnection con = new SqlConnection(#"Data Source=NAWODA;Initial Catalog=InternsDB;Integrated Security=True");
SqlCommand cmd;
SqlDataReader sdr,sdr1, sdr2;
String query;
DateTime current = DateTime.Now;
String dateColumn;
StringBuilder table = new StringBuilder();
protected void Page_Load(object sender, EventArgs e)
{
searchDetailPanel.Visible = false;
searchTaskPanel.Visible = false;
if (!Page.IsPostBack)
{
con.Open();
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2018) = '2018'
ORDER BY InstituteId";
cmd = new SqlCommand(query, con);
sdr1 = cmd.ExecuteReader();
}
setData(sdr1, currentDetailPanel);
{
query = #"SELECT CareerDay2017, CareerDay2018, CareerDay2019
FROM Institution
ORDER BY InstituteId";
cmd = new SqlCommand(query, con);
sdr2 = cmd.ExecuteReader();
}
createYearTable(sdr1, sdr2, currentTaskPanel);
}
}
private void setData(SqlDataReader sdr, Panel DetailPanel1)
{
table.Append("<table>");
table.Append("<tr><th>Institute ID</th> <th>Institute Name</th>");
table.Append("</tr>");
if (sdr.HasRows)
{
while (sdr.Read())
{
table.Append("<tr>");
table.Append("<td>" + sdr[0] + "</td>");
table.Append("<td>" + sdr[1] + "</td>");
table.Append("</tr>");
}
}
table.Append("</table>");
DetailPanel1.Controls.Add(new Literal { Text = table.ToString() });
sdr.Close();
sdr.Dispose();
}
private void createYearTable(SqlDataReader sdr1,SqlDataReader sdr2, Panel DetailPanel2)
{
int currentYear = Int32.Parse(current.ToString("yyyy"));
table.Append("<table>");
//****filling the year
table.Append("<tr>");
for (int i = 1; i <= 12; i++)
{
table.Append("<td>" + Convert.ToString(currentYear) + "</td>");
}
table.Append("</tr>");
//****filling the month
table.Append("<tr>");
for (int j = 1; j <= 12; j++)
{
int monthString = j;
table.Append("<td>" +getMonthName(monthString) + "</td>");
}
table.Append("</tr>");
//****data cell filling
if (sdr2.HasRows)
{
while (sdr2.Read())
{
table.Append("<tr>");
if (yearDropDownList.SelectedValue == "2017")
{
dateColumn = sdr2[5].ToString();
DateTime careerFairDate = Convert.ToDateTime(dateColumn);
int monthNo = Int32.Parse(careerFairDate.ToString("MM"));
int dateNo = Int32.Parse(careerFairDate.ToString("dd"));
for (int j = 1; j <= 12; j++)
{
if (monthNo == j)
{
table.Append("<td>");
Label lbl1 = new Label();
lbl1.Text = "On" + dateNo;
table.Append("</td>");
}
else
{
table.Append("<td>");
Label lbl2 = new Label();
table.Append("</td>");
}
}
}
table.Append("</tr>");
}
table.Append("</table>");
DetailPanel2.Controls.Add(new Literal { Text = table.ToString() });
sdr2.Close();
sdr2.Dispose();
}
}
protected String getMonthName(int i)
{
String[] monthName = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
return monthName[i - 1];
}
protected void searchBtn_Click(object sender, EventArgs e)
{
currentDetailPanel.Visible = false;
currentTaskPanel.Visible = false;
searchDetailPanel.Visible = true;
searchTaskPanel.Visible = true;
con.Open();
if (yearDropDownList.SelectedValue == "2018")
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2018) = '2018'
ORDER BY InstituteId";
}
else if (yearDropDownList.SelectedValue == "2017")
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2017) = '2017'
ORDER BY InstituteId";
}
else if (yearDropDownList.SelectedValue == "2019")
{
query = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CareerDay2019) = '2019'
ORDER BY InstituteId";
}
cmd = new SqlCommand(query, con);
sdr = cmd.ExecuteReader();
setData(sdr, searchDetailPanel);
DateTime current = DateTime.Now;
createYearTable(sdr,sdr2,searchTaskPanel);
}
As for the UI part, you need to place a breakpoint in the method that draws your UI and step through it while it is reading your data. You need to learn how to debug you code.
Just based off what you have posted, I think you have a bigger issue, you should not be declaring a SqlConnection at the class level, it should be in a method somewhere. For example:
public void GetCalendarData(int year)
{
// You need to use a parameter for the year instead of hard-coding it (note the #year)
string strCmd = #"SELECT InstituteId, InstituteName
FROM Institution
WHERE YEAR(CarrerDay2018) = #year
ORDER BY InstituteId";
using(var conn = new SqlConnection(connString))
using(var cmd = new SqlCommand(strCmd))
{
// add the #year parameter to the command
cmd.Parameters.AddWithValue("#year", year);
conn.Open();
var reader = cmd.ExecuteReader();
// setdata, createYearTable, etc.
conn.Close();
}
}
This way you are not holding a connection to the database for any longer than you need to. Also, I have put the connection and the command inside using statements, meaning that they will be disposed of properly by the garbage collector.
Can anyone point me to where I make a mistake, I want to put a new sql query where I will read the data from the database and put them in my function, and in the end they will be displayed at the exit in the colon ("stunden") which currently appears on the first query SUM (zei.ZPZ_Std100) AS ZPZ_Std100
This looks like my entire code in the button
using (SqlConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString))
{
boAPI4.Login login = new boAPI4.Login();
string cS = login.GetConnectionString();
DataAccess dA = new DataAccess(cS);
int userID = dA.getLpeID(login.GetBoUserNr());
PRAESENZZEIT q = new PRAESENZZEIT();
q.ZPZ_LPE_ID = userID;
if (db.State == ConnectionState.Closed)
db.Open();
string query = "SELECT per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum, SUM (zei.ZPZ_Std100) AS ZPZ_Std100" +
" FROM DB.dbo.Z_PRAESENZZEIT zei INNER JOIN DB.dbo.A_PERSONAL per ON zei.ZPZ_LPE_ID = per.LPE_ID" +
$" WHERE zei.ZPZ_Datum BETWEEN '{dtFromDate.Value}' AND '{dtToDate.Value}' AND zei.ZPZ_LPE_ID='{userID.ToString()}' GROUP BY per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum ORDER BY zei.ZPZ_Datum, per.LPE_Nr;";
pRAESENZZEITBindingSource.DataSource = db.Query<PRAESENZZEIT>(query, commandType: CommandType.Text);
List<PRAESENZZEIT> listid = new List<PRAESENZZEIT>();
PRAESENZZEIT pra = new PRAESENZZEIT();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString);
string sql = "SELECT ZPZ_Von,ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pra.ZPZ_Von = Convert.ToDateTime(dr["ZPZ_Von"]);
pra.ZPZ_Bis = Convert.ToDateTime(dr["ZPZ_bis"]);
listid.Add(pra);
}
dataGridView1.DataSource = listid;
con.Close();
DateTime kommen = DateTime.Now;
kommen = pra.ZPZ_Von;
if (pra.ZPZ_Von.TimeOfDay < new TimeSpan(8, 5, 0))
pra.ZPZ_Von = new DateTime(pra.ZPZ_Von.Year, pra.ZPZ_Von.Month, pra.ZPZ_Von.Day, 8, 0, 0);
DateTime gehen = DateTime.Now;
gehen = pra.ZPZ_Bis;
TimeSpan arbeitszeit = pra.ZPZ_Bis - pra.ZPZ_Von;
}
Currently, at the exit I get 0.
So, I need data that pass through the datetime variable
This is how it goes through the variables but returns the result as if it did not address base data, what's the problem? I understand if time [ZPZ_VON 07:45] that the exit should be 08:00..
SQL QUERY SELECT ZPZ_Von,ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'
CODE:
List<PRAESENZZEIT> listid = new List<PRAESENZZEIT>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString);
string sql = "SELECT ZPZ_Von, ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
while (dr.Read())
{
PRAESENZZEIT pra = new PRAESENZZEIT();
pra.ZPZ_Von = Convert.ToDateTime(dr["ZPZ_Von"]);
pra.ZPZ_Bis = Convert.ToDateTime(dr["ZPZ_bis"]);
listid.Add(pra);
DateTime kommen = DateTime.Now;
kommen = pra.ZPZ_Von;
if (pra.ZPZ_Von.TimeOfDay < new TimeSpan(8, 5, 0))
pra.ZPZ_Von = new DateTime(pra.ZPZ_Von.Year, pra.ZPZ_Von.Month, pra.ZPZ_Von.Day, 8, 0, 0);
DateTime gehen = DateTime.Now;
gehen = pra.ZPZ_Bis;
TimeSpan arbeitszeit = pra.ZPZ_Bis - pra.ZPZ_Von;
}
con.Close();
DATABASE QUERY RESULT:
You were initializing the pra class outside the while loop. Which doesn't add new record in the list listid every time read DataRow from DataReader.
Try this below code:
using (SqlConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString))
{
boAPI4.Login login = new boAPI4.Login();
string cS = login.GetConnectionString();
DataAccess dA = new DataAccess(cS);
int userID = dA.getLpeID(login.GetBoUserNr());
PRAESENZZEIT q = new PRAESENZZEIT();
q.ZPZ_LPE_ID = userID;
if (db.State == ConnectionState.Closed)
db.Open();
string query = "SELECT per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum, SUM (zei.ZPZ_Std100) AS ZPZ_Std100" +
" FROM DB.dbo.Z_PRAESENZZEIT zei INNER JOIN DB.dbo.A_PERSONAL per ON zei.ZPZ_LPE_ID = per.LPE_ID" +
$" WHERE zei.ZPZ_Datum BETWEEN '{dtFromDate.Value}' AND '{dtToDate.Value}' AND zei.ZPZ_LPE_ID='{userID.ToString()}' GROUP BY per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum ORDER BY zei.ZPZ_Datum, per.LPE_Nr;";
pRAESENZZEITBindingSource.DataSource = db.Query<PRAESENZZEIT>(query, commandType: CommandType.Text);
List<PRAESENZZEIT> listid = new List<PRAESENZZEIT>();
//PRAESENZZEIT pra = new PRAESENZZEIT(); //Needs to be inside the while loop.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString);
string sql = "SELECT ZPZ_Von,ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
var listid = ConvertDataTable<PRAESENZZEIT>(dt);
dataGridView1.DataSource = listid;
con.Close();
}
private static List<T> ConvertDataTable<T>(DataTable dt)
{
List<T> data = newList<T>();
foreach (DataRowrow in dt.Rows)
{
Titem = GetItem<T>(row);
data.Add(item);
}
return data;
}
private static TGetItem<T>(DataRow dr)
{
Type temp = typeof(T);
T obj =Activator.CreateInstance<T>();
foreach (DataColumncolumn in dr.Table.Columns)
{
foreach (PropertyInfopro in temp.GetProperties())
{
if (pro.Name == column.ColumnName)
pro.SetValue(obj,dr[column.ColumnName], null);
else
continue;
}
}
return obj;
}
I have the following lines of code:
protected void btnUpload_Click(object sender, EventArgs e)
{
MySqlTransaction transaction;
string ex_id = "";
string file_name = Path.GetFileName(FileUpload1.FileName);
string Excel_path = Server.MapPath("~/Excel/" + file_name);
DataTable dtExceldata = new DataTable();//just added
FileUpload1.SaveAs(Excel_path);
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
my_con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
da.Fill(dtExceldata);
if (dtExceldata.Rows.Count > 0)
{
//foreach (DataRow row in dtExceldata.Rows)
for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
{
string ex_dir = dtExceldata.Rows[i]["website_a"].ToString();
//string ex_dir = row["website_a"].ToString();
string ex_email = dtExceldata.Rows[i]["email_id"].ToString();
// string ex_email = row["email_id"].ToString();
string ex_email1 = dtExceldata.Rows[i]["email_id2"].ToString();
//string ex_email1 = row["email_id2"].ToString();
string ex_email2 = dtExceldata.Rows[i]["email_id3"].ToString();
//string ex_email2 = row["email_id3"].ToString();
string ex_company = dtExceldata.Rows[i]["company"].ToString();
//string ex_company = row["company"].ToString();
string ex_contact = dtExceldata.Rows[i]["contact_name"].ToString();
//string ex_contact = row["contact_name"].ToString();
string ex_proposal = dtExceldata.Rows[i]["proposal_status"].ToString();
// string ex_proposal = row["proposal_status"].ToString();
string ex_reason = dtExceldata.Rows[i]["reason"].ToString();
//string ex_reason = row["reason"].ToString();
int chk = 0;
int type = 0;
int dup = 0;
int dir = 0;
if (ddlwebsites.SelectedIndex != 0)
{
dir = Convert.ToInt32(ddlwebsites.SelectedValue);
if (dir == 8)
{
type = 1;
}
}
foreach (ListItem lstAssign in ddlevents.Items)
{
if (lstAssign.Selected == true)
{
chk = 1;
}
}
if (type == 1 && chk == 0)
{
evyerror.Text = "Please Select the Event!!";
return;
}
else
{
string querycomp = "", compID = "";
querycomp = "Select * from barter_company where website like '%' '" + ex_dir + "' '%'";
string connStr = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
connect = new MySqlConnection(connStr);
connect.Open();
transaction = connect.BeginTransaction();
try
{
ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
DataTable dt = clsDtResult.GetDataTable(querycomp);
if (dt.Rows.Count > 0)
{
compID = dt.Rows[0]["comp_id"].ToString();
ViewState["comp_id"] = compID;
if (type == 1)
{
dup = checkforDuplicates(Convert.ToInt32(compID));
if (dup == 1)
{
//Confirm_MP.Show();
// ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "confirmation();", true);
}
}
//return;
}
else
{
string queryStr = "insert into barter_company (comp_name,website) values(?comp,?website)";
MySqlCommand cmd = new MySqlCommand(queryStr, connect, transaction);
cmd.Parameters.AddWithValue("?comp", ex_company);
cmd.Parameters.AddWithValue("?website", ex_dir);
cmd.ExecuteNonQuery();
cmd.CommandText = "Select LAST_INSERT_ID()";
compID = cmd.ExecuteScalar().ToString();
transaction.Commit();
connect.Close();
}
}
catch
{
transaction.Rollback();
}
if (dup == 0)
{
// create a connection string with your sql database
string connStr1 = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
connect = new MySqlConnection(connStr1);
connect.Open();
DateTime date = new DateTime();
date = DateTime.ParseExact(txtsentdate.Text, "MM/dd/yyyy", null);
string SentDateString = date.ToString("yyyy/MM/dd");
//DateTime date = new DateTime();
//if (!string.IsNullOrEmpty(ex_date))
// {
//DateTime date = new DateTime();//added by chetan
//ex_date = ex_date.Split(' ')[0];//added by chetan
//date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);//added by chetan
//string SentDateString = date.ToString("yyyy/MM/dd");//added by chetan
//DateTime SentDate = Convert.ToDateTime(SentDateString).Date;//added by chetan
//// DateTime date = DateTime.Parse(ex_date);//added by chetan
// }
//date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);//added by chetan
//date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
// string SentDateString = date.ToString("yyyy/MM/dd");
transaction = connect.BeginTransaction();
try
{
string ex_uid = Session["session_barterUser_id"].ToString();
MySqlCommand cmd = new MySqlCommand("insert into barter_proposals(user_id, sent_date, website_a, email_id, email_id2, email_id3, company, contact_name, proposal_status, reason,type) values(?uid,?sentdate,?dir,?email,?email2,?email3,?comp,?cont_name,?pro_status,?reason,?type)", connect);
cmd.Parameters.AddWithValue("?uid", ex_uid);
cmd.Parameters.AddWithValue("?comp", compID);
cmd.Parameters.AddWithValue("?sentdate", SentDateString);
// command.Parameters.AddWithValue("?event", eventname);
cmd.Parameters.AddWithValue("?dir", dir);
// command.Parameters.AddWithValue("?bar_type", ddlbartertype.SelectedValue);
// command.Parameters.AddWithValue("?website_b", txtwebsite.Text);
//cmd.Parameters.AddWithValue("?comp", ex_company);
cmd.Parameters.AddWithValue("?cont_name", ex_contact);
cmd.Parameters.AddWithValue("?email", ex_email);
cmd.Parameters.AddWithValue("?email2", ex_email1);
cmd.Parameters.AddWithValue("?email3", ex_email2);
cmd.Parameters.AddWithValue("?pro_status", ex_proposal);
cmd.Parameters.AddWithValue("?reason", ex_reason);
cmd.Parameters.AddWithValue("?type", type);
// command.Parameters.AddWithValue("?type", type);
cmd.ExecuteNonQuery();
if (type == 1)
{
cmd.CommandText = "Select LAST_INSERT_ID()";
Int64 CurrentProId = Convert.ToInt64(cmd.ExecuteScalar());
int eventAssignID;
string QueryInqEventAssign = "insert into barter_propeventassign(prop_id,event_id) values(?pro_id,?event_id)";
foreach (ListItem lstAssign in ddlevents.Items)
{
if (lstAssign.Selected == true)
{
cmd = new MySqlCommand(QueryInqEventAssign, connect, transaction);
cmd.Parameters.AddWithValue("?pro_id", CurrentProId);
eventAssignID = Convert.ToInt32(lstAssign.Value);
cmd.Parameters.AddWithValue("?event_id", eventAssignID);
cmd.ExecuteNonQuery();
}
}
}//end of if
transaction.Commit();
connect.Close();
Response.Write("<script type=\"text/javascript\">alert('Proposal Added Successfully!!!');</script>");
}//end of try
catch (Exception ex)
{
transaction.Rollback();
Response.Write("<script>alert('There is an Error Ocurred:" + Server.HtmlEncode(ex.Message) + "')</script>");
}
finally
{
connect.Close();
}
}//ifdupzero
}//else
}//for//foreach
}//while //if
// dr.Close();//commented by chetan
my_con.Close();
if (System.IO.File.Exists(Excel_path))
{
System.IO.File.Delete(Excel_path);
}
}
suppose there are 2 entries in the excelsheet file.When trying to import,it is inserting those 2 rows entries into the database table.but the problem is that, the reader does not stop its execution.After reading 2 rows entry,it is reading 3rd row which is blank.i have used dr.close and it keeps on reading the rows entries which is blank.
Instead of checking if there are rows left (dr.Read()) as your loop condition, you could check if the first cell of the row is blank (dr[0].ToString() != String.Empty)
string file_name = Path.GetFileName(FileUpload1.FileName);
string Excel_path = Server.MapPath("~/Excel/" + file_name);
FileUpload1.SaveAs(Excel_path);
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
my_con.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", my_con);
OleDbDataReader dr = command.ExecuteReader();
dr.Read();
while (dr[0].ToString() != String.Empty)
{
ex_id = dr[0].ToString();
string ex_uid = dr[1].ToString();
//get second row data and assign it ex_name variable
string ex_date = dr[2].ToString();
//get thirdt row data and assign it ex_name variable
string ex_dir = dr[3].ToString();
//get first row data and assign it ex_location variable
string ex_email = dr[4].ToString();
string ex_email1 = dr[5].ToString();
string ex_email2 = dr[6].ToString();
//string ex_company = dr[7].ToString();
string ex_company = dr[7].ToString();
string ex_contact = dr[8].ToString();
string ex_proposal = dr[9].ToString();
string ex_reason = dr[10].ToString();
...............
//Insert operation
...............
dr.Read();
}
dr.close();
my_con.close();
The premise of course is, that the first column is always filled if the rest of the row isn't blank.
If that isn't the case you can also check other columns in the loop condition.
there is various way of doing that
you can load excel data to datatable and then you can for loop for each row with perticular column name like this
string file_name = Path.GetFileName(FileUpload1.FileName);
string Excel_path = Server.MapPath("~/Excel/" + file_name);
DataTable dtExceldata = new DataTable();
FileUpload1.SaveAs(Excel_path);
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended
Properties=Excel 8.0;Persist Security Info=False");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
da.Fill(dtExceldata);
if(dtExceldata.Rows.Count>0)
{
for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
{
//assign value to variable
//like below
//string ex_uid = dtExceldata.Rows[i]["columnName"];
//then insert operation here
}
}
see this excel file
and the datatable in c#
this loop will repeat for only number of row in datatable then also i practically tried this and it only loop for number of row (e.g two times) but i found a bug that if you will enter two row then five blank row then some data it will give you blank value in data table check your excel file there may some blank value as shown in attechment
then also you can skip blank value by checking null value in row like this
for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
{
if (!String.IsNullOrEmpty(Convert.ToString(dtExceldata.Rows[i]["fieldvalues"])))
{
//assign value to variable
//like below
//string ex_uid = dtExceldata.Rows[i]["columnName"];
//then insert operation here
}
}
I have a code that importing and displaying a excel file to datagridview and I'm wondering if you help me to how can I save those sheet from my excel file to my database in mysql?? My sheet name are 1st grading, 2nd grading and attendance, I'm using c#. Anyway here's my code:
private void btnSaved_Click(object sender, EventArgs e)
{
int qtr = 0;
string att_qtr = "ATTENDANCE";
MySqlConnection con = new MySqlConnection("Server = DESKTOP-9H7QBOH; Database = sti_spms; UID = root; Password = 1234;");
try
{
string query = "INSERT INTO tbl_secondsem_grades(STUDENT_NO, NAME, SUBJECT, SECTION, GRADE, INITIAL_GRADE, QTR)" + "Values(#STUDENT_NO, #NAME, #SUBJECT, #SECTION, #GRADE, #INITIAL_GRADE, #QTR)";
query += "INSERT INTO tbl_attendance(STUDENT_ID, NAME, SUBJECT, SECTION, TOTAL_ABSENCES)" + "Values(#STUDENT_ID, #NAME, #SUBJECT, #SECTION, #TOTAL_ABSENCES)";
MySqlCommand cmd = new MySqlCommand(query, con);
DataTable dt = new DataTable();
con.Open();
for (int i = 0; i < dataGridView1.Rows.Count -1; i++)
{
if(quarter.Equals("1st QTR"))
{
qtr = 1;
}
else if(quarter.Equals("2nd QTR"))
{
qtr = 2;
}
else if(quarter.Equals("3rd QTR"))
{
qtr = 3;
}
else if(quarter.Equals("4th QTR"))
{
qtr = 4;
}
else if (quarter.Equals("ATTENDANCE"))
{
att_qtr = "ATTENDANCE";
}
else
{
MessageBox.Show("Error!");
}
//int num = Convert.ToInt32(dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString());
cmd.Parameters.AddWithValue("#STUDENT_NO", dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString());
cmd.Parameters.AddWithValue("#NAME", dataGridView1.Rows[i].Cells["NAME"].Value.ToString());
cmd.Parameters.AddWithValue("#SUBJECT", dataGridView1.Rows[i].Cells["SUBJECT"].Value.ToString());
cmd.Parameters.AddWithValue("#SECTION", dataGridView1.Rows[i].Cells["SECTION"].Value.ToString());
cmd.Parameters.AddWithValue("#INITIAL_GRADE", dataGridView1.Rows[i].Cells["INITIAL GRADE"].Value.ToString());
cmd.Parameters.AddWithValue("#GRADE", dataGridView1.Rows[i].Cells["QG"].Value.ToString());
cmd.Parameters.AddWithValue("#QTR", qtr);
cmd.Parameters.AddWithValue("#STUDENT_NO", dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString());
cmd.Parameters.AddWithValue("#NAME", dataGridView1.Rows[i].Cells["NAME"].Value.ToString());
cmd.Parameters.AddWithValue("#SUBJECT", dataGridView1.Rows[i].Cells["SUBJECT"].Value.ToString());
cmd.Parameters.AddWithValue("#SECTION", dataGridView1.Rows[i].Cells["SECTION"].Value.ToString());
cmd.Parameters.AddWithValue("#Total_Absences", dataGridView1.Rows[i].Cells["Total_Absences"].Value.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
catch (Exception ex)
{
MessageBox.Show("Data Sucessfully Saved!");
}
}
Quickie partial
...
MySqlCommand cmd = new MySqlCommand(query, con);
DataTable dt = new DataTable();
cmd.Paramters.Add("#STUDENT_NO", MySqlDbType.Int); .. guessing this is an int - otherwise choose type
cmd.Paramters.Add("#NAME", MySqlDbType.String);
... // add rest here
con.Open();
...
for (.. ) {
...
int studentno;
int.TryParse(dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString(), out studentno);
cmd.Paramters["#STUDENT_NO"].Value = studentno;
cmd.Paramters["#NAME"].Value = dataGridView1.Rows[i].Cells["NAME"].Value.ToString();
...
}