I want to insert the (Day,Date,Time) from a Calendar and TimePicker a in my DB but I got this error
"SqlDateTime overflow"
Date access code:
public void InsertExam(SqlCommand cmd)
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "InsertExam";
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
con.Close();
}
Business
public void InsertExam_record()
{
cmd.Parameters.AddWithValue("#EWeekday", EWeekday);
cmd.Parameters.AddWithValue("#BegainTime", BegainTime);
cmd.Parameters.AddWithValue("#EndTime", EndTime);
cmd.Parameters.AddWithValue("#Duration", Duration);
cmd.Parameters.AddWithValue("#DateAD", DateAD);
cmd.Parameters.AddWithValue("#CourseID", CourseID);
cmd.Parameters.AddWithValue("#SemsterID", SemsterID);
dal.InsertExam(cmd);
}
CS
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DateTime dt = DateTime.Parse("08:30 AM");
MKB.TimePicker.TimeSelector.AmPmSpec am_pm;
if (dt.ToString("tt") == "AM")
{
am_pm = MKB.TimePicker.TimeSelector.AmPmSpec.AM;
}
else
{
am_pm = MKB.TimePicker.TimeSelector.AmPmSpec.PM;
}
TimeSelector1.SetTime(dt.Hour, dt.Minute, am_pm);
}
CourseGridView.DataBind();
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox1.Text = Calendar1.SelectedDate.ToString("ddd", new System.Globalization.CultureInfo("ar-SA"));
TextBox2.Text= Calendar1.SelectedDate.ToString("yyyy/MM/dd", new System.Globalization.CultureInfo("ar-SA"));
TextBox3.Text = Calendar1.SelectedDate.ToString("yyyy/MM/dd");
}
protected void Submit(object sender, EventArgs e)
{
DateTime start = DateTime.Parse(string.Format("{0}:{1}", TimeSelector1.Hour, TimeSelector1.Minute));
DateTime end = DateTime.Parse(string.Format("{0}:{1}", TimeSelector2.Hour, TimeSelector2.Minute));
TimeSpan du = end - start;
double r = du.TotalHours;
EndTime.Text = r.ToString();
b.EWeekday = TextBox1.Text;
b.BegainTime = Convert.ToDateTime(start);
b.EndTime = Convert.ToDateTime(end);
b.Duration = Convert.ToInt32(r);
b.DateAD = Convert.ToDateTime(TextBox3.Text);
b.CourseID = Convert.ToInt32(CourseGridView.SelectedValue);
b.SemsterID = Convert.ToInt32(SemsterList.SelectedValue);
b.InsertExam_record();
}
and this is my Stored Procedure
[dbo].[InsertExam]
-- Add the parameters for the stored procedure here
#EWeekday NVARCHAR (50),
#BegainTime Time,
#EndTime Time,
#Duration INT,
#DateAD Date,
#CourseID INT,
#SemsterID INT
AS
BEGIN
INSERT INTO Exam
( EWeekday, BegainTime, EndTime, Duration, DateAD, CourseID, SemsterID)
VALUES (#EWeekday,#BegainTime,#EndTime,#Duration,#DateAD,#CourseID,#SemsterID)
END
Related
I'm using ASP.NET daypilot event calendar
Data is stored in a SQLite File for testing
The Events in the Calendar have the following structure
CREATE TABLE event (
id VARCHAR(50),
name VARCHAR(50),
eventstart DATETIME,
eventend DATETIME
);
my tables
objects(Id,Name)
timeprofiles(Id,Object.Id,Location.Id,Start,End)
locations(Id,Name,Addr)
Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DayPilotCalendar1.StartDate = DayPilot.Utils.Week.FirstDayOfWeek(new DateTime(2020, 1, 1));
DayPilotCalendar1.DataSource = dbGetEvents(DayPilotCalendar1.StartDate, DayPilotCalendar1.Days);
DataBind();
}
}
CalendarEventMove
protected void DayPilotCalendar1_EventMove(object sender, DayPilot.Web.Ui.Events.EventMoveEventArgs e)
{
dbUpdateEvent(e.Value, e.NewStart, e.NewEnd);
DayPilotCalendar1.DataSource = dbGetEvents(DayPilotCalendar1.StartDate, DayPilotCalendar1.Days);
DayPilotCalendar1.DataBind();
DayPilotCalendar1.Update();
}
LoadingEvents
private DataTable dbGetEvents(DateTime start, int days)
{
SQLiteDataAdapter da = new SQLiteDataAdapter("SELECT [id], [name], [eventstart], [eventend] FROM [event] WHERE NOT (([eventend] <= #start) OR ([eventstart] >= #end))", ConfigurationManager.ConnectionStrings["db"].ConnectionString);
da.SelectCommand.Parameters.AddWithValue("start", start);
da.SelectCommand.Parameters.AddWithValue("end", start.AddDays(days));
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
UpdateEvents
private void dbUpdateEvent(string id, DateTime start, DateTime end)
{
using (SQLiteConnection con = new SQLiteConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString))
{
con.Open();
SQLiteCommand cmd = new SQLiteCommand("UPDATE [event] SET [eventstart] = #start, [eventend] = #end WHERE [id] = #id", con);
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters.AddWithValue("start", start);
cmd.Parameters.AddWithValue("end", end);
cmd.ExecuteNonQuery();
}
}
I'm trying filter this by location, adding a combobox to select and then querying by location
Does someone have an idea how to achieve this?
<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;
}
}
}
Here is the my c# application, it's a pop up ,i want to know how add cache clean method to this code.
i want to include a cache clean coding to clean cache in this program and minimize the ram
namespace SmartAlert
{
public partial class Form2 : Form
{
static String maxValue = "1";
static int checkNewRecordTime =8;
static int frameVisibilityTime = 20;
private const int CP_DISABLE_CLOSE_BUTTON = 0x200;
System.Windows.Forms.Timer hideTime;
public Form2()
{
InitializeComponent();
checkNewRecordTimer();
checkNewRecord();
}
// Method to disable form close button \\
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ClassStyle = cp.ClassStyle | CP_DISABLE_CLOSE_BUTTON;
return cp;
}
}
protected override void OnLoad(EventArgs e)
{
// Code for set the screen location \\
var screen = Screen.FromPoint(this.Location);
this.Location = new Point(screen.WorkingArea.Right - this.Width, screen.WorkingArea.Bottom - this.Height);
base.OnLoad(e);
}
private void Form2_Load(object sender, EventArgs e)
{
}
// Database record's checking method \\
// 2
public void checkNewRecord()
{
try {
var connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection scon = new SqlConnection(connectionString);
String cost_code = ConfigurationManager.AppSettings["costCenter"].ToString();
scon.Open();
SqlCommand smd = new SqlCommand();
DateTime d1 = DateTime.Now;
string sqlFormattedDate = d1.Date.ToString("yyyy-MM-dd");
//** query for check and get the last enterd record **\\
smd.CommandText = "select max(OrdM_No) as M_id from FOOrderMaster where OrdM_Staff ='" + cost_code + "' and OrdM_Date ='" + sqlFormattedDate + "' ";
smd.Connection = scon;
SqlDataReader reader = smd.ExecuteReader();
reader.Read();
string mx_id = reader["M_id"].ToString();
reader.Close();
if (maxValue != mx_id)
{
maxValue = mx_id;
popup_Window(mx_id);
this.Show();
frameHideTimer();
}
scon.Close();
}
catch (SqlException)
{
}
catch (Exception)
{
}
}
// Retriving Database record's checking and sending to form method \\
// 3
public void popup_Window(String mx_id)
{
try
{
var connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection scon1 = new SqlConnection(connectionString);
scon1.Open();
//** query for get the data of last enterd record **\\
SqlCommand smd1 = new SqlCommand();
smd1.CommandText = "SELECT f.OrdM_No,f.OrdM_BillNo,f.OrdM_Table,f.OrdM_Date,d.OrdD_Price FROM FOOrderMaster f inner join FOOrderDetail d on f.OrdM_No = d.OrdM_No WHERE f.OrdM_No = '" + mx_id + "'";
smd1.Connection = scon1;
SqlDataReader reader12 = smd1.ExecuteReader();
reader12.Read();
if (reader12.HasRows)
{
label8.Text = reader12["OrdM_BillNo"].ToString();
label9.Text = reader12["OrdD_Price"].ToString();
label7.Text = reader12["OrdM_Table"].ToString();
string nm = reader12["OrdM_Date"].ToString();
DateTime dm = Convert.ToDateTime(nm);
string df = dm.Date.ToString("yyyy-MM-dd");
label6.Text = df.ToString();
}
scon1.Close();
}
catch (SqlException)
{
}
catch (Exception)
{
}
}
// timer for check new record method \\
// 1
public void checkNewRecordTimer()
{
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 1000*checkNewRecordTime; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();
}
void timer_Tick(object sender, EventArgs e)
{
checkNewRecord();
}
// timer for hidden the form \\
public void frameHideTimer()
{
hideTime = new System.Windows.Forms.Timer();
hideTime.Interval = 1000*frameVisibilityTime; // specify interval time as you want
hideTime.Tick += new EventHandler(hideTimer_Tick);
hideTime.Start();
}
void hideTimer_Tick(object sender, EventArgs e)
{
this.Hide();
hideTime.Stop();
}
private void button1_Click(object sender, EventArgs e)
{
var fm3 = new Form3();
fm3.Show();
}
private void Form2_Move(object sender, EventArgs e)
{
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
var fm3 = new Form3();
fm3.Show();
notifyIcon1.Visible = true;
}
}
}
please help me with this
I had this message
Input string was not in a correct format
when inserting values into the database. When I checked I have DDL but I did not select value from it so this message appeared, although I make this column in the database to allow NULL value.
protected void BT_submit_Click(object sender, ImageClickEventArgs e)
{
string File = "~/CvFiles/" + FU_CV.FileName;
if (FU_CV.FileBytes.Length > 4194304)
{
modalpopup.Show();
}
else
{
app.AddApplicant(txt_Mname.Text, Convert.ToInt32(DDL_Dept.SelectedValue));
}
}
private void loadDepts()
{
DDL_Dept.DataSource = d.GetAll();
DDL_Dept.Items.Clear();
DDL_Dept.AppendDataBoundItems = true;
DDL_Dept.Items.Insert(0, new ListItem("-All-", "NULL"));
DDL_Dept.DataValueField = "id";
DDL_Dept.DataTextField = "name";
DDL_Dept.DataBind();
}
public bool AddApplicant(string MiddleName, int Dept_ID)
{
SqlCommand cmd = new SqlCommand("SP_Insert_IntoApplicantforuser");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#MiddleName", MiddleName);
cmd.Parameters.AddWithValue("#Dept_ID", Dept_ID);
System.Data.SqlClient.SqlParameter paramter1 = cmd.Parameters.Add("#AppID", SqlDbType.Int);
paramter1.Direction = ParameterDirection.Output;
bool rowaffected;
rowaffected = DBHelper.Instance().Insert(cmd);
if (rowaffected == false)
{
AppID = (int)paramter1.Value;
}
return rowaffected;
}
You should check, if DDL_Dept.SelectedValue is a string representation of int. Use int.TryParse method:
if (FU_CV.FileBytes.Length > 4194304)
{
modalpopup.Show();
}
else
{
int dept;
if (int.TryParse(DDL_Dept.SelectedValue, out dept))
app.AddApplicant(txt_Mname.Text, dept);
else
app.AddApplicant(txt_Mname.Text, -1); //or whatever there should be for you
}
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();
}