I have developed text boxes to add date range to pick specific records within that date range.
I have written IF ELSE for that if Both text boxes are empty then SHOW ERROR MESSAGE but problem is that when i first time call page then it shows same error. I know why because in first attempt text boxes are empty but how to control this ?
public ActionResult ShowMyAtdByDate(String DateFrom, String DateTo)
{
int empId = 0;
int.TryParse((string)Session["Employee"], out empId); // parse variable to int and saves the result in empId
// IEnumerable<GetMyAtd_DateResult> MyAtdRecord = DataContext.GetMyAtd_Date(DateFrom,DateTo,empId).ToList();
if (DateFrom != "" && DateTo == "" && empId > 0)
{
IEnumerable<GetMyAtd_DateResult> MyAtdRecord = DataContext.GetMyAtd_Date(DateFrom,null, empId).ToList();
ViewBag.Dates = "Records for" + " " + DateFrom;
return View(MyAtdRecord);
}
else if (DateFrom == "" && DateTo != "" && empId > 0)
{
IEnumerable<GetMyAtd_DateResult> MyAtdRecord = DataContext.GetMyAtd_Date( null, DateTo, empId).ToList();
ViewBag.Dates = "Records for" + " " + DateTo;
return View(MyAtdRecord);
}
else if (DateFrom != "" && DateTo != "" && empId > 0)
{
IEnumerable<GetMyAtd_DateResult> MyAtdRecord = DataContext.GetMyAtd_Date(DateFrom, DateTo, empId).ToList();
ViewBag.Dates = "Records from" + " " + DateFrom + " " + "to" + " " + DateTo;
return View(MyAtdRecord);
}
else if (DateFrom == "" && DateTo == "" && empId > 0)
{
IEnumerable<GetMyAtd_DateResult> MyAtdRecord = DataContext.GetMyAtd_Date(null, null, empId).ToList();
ViewBag.Dates = "No dates selection";
return View(MyAtdRecord);
}
else if(empId <=0 )
{
return RedirectToAction("IsAuth_Page","Home");
}
return View();
}
View:
#{
var grid = new WebGrid(ViewData.Model, rowsPerPage: 25);
}
#if (Model.Count > 0)
{
<div id="AllMyAtd_ByDate">
#grid.GetHtml(columns: grid.Columns(
grid.Column("EmplID", "Employee ID"),
grid.Column("EmplName", "Employee Name"),
grid.Column("ShiftID", "Shift ID"),
grid.Column("DateVisited", "Date of Visit"),
grid.Column("InTime", "In Time"),
grid.Column("TimeOut", "Time Out"),
grid.Column("OverTime", "Over Time"),
grid.Column("TotalWorkingTime", "Total Working Time")
))
</div>
}
else
{
<h4 class="error">Sorry Record Doesn't Exist for selected date(s)</h4>
}
When i first browse to this page then this appears which actually should appear only if i leave both text boxes empty.
The first time an user enters this page, it will be as a GET-request. You could remove this logic out of the GET-method (because it doesn't need to be executed when it is the first time) and put it in the POST-method, since this is the HTTP-method that will be used when the user has submitted the form.
[HttpGet]
public ActionResult ShowMyAtdByDate()
{
int empId = 0;
int.TryParse((string)Session["Employee"], out empId);
if (empId <= 0)
{
return RedirectToAction("IsAuth_Page", "Home");
}
return View();
}
[HttpPost]
public ActionResult ShowMyAtdByDate(string dateFrom, string dateTo)
{
if (dateFrom != "" && dateTo == "" && empId > 0)
{
...
}
else if (dateFrom == "" && dateTo != "" && empId > 0)
{
...
}
etc...
}
And make sure in your view your form has the method POST
Related
I have two forms and they are Frm_Department and Frm_Employee
How can I transfer data from my TextBox(Frm_Department) into ComboBox(Frm_Employee)? The image below this is where I will transfer the data from my TextBox.
Here are the forms.
Code of form department:
if (txtDepname.Text != "" && txtDepLocation.Text != "" && txtDepLocal.Text != "" )
{
DataClasses1DataContext db = new DataClasses1DataContext();
tbldepartment dep = new tbldepartment();
dep.DepID = txtDepID.Text;
dep.Depname = txtDepname.Text;
dep.Location = txtDepLocation.Text;
dep.LocalPhone = txtDepLocal.Text;
Insert.sp_insertdepartment(dep);
MessageBox.Show("Successfully Saved!");
AutoGenerate();
}
else
{
MessageBox.Show("Input all Details....");
}
Code of form employee:
if (txtempLname.Text != "" && txtempFname.Text != "" && txtempMname.Text != "" && txtempPossition.Text != "")
{
DataClasses1DataContext db = new DataClasses1DataContext();
tblemployee emp = new tblemployee();
emp.EmpID = txtempnum.Text;
emp.Lname = txtempLname.Text;
emp.Fname = txtempFname.Text;
emp.Mname = txtempMname.Text;
emp.Position = txtempPossition.Text;
Insert.sp_insertemployee(emp);
MessageBox.Show("Successfully Saved!");
AutoGenerate();
}
else
{
MessageBox.Show("Input all Details....");
}
I have to display a validation message when a user selects a date outside the allowed range. The is the code i have to work with:
public ActionResult QuickEdit(int pk, string name, string value)
{
var freeOfChargeTime = Db.FreeOfChargeTime.Find(pk);
freeOfChargeTime.ProjectExtension = freeOfChargeTime.ProjectExtension ?? Db.ProjectExtensions.Find(freeOfChargeTime.ProjectExtensionId);
if ((name == "StartDate" && DateTime.Parse(value) > freeOfChargeTime.EndDate) || (name == "EndDate" && DateTime.Parse(value) < freeOfChargeTime.StartDate))
{
ModelState.AddModelError("StartDate", "the end date must be after the start date");
}
if (name == "NumberOfDays" && double.Parse(value) <= 0)
{
ModelState.AddModelError("NumberOfDays", "Number of days must be > 0");
}
if (name == "StartDate" && DateTime.Parse(value) < freeOfChargeTime.ProjectExtension.StartDate)
{
ModelState.AddModelError("StartDate", "the free of charge period start date must be after the project extension start date");
}
if (freeOfChargeTime.ProjectExtension is IPextWithEndDate)
{
var poWithEndDate = (IPextWithEndDate)freeOfChargeTime.ProjectExtension;
if (name == "EndDate" && DateTime.Parse(value) > poWithEndDate.EndDate)
{
ModelState.AddModelError("EndDate", "the free of charge period end date must be before the project extension end date");
}
}
if (freeOfChargeTime.ProjectExtension.StatusId == ProjectExtensionStatus.Cancelled ||
freeOfChargeTime.ProjectExtension.StatusId == ProjectExtensionStatus.Disabled)
{
ModelState.AddModelError("Status", "the project extension is cancelled or disabled");
}
if (ModelState.IsValid) return XEditableUpdate(Db.FreeOfChargeTime, pk, name, value);
Response.StatusCode = 400;
var error = new Error { Message = "Error: " + ModelState.Errors() };
return Json(error.Message, JsonRequestBehavior.AllowGet);
}
This displays "Error: the free of charge period start date must be after the project extension start date\n"
I have tried:
#*#1*#
error.Message = error.Message.Split('\\').First();
#*#2*#
error.Message = error.Message.Replace("\\n", " ");
#*#3*#
string validationMessage = error.Message.Split('\\').First();
#*#4*#
string validationMessage = error.Message.Replace("\\n", " ");
#*#5*#
string validationMessage = error.Message;
validationMessage = validationMessage.Split('\\').First();
#*#6*#
string validationMessage = error.Message;
validationMessage = validationMessage.Replace("\\n", " ");
I still get the same result. Is there any way to get rid of the "\n", or work around the problem?
validationMessage.Replace("\r\n", string.Empty).Replace("\n", string.Empty).Replace("\r", string.Empty);
Use this code.
Edit: ok I know the query is incorrect. When I remove the TimeCreated part I get results back. What is the proper way to pull all events for that given day?
startTime = DateTime.Now.Date
string query = "*[System/Level=1 or System/Level=2] and TimeCreated[#SystemTime >= '" + startTime + "']";
using (EventLogSession session = new EventLogSession(serverName))
{
EventLogQuery eventQuery = new EventLogQuery(logName, PathType.LogName, query);
eventQuery.Session = session;
using (EventLogReader reader = new EventLogReader(eventQuery))
{
for (EventRecord eventDetail = reader.ReadEvent(); eventDetail != null; eventDetail = reader.ReadEvent())
{
entries.Add(eventDetail);
}
}
}
I have tired the following as well
"*[System/Level=1 or System/Level=2] and *[System/TimeCreated[#SystemTime >= '" + startTime + "']]";
"*[System[(Level=1) or System[(Level=2)] and TimeCreated[#SystemTime >= '" + startTime.ToUniversalTime().ToString("o") + "']]";
Here I made a helper to retrieve log from the event viewer, you can parametrized it quite easily
public static void WriteEventViewerHistoryByTypes(IList<EventViewerCriticalityLevel> levelTypes, string logType, string filePath, IList<string> sources, DateTime? startDate = new System.Nullable<DateTime>(), DateTime? endDate = new System.Nullable<DateTime>())
{
if (levelTypes == null || levelTypes.Count == 0)
levelTypes = new List<EventViewerCriticalityLevel> { EventViewerCriticalityLevel.Comment, EventViewerCriticalityLevel.Error, EventViewerCriticalityLevel.Fatal, EventViewerCriticalityLevel.Info, EventViewerCriticalityLevel.Warning };
StringBuilder sb = new StringBuilder();
sb.Append("<QueryList>");
sb.AppendFormat("<Query Id=\"0\" Path=\"{0}\">", logType);
sb.AppendFormat(" <Select Path=\"{0}\">", logType);
sb.AppendFormat(" *[System[(");
sb.AppendFormat("({0})", string.Join(" or ", levelTypes.Select(lev =>
{
if (lev == EventViewerCriticalityLevel.Info)
return string.Format("Level={0} or Level=0", (int)lev);
else
return string.Format("Level={0}", (int)lev);
})));
if (sources != null && sources.Count > 0)
{
sb.AppendFormat(" or ");
sb.AppendFormat("(Provider[{0}])", string.Join(" or ", sources.Select(el => "#Name='" + el + "'")));
}
sb.AppendFormat(")");
if (startDate.HasValue)
{
sb.AppendFormat(" and TimeCreated[#SystemTime >= '{0}']", startDate.Value.ToString("o"));
}
if (endDate.HasValue)
{
sb.AppendFormat(" and TimeCreated[#SystemTime <= '{0}']", endDate.Value.ToString("o"));
}
sb.AppendFormat("]]");
sb.AppendFormat(" </Select>");
sb.AppendFormat("</Query>");
sb.Append("</QueryList>");
try
{
EventLogSession sess = new EventLogSession();
sess.ExportLogAndMessages(logType, PathType.LogName, sb.ToString(), filePath, true, CultureInfo.CurrentCulture);
}
catch (Exception ex)
{
throw ex;
}
}
And here the enum
public enum EventViewerCriticalityLevel
{
Fatal = 1,
Error = 2,
Warning = 3,
Info = 4,
Comment = 5
}
It will generate evtx files that you can read with the event viewer console.
Hope it helps !
I have a signup page that have many filed. Many of them should filled by user.
I use RequiredFieldValidator and RegularExpressionValidator for validate in client side.
Should I validate them in server side? How?
I wrote this code. I use many if and else if. Is this correct?
CaptchaControl1.ValidateCaptcha(txtSecureImg.Text);
if (CaptchaControl1.UserValidated)
{
if (txtFName.Text != string.Empty && txtLName.Text != string.Empty && txtUserName.Text != string.Empty && txtEmail.Text != string.Empty && txtPass.Text != string.Empty && txtCPass.Text != string.Empty && txtSecureImg.Text != string.Empty)
{
if (RegEx.EmailValidate(txtEmail.Text) == 1 && RegEx.PasswordValidate(txtPass.Text) == 1 && RegEx.UserName(txtUserName.Text) == 1)
{
try
{
// insert in database
}
catch (Exception)
{
lblMsg.Text = "Error";
}
}
else if(RegEx.EmailValidate(txtEmail.Text) == 0)
{
EmailRegularExpression.Visible = true;
}
else if(RegEx.PasswordValidate(txtPass.Text) == 0)
{
passRegularExpression.Visible = true;
}
else if(RegEx.UserName(txtUserName.Text) == 0)
{
UnameRegularExpression.Visible = true;
}
}
else if(txtFName.Text == string.Empty)
{
RequiredFieldValidator1.Visible = true;
}
// continue like above for another filed
}
else
{
lblMsg.Text = "Please insert Secure Image";
}
And :
public static int EmailValidate(string Mail)
{
int i = 0;
Regex regExEmail = new Regex(#"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*");
if (regExEmail.IsMatch(Mail))
i = 1;
return i;
}
I'm assuming this is Web Forms...
The validation is run automatically. You can just use the Page.IsValid property: msdn
You'll still need to manually check the captcha field though.
CaptchaControl1.ValidateCaptcha(txtSecureImg.Text);
if (CaptchaControl1.UserValidated && Page.IsValid)
{
// Insert in db.
}
Since you use those validators, then you don't need to validate form in server side again like your codes.
But you should call Page.Validate()and then check page with Page.IsValid method.
from here
example
I have a gridview object that I am using to bind to a datasource. Upon the selectedIndexChanging event of the gridview, I would like to bring the data shown in the gridview into the textboxes on the form. However, when the data contains alphanumeric characters such as &'"", the data from the grid is showing ;amp, #S etc. and all other weird characters whenever I enter an alphanumeric character. Is there a way to prevent these characters from popping up in the textboxes when taking data from the grid?
The code that I have so far:
protected void grdActions_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedRow1 = grdActions.SelectedRow.RowIndex;
hdnIndexNo.Value = grdActions.Rows[selectedRow1].Cells[1].Text;
ddlActionType.SelectedValue = grdActions.Rows[selectedRow1].Cells[3].Text;
if (grdActions.Rows[selectedRow1].Cells[4].Text == null || grdActions.Rows[selectedRow1].Cells[4].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[4].Text == " ")
{
txtDetails.Text = string.Empty;
}
else
{
txtDetails.Text = grdActions.Rows[selectedRow1].Cells[4].Text;
}
if (grdActions.Rows[selectedRow1].Cells[5].Text == null || grdActions.Rows[selectedRow1].Cells[5].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[5].Text == " ")
{
txtCompletedDate.Text = string.Empty;
}
else
{
txtCompletedDate.Text = Convert.ToDateTime(grdActions.Rows[selectedRow1].Cells[5].Text).ToString("dd-MMM-yyyy");
}
ddlActionOwner.SelectedValue = grdActions.Rows[selectedRow1].Cells[7].Text;
if (grdActions.Rows[selectedRow1].Cells[8].Text == null || grdActions.Rows[selectedRow1].Cells[8].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[8].Text == " ")
{
txtAssignedTo.Text = string.Empty;
}
else
{
txtAssignedTo.Text = grdActions.Rows[selectedRow1].Cells[8].Text;
}
if (grdActions.Rows[selectedRow1].Cells[9].Text == null || grdActions.Rows[selectedRow1].Cells[9].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[9].Text == " ")
{
lblComments.Visible = false;
txtComments.Visible = false;
}
else
{
lblComments.Visible = true;
txtComments.Visible = true;
txtComments.Text = grdActions.Rows[selectedRow1].Cells[9].Text;
}
I used the Server.HTMLDecode() when transferring the data fromthe gridview to the textboxes. This ensured that all special characters were removed before it was sent back to the textboxes on the form