如何将 try/check 用于 DateTime 以防止服务器错误?
How do I use try/check for DateTime to prevent Server Error?
我正在尝试编写 try/catch,但显然失败了。我不确定我是否完全理解 try/catch,但我确实知道我在思考我需要做什么以验证是否输入了正确的日期并通过表单提交时遇到了麻烦。我的意思是,我认为它需要采用 DateTime 格式,而不是字符串,并且应该是 (MM/dd/yyyy),但是这个 try/check 东西让我陷入了循环。
Instructions: Go back to the validation code that you added in the
frmPersonnel code and add a try/catch with logic to prevent an invalid
date from causing a server error.
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class frmPersonnel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
btnSubmit.Click += new EventHandler(this.btnSubmit_Click);//event for button
}
private void btnSubmit_Click(object sender, EventArgs e)
{
//DECLARATIONS
int count = 0;
string Msg = "You must enter a value in the following fields: <br/> ";
Boolean validatedState = true;
Boolean validateEntry = false;
DateTime endDate = new DateTime(2016, 03, 01);
DateTime startDate = new DateTime(2016, 03, 01);
//BEGIN SERIES OF IF/ELSE FOR CONFIRMING ENTRIES
if (Request["txtFirstName"].ToString().Trim() == "")
{
//displays yellow bg for missing input
txtFirstName.BackColor = System.Drawing.Color.Yellow;
Msg = Msg + "First Name <br/> ";
}//endif
else
{
txtFirstName.BackColor = System.Drawing.Color.White;
count += 1;
}//end else
if (Request["txtLastName"].ToString().Trim() == "")
{
//displays yellow bg for missing input
txtLastName.BackColor = System.Drawing.Color.Yellow;
Msg = Msg + "Last Name <br/> ";
}//endif
else
{
txtFirstName.BackColor = System.Drawing.Color.White;
count += 1;
}//end else
if (Request["txtPayRate"].ToString().Trim() == "")
{
//displays yellow bg for missing input
txtPayRate.BackColor = System.Drawing.Color.Yellow;
Msg = Msg + "Pay Rate <br/> ";
}//endif
else
{
txtFirstName.BackColor = System.Drawing.Color.White;
count += 1;
}//end else
if (Request["txtStartDate"].ToString().Trim() == "")
{
//displays yellow bg for missing input
txtStartDate.BackColor = System.Drawing.Color.Yellow;
validateEntry = false;
Msg = Msg + "Start Date <br/> ";
}//endif
else
{
try
{
//Conversion to DateTime format?
startDate = DateTime.Parse(Request["txtStartDate"]);
//How do I write the format I want, and when it should be checked?
}
catch (Exception ex)
{
//Exception should be caught here, not sure how to write this out though?
}
validateEntry = true;
}//end else
if (Request["txtEndDate"].ToString().Trim() == "")
{
//displays yellow bg for missing input
txtEndDate.BackColor = System.Drawing.Color.Yellow;
validateEntry = false;
Msg = Msg + "End Date <br/> ";
}//endif
else
{
try
{
//Conversion to DateTime format?
endDate = DateTime.Parse(Request["txtEndDate"]);
//How do I write the format I want, and when it should be checked?
}
catch (Exception ex)
{
//Exception should be caught here, not sure how to write this out though?
}
validateEntry = true;
}//end else
//END SERIES OF IF/ELSE FOR CONFIRMING ENTRIES
//START IF VALIDATE ENTRY
if (validateEntry == true)
{
if (DateTime.Compare(startDate, endDate) >= 0)
{
txtStartDate.BackColor = System.Drawing.Color.Yellow;
txtEndDate.BackColor = System.Drawing.Color.Yellow;
Msg = Msg + "Start Date <br/>" + "End Date <br/> <br/>The end date must be a later date than the start date.";
//The Msg text will be displayed in lblError.Text after all the error messages are concatenated
validatedState = false;
//Boolean value - test each textbox to see if the data entered is valid, if not set validState=false.
//If after testing each validation rule, the validatedState value is true, then submit to frmPersonnelVerified.aspx, if not, then display error message
}
else //goes to this if dates are correct
{
validatedState = true;
count += 2;
txtStartDate.BackColor = System.Drawing.Color.White;
txtEndDate.BackColor = System.Drawing.Color.White;
}
}
//END IF VALIDATE ENTRY
//SENDS DATA & ERROR MESSAGES
if (count == 5 && validatedState == true)
{
Session["txtFirstName"] = txtFirstName.Text;
Session["txtLastName"] = txtLastName.Text;
Session["txtPayRate"] = txtPayRate.Text;
Session["txtStartDate"] = txtStartDate.Text;
Session["txtEndDate"] = txtEndDate.Text;
Response.Redirect("frmPersonnelVerified.aspx");
//sends to other page
}
else
{
//Writes out error messages
Response.Write("<br/><span style = 'color: red ; position: absolute; top: 360px; left: 90px;'>" + Msg + "</span>");
}
//ENDS DATA AND ERROR MESSAGES
}//end Function: private void BtnSubmit_click...
}
您可以使用 TryParse 检查有效日期
// valid Date
DateTime goodDate;
if (DateTime.TryParse("2000-02-02", out goodDate))
{
Console.WriteLine(goodDate);
}
// not a date
DateTime badDate;
if (DateTime.TryParse("???", out badDate))
{
Console.WriteLine(badDate);
}
else
{
Console.WriteLine("Invalid");
}
如果您希望使用基于区域的格式,您可能还想包括文化
string dateString;
CultureInfo culture;
DateTimeStyles styles;
DateTime dateResult;
// Parse a date and time with no styles.
dateString = "03/01/2009 10:00 AM";
culture = CultureInfo.CreateSpecificCulture("en-US");
styles = DateTimeStyles.None;
if (DateTime.TryParse(dateString, culture, styles, out dateResult))
Console.WriteLine("{0} converted to {1} {2}.",
dateString, dateResult, dateResult.Kind);
else
Console.WriteLine("Unable to convert {0} to a date and time.",
dateString);
如果你真的想要准确的话:
DateTime dateValue;
var isDatePass = DateTime.TryParseExact("03/08/2002", "MM/dd/yyyy", new CultureInfo("en-US"), DateTimeStyles.None, out dateValue);
请记住,您始终可以使用预先验证。
来自 MSDN:https://msdn.microsoft.com/en-us/library/0yd65esw.aspx
When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program.
The try block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully.
从逻辑上讲,您可以将 try...catch... 块视为条件语句。
例如,假设您有以下代码:
string someString = "ABC";
DateTime someDate = DateTime.Parse(someString);
显然“ABC”不是有效的 DateTime,那么会发生什么?您的应用程序因未处理的异常(错误)而崩溃。
当你在 try...catch... 块中包装一些东西时,你基本上是在说:
If an exception occurs in my try block, then STOP executing the code in my try block, execute the code in the catch block, and continue on like nothing happened. Otherwise, just ignore code in my catch block.
这称为结构化异常处理。您正在预测代码的“危险”区域,并添加应急代码以防最坏情况发生。结构化异常处理对于处理不安全的用户输入以及外部或不可靠的系统(如外部网络服务)特别有用。
一个例子:
string someString = "ABC";
DateTime someDate;
try
{
someDate = DateTime.Parse(someString);
}
catch
{
// someString must not have been a valid DateTime!
// Console.WriteLine($"Hey, {someString} is not a valid DateTime!");
Console.WriteLine(String.Format("Hey, {0} is not a valid DateTime!", someString));
}
// Code continues executing because the exception was "caught"
将 validateEntry = true;
移动到 try
内,这样即使 DateTime.Parse
抛出异常,您也不会设置它。你的 try-catch
没问题。他们将 捕获 DateTime.Parse
中的任何错误。
我正在尝试编写 try/catch,但显然失败了。我不确定我是否完全理解 try/catch,但我确实知道我在思考我需要做什么以验证是否输入了正确的日期并通过表单提交时遇到了麻烦。我的意思是,我认为它需要采用 DateTime 格式,而不是字符串,并且应该是 (MM/dd/yyyy),但是这个 try/check 东西让我陷入了循环。
Instructions: Go back to the validation code that you added in the frmPersonnel code and add a try/catch with logic to prevent an invalid date from causing a server error.
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class frmPersonnel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
btnSubmit.Click += new EventHandler(this.btnSubmit_Click);//event for button
}
private void btnSubmit_Click(object sender, EventArgs e)
{
//DECLARATIONS
int count = 0;
string Msg = "You must enter a value in the following fields: <br/> ";
Boolean validatedState = true;
Boolean validateEntry = false;
DateTime endDate = new DateTime(2016, 03, 01);
DateTime startDate = new DateTime(2016, 03, 01);
//BEGIN SERIES OF IF/ELSE FOR CONFIRMING ENTRIES
if (Request["txtFirstName"].ToString().Trim() == "")
{
//displays yellow bg for missing input
txtFirstName.BackColor = System.Drawing.Color.Yellow;
Msg = Msg + "First Name <br/> ";
}//endif
else
{
txtFirstName.BackColor = System.Drawing.Color.White;
count += 1;
}//end else
if (Request["txtLastName"].ToString().Trim() == "")
{
//displays yellow bg for missing input
txtLastName.BackColor = System.Drawing.Color.Yellow;
Msg = Msg + "Last Name <br/> ";
}//endif
else
{
txtFirstName.BackColor = System.Drawing.Color.White;
count += 1;
}//end else
if (Request["txtPayRate"].ToString().Trim() == "")
{
//displays yellow bg for missing input
txtPayRate.BackColor = System.Drawing.Color.Yellow;
Msg = Msg + "Pay Rate <br/> ";
}//endif
else
{
txtFirstName.BackColor = System.Drawing.Color.White;
count += 1;
}//end else
if (Request["txtStartDate"].ToString().Trim() == "")
{
//displays yellow bg for missing input
txtStartDate.BackColor = System.Drawing.Color.Yellow;
validateEntry = false;
Msg = Msg + "Start Date <br/> ";
}//endif
else
{
try
{
//Conversion to DateTime format?
startDate = DateTime.Parse(Request["txtStartDate"]);
//How do I write the format I want, and when it should be checked?
}
catch (Exception ex)
{
//Exception should be caught here, not sure how to write this out though?
}
validateEntry = true;
}//end else
if (Request["txtEndDate"].ToString().Trim() == "")
{
//displays yellow bg for missing input
txtEndDate.BackColor = System.Drawing.Color.Yellow;
validateEntry = false;
Msg = Msg + "End Date <br/> ";
}//endif
else
{
try
{
//Conversion to DateTime format?
endDate = DateTime.Parse(Request["txtEndDate"]);
//How do I write the format I want, and when it should be checked?
}
catch (Exception ex)
{
//Exception should be caught here, not sure how to write this out though?
}
validateEntry = true;
}//end else
//END SERIES OF IF/ELSE FOR CONFIRMING ENTRIES
//START IF VALIDATE ENTRY
if (validateEntry == true)
{
if (DateTime.Compare(startDate, endDate) >= 0)
{
txtStartDate.BackColor = System.Drawing.Color.Yellow;
txtEndDate.BackColor = System.Drawing.Color.Yellow;
Msg = Msg + "Start Date <br/>" + "End Date <br/> <br/>The end date must be a later date than the start date.";
//The Msg text will be displayed in lblError.Text after all the error messages are concatenated
validatedState = false;
//Boolean value - test each textbox to see if the data entered is valid, if not set validState=false.
//If after testing each validation rule, the validatedState value is true, then submit to frmPersonnelVerified.aspx, if not, then display error message
}
else //goes to this if dates are correct
{
validatedState = true;
count += 2;
txtStartDate.BackColor = System.Drawing.Color.White;
txtEndDate.BackColor = System.Drawing.Color.White;
}
}
//END IF VALIDATE ENTRY
//SENDS DATA & ERROR MESSAGES
if (count == 5 && validatedState == true)
{
Session["txtFirstName"] = txtFirstName.Text;
Session["txtLastName"] = txtLastName.Text;
Session["txtPayRate"] = txtPayRate.Text;
Session["txtStartDate"] = txtStartDate.Text;
Session["txtEndDate"] = txtEndDate.Text;
Response.Redirect("frmPersonnelVerified.aspx");
//sends to other page
}
else
{
//Writes out error messages
Response.Write("<br/><span style = 'color: red ; position: absolute; top: 360px; left: 90px;'>" + Msg + "</span>");
}
//ENDS DATA AND ERROR MESSAGES
}//end Function: private void BtnSubmit_click...
}
您可以使用 TryParse 检查有效日期
// valid Date
DateTime goodDate;
if (DateTime.TryParse("2000-02-02", out goodDate))
{
Console.WriteLine(goodDate);
}
// not a date
DateTime badDate;
if (DateTime.TryParse("???", out badDate))
{
Console.WriteLine(badDate);
}
else
{
Console.WriteLine("Invalid");
}
如果您希望使用基于区域的格式,您可能还想包括文化
string dateString;
CultureInfo culture;
DateTimeStyles styles;
DateTime dateResult;
// Parse a date and time with no styles.
dateString = "03/01/2009 10:00 AM";
culture = CultureInfo.CreateSpecificCulture("en-US");
styles = DateTimeStyles.None;
if (DateTime.TryParse(dateString, culture, styles, out dateResult))
Console.WriteLine("{0} converted to {1} {2}.",
dateString, dateResult, dateResult.Kind);
else
Console.WriteLine("Unable to convert {0} to a date and time.",
dateString);
如果你真的想要准确的话:
DateTime dateValue;
var isDatePass = DateTime.TryParseExact("03/08/2002", "MM/dd/yyyy", new CultureInfo("en-US"), DateTimeStyles.None, out dateValue);
请记住,您始终可以使用预先验证。
来自 MSDN:https://msdn.microsoft.com/en-us/library/0yd65esw.aspx
When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program.
The try block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully.
从逻辑上讲,您可以将 try...catch... 块视为条件语句。
例如,假设您有以下代码:
string someString = "ABC";
DateTime someDate = DateTime.Parse(someString);
显然“ABC”不是有效的 DateTime,那么会发生什么?您的应用程序因未处理的异常(错误)而崩溃。
当你在 try...catch... 块中包装一些东西时,你基本上是在说:
If an exception occurs in my try block, then STOP executing the code in my try block, execute the code in the catch block, and continue on like nothing happened. Otherwise, just ignore code in my catch block.
这称为结构化异常处理。您正在预测代码的“危险”区域,并添加应急代码以防最坏情况发生。结构化异常处理对于处理不安全的用户输入以及外部或不可靠的系统(如外部网络服务)特别有用。
一个例子:
string someString = "ABC";
DateTime someDate;
try
{
someDate = DateTime.Parse(someString);
}
catch
{
// someString must not have been a valid DateTime!
// Console.WriteLine($"Hey, {someString} is not a valid DateTime!");
Console.WriteLine(String.Format("Hey, {0} is not a valid DateTime!", someString));
}
// Code continues executing because the exception was "caught"
将 validateEntry = true;
移动到 try
内,这样即使 DateTime.Parse
抛出异常,您也不会设置它。你的 try-catch
没问题。他们将 捕获 DateTime.Parse
中的任何错误。