ASP.NET C# Form Submission Problems - c#

I have built a form with jqueryui-date picker - basically if the end date is less than or equal to start time it needs to display a message saying it must be greater than the start time before allowing the user to submit the form. Cannot see where i am going wrong.
Code Below on Submit
protected void btnSubmit_Click(object sender, EventArgs e)
{
DateTime startDate = Convert.ToDateTime(txtStartDate.Text + " " + ddlTime.SelectedValue);
DateTime endDate = Convert.ToDateTime(txtEndDate.Text + " " + ddlTime2.SelectedValue);
if (startDate >= DateTime.Now)
{
if (endDate <= startDate)
{
usrComment.Visible = true;
//usrComment.Text = "Return time needs to be greater than pickup time IF same day";
usrComment.Text = "Date =" + startDate + "Date 2 =" + endDate;
}
else
{
if (Page.IsValid)
{
string EmailServer = WebConfigurationManager.AppSettings["Email.Server"];
int ServerPort = Int32.Parse(WebConfigurationManager.AppSettings["Email.ServerPort"]);
string EmailServerUser = (WebConfigurationManager.AppSettings["Email.UserName"]);
string EmailServerPass = (WebConfigurationManager.AppSettings["Email.Password"]);
string EmailFrom = (WebConfigurationManager.AppSettings["Email.From"]);
string EmailTo = (WebConfigurationManager.AppSettings["Email.To"]);
string EmailToUser = txtEmail.Text;
string EmailSubject = "Quote Form submitted";
****.****.*****.Email m = new ****.****.Helpers.Email(EmailServer, ServerPort, EmailServerUser, EmailServerPass);
StringBuilder html = new StringBuilder();
html.AppendLine("<ul>");
html.AppendLine("<li>" + lblName.Text + ": " + txtName.Text + "</li>");
html.AppendLine("<li>" + lblEmail.Text + ": " + txtEmail.Text + "</li>");
html.AppendLine("<li>" + lblPhone.Text + ": " + txtPhone.Text + "</li>");
html.AppendLine("<li>" + lblVehicleType.Text + ": " + ddlVehicleType.SelectedValue + "</li>");
html.AppendLine("<li>" + lblPickupDate.Text + ": " + txtStartDate.Text + "</li>");
html.AppendLine("<li>" + ddlTime.SelectedValue + "</li>");
html.AppendLine("<li>" + lblReturnDate.Text + ": " + txtEndDate.Text + "</li>");
html.AppendLine("<li>" + ddlTime2.SelectedValue + "</li>");
html.AppendLine("</ul>");
m.SendHTMLEmail(EmailFrom, EmailTo, EmailSubject, html.ToString());
//Response.Redirect("/contact-us/quote-form-submitted.aspx");
}
usrComment.Text = "SUBMIT IT NOW!!!!!";
}
}
}
jQuery for the date picker
$(function () {
function getDiff() {
var from = $(".start").val();
var till = $(".fin").val();
var c = from.split("/");
beg = new Date(c[2], c[1] - 1, c[0]);
var d = till.split("/");
en = new Date(d[2], d[1] - 1, d[0]);
var rest = (en - beg) / 86400000;
var txt = rest == 0 ? "" : rest + " days"
$("#res").text(txt);
}
$(".start").datepicker({
changeMonth: false,
changeYear: false,
showAnim: "fadeIn",
gotoCurrent: true,
minDate: 0, //change this to +3 to start 3 days from now
dateFormat: "dd/mm/yy",
onSelect: function (dateText, inst) {
$(".fin").val(dateText);
$(".fin").datepicker("option", "minDate", dateText);
getDiff();
}
});
$(".fin").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
showAnim: "fadeIn",
onSelect: getDiff
});
//Disabling Copy, Paste, Cut
$('.start').bind('paste', function (e) {
e.preventDefault();
//alert("You cannot paste text into this textbox!");
window.alert = function () { };
});
$('.fin').bind('paste', function (e) {
e.preventDefault();
//alert("You cannot paste text into this textbox!");
window.alert = function () { };
});
});
So if you have a pickup date of 17/09/2013 and pickup time as 08:00 and the same for return date and time it should alert you with the message and if the return date is greater than or equal to start time the return pickup time needs to be greater than 08:00 if that makes sense?

It would be nice to have a useful, constructive comment. It doesn't matter if this is the "right way" to do it. I believe this is what you're trying to do. I've just added an else to the initial if statement to inform the user to choose a Start date later than now and altered the text of the other else statement to inform the user to pick a return date later than the start date.
protected void btnSubmit_Click(object sender, EventArgs e)
{
DateTime startDate = Convert.ToDateTime(txtStartDate.Text + " " + ddlTime.SelectedValue);
DateTime endDate = Convert.ToDateTime(txtEndDate.Text + " " + ddlTime2.SelectedValue);
if (startDate >= DateTime.Now)
{
if (endDate <= startDate)
{
usrComment.Visible = true;
usrComment.Text = "Please enter a Return date later than " + startDate;
}
else
{
if (Page.IsValid)
{
string EmailServer = WebConfigurationManager.AppSettings["Email.Server"];
int ServerPort = Int32.Parse(WebConfigurationManager.AppSettings["Email.ServerPort"]);
string EmailServerUser = (WebConfigurationManager.AppSettings["Email.UserName"]);
string EmailServerPass = (WebConfigurationManager.AppSettings["Email.Password"]);
string EmailFrom = (WebConfigurationManager.AppSettings["Email.From"]);
string EmailTo = (WebConfigurationManager.AppSettings["Email.To"]);
string EmailToUser = txtEmail.Text;
string EmailSubject = "Quote Form submitted";
****.****.*****.Email m = new ****.****.Helpers.Email(EmailServer, ServerPort, EmailServerUser, EmailServerPass);
StringBuilder html = new StringBuilder();
html.AppendLine("<ul>");
html.AppendLine("<li>" + lblName.Text + ": " + txtName.Text + "</li>");
html.AppendLine("<li>" + lblEmail.Text + ": " + txtEmail.Text + "</li>");
html.AppendLine("<li>" + lblPhone.Text + ": " + txtPhone.Text + "</li>");
html.AppendLine("<li>" + lblVehicleType.Text + ": " + ddlVehicleType.SelectedValue + "</li>");
html.AppendLine("<li>" + lblPickupDate.Text + ": " + txtStartDate.Text + "</li>");
html.AppendLine("<li>" + ddlTime.SelectedValue + "</li>");
html.AppendLine("<li>" + lblReturnDate.Text + ": " + txtEndDate.Text + "</li>");
html.AppendLine("<li>" + ddlTime2.SelectedValue + "</li>");
html.AppendLine("</ul>");
m.SendHTMLEmail(EmailFrom, EmailTo, EmailSubject, html.ToString());
//Response.Redirect("/contact-us/quote-form-submitted.aspx");
}
usrComment.Text = "SUBMIT IT NOW!!!!!";
}
}
else
{
usrComment.Visible = true;
usrComment.Text = "Please enter a Start date later than " + DateTime.Now;
}
}

I suggest you not to use any kind of custom function.
JquerUI-date picker have inbuilt functionality for comparing end date with start date.
Please try this
http://jqueryui.com/datepicker/#date-range

Related

Results in descending order

I've got a block of code which sums up time togged for various tasks in a project and returns the total hours logged per project (intMinutesLogged). How do I get my results n descending order?
static async void NotifyEntriesByWorkSpace(Dictionary<string, List<TimeEntry>> dicEntriesByWorkspace, string strChatURL)
{
string strMessage = "";
foreach (var kvpEntry in dicEntriesByWorkspace)
{
var lstTimeEntries = kvpEntry.Value;
string strTitle = "";
var intMinutesLogged = 0;
var intMinutesBillable = 0;
var intMinutesNonBillable = 0;
foreach (var objTimeEntry in lstTimeEntries)
{
if (objTimeEntry.Billable)
{
intMinutesBillable += objTimeEntry.TimeInMinutes;
}
else
{
intMinutesNonBillable += objTimeEntry.TimeInMinutes;
}
}
strTitle = Workspaces.getWorkspaceFromCache(kvpEntry.Key).Title;
//Console.WriteLine(intMinutesLogged + ": " + strTitle + "m");
intMinutesLogged = intMinutesBillable + intMinutesNonBillable;
Console.WriteLine(TimeLoggedMessage(intMinutesLogged) + ": " + strTitle + " " + "(Billable: " + TimeLoggedMessage(intMinutesBillable) + ";" + " " + "Non-Billable: " + TimeLoggedMessage(intMinutesNonBillable) + ")");
strMessage += TimeLoggedMessage(intMinutesLogged) + ": " + strTitle + " " + "(Billable: " + TimeLoggedMessage(intMinutesBillable) + ";" + " " + "Non-Billable: " + TimeLoggedMessage(intMinutesNonBillable) + ")" + "\n";
}
await SendMessage(strChatURL, strMessage);
}
static string TimeLoggedMessage(int intMinutesLogged)
{
return intMinutesLogged / 60 + "h" + " " + intMinutesLogged % 60 + "m";
}
You could use LINQ for this: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderbydescending?view=net-6.0
You could create a simple class or anonymous type to hold the integer values you're summing up (total minutes, billable minutes, non-billable minutes). Then you could populate a collection of this type within the code you shared and afterwards call OrderByDescending on it. You could order based on any of the three integer values.

Ho to set timeout for dataset in C#

when i run this code after 30 second give me error 'time out expire' . error comming exactly after fill dataset . by the way i add connection time out = 0 to my app config but still the problem is the same . so how i can set connection time out for this dataset
public void ExportInvoicesAccount()
{
var q = from h in hmsdb.TransHdrs
where h.Account.AccountsContracts.First().AccountsMain.ID == _mainaccid
&& h.PayMethod == "R"
&& h.CancelDate == null
&& h.TransDate >= _fromdate
&& h.TransDate <= _todate
group h by new
{
amID = h.Account.AccountsContracts.First().AccountsMain.ID,
amcode = h.Account.AccountsContracts.First().AccountsMain.Code,
amName = h.Account.AccountsContracts.First().AccountsMain.EngName,
acccode = h.AccountCode,
accid = h.AccountID,
accname = h.Account.EngName
} into qg
select new
{
amID = qg.Key.amID,
amCode = qg.Key.amcode,
amName = qg.Key.amName,
acccode = qg.Key.acccode,
accid = qg.Key.accid,
accname = qg.Key.accname
};
if (_facccode != "" && _taccccode == "")
{
q = q.Where(f => f.acccode == _facccode);
}
if (_facccode != "" && _taccccode != "")
{
q = q.Where(f => Convert.ToInt32(f.acccode) >= Convert.ToInt32(_facccode) && Convert.ToInt32(f.acccode) <= Convert.ToInt32(_taccccode) && f.acccode != "C" && f.acccode != "10281501مكرر ");
}
foreach (var x in q)
{
try
{
ClaimDS ds = new ClaimDS();
SP_EClaims_StatmentOfAccountGeneralTableAdapter adapt = new SP_EClaims_StatmentOfAccountGeneralTableAdapter();
ds.EnforceConstraints = false;
adapt.Fill(ds.SP_EClaims_StatmentOfAccountGeneral, x.amID, x.accid, 0, _fromdate, _todate, _inout,0,0,0, 0);
if (ds.SP_EClaims_StatmentOfAccountGeneral.Rows.Count != 0)
{
InvoicesByAcc rptinv = new InvoicesByAcc();
rptinv.SetDataSource(ds);
ExportOptions expop = new ExportOptions();
DiskFileDestinationOptions dfdo = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions pdfop = new PdfRtfWordFormatOptions();
FolderPath = _path + x.amCode + " - " + x.amName + "\\";
bool exists = System.IO.Directory.Exists(FolderPath);
if (!exists)
System.IO.Directory.CreateDirectory(FolderPath);
fpath = FolderPath;
rptinv.ExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
rptinv.ExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
DiskFileDestinationOptions objDiskOpt = new DiskFileDestinationOptions();
if (_inout == "O")
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-OUT" + ".pdf";
}
else if (_inout == "I")
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-IN" + ".pdf";
}
else
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-ALL" + ".pdf";
}
rptinv.ExportOptions.DestinationOptions = objDiskOpt;
rptinv.Export();
rptinv.Dispose();
rptinv.Close();
}
GC.Collect();
ds.Dispose();
ds.Clear();
}
catch (Exception ex)
{
string logpath = FolderPath + "E_Claim_ErrorLog.txt";
// This text is added only once to the file.
if (!File.Exists(logpath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(logpath))
{
//sw.WriteLine(ex.Message + "( " + "AccountMainID: " + x.amID + " - " + "AccountID: " + x.accid + " - "+ "ConsID: " + x.consid + " - " + "MRN: " + x.mrn + " )");
}
}
// This text is always added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = File.AppendText(logpath))
{
sw.WriteLine(ex.Message + " SP_EClaims_StatmentOfAccountGeneral" + "ExportInvoicesAccount" + "( " + "AccountMainID: " + x.amID + " - " + "AccountID: " + x.accid + " - " + "ConsID: " + "0" + " - " + "MRN: " + "0" + " )");
}
//MessageBox.Show(ex.Message + "AccountMainID: " + x.amID + "-"+ "AccountID: " + x.accid + "ConsID: " + x.consid + "MRN: " + x.mrn );
}
}
}

NUnit: To get Error message

I would like to know Is it possible to get error message (reason of why my testcase failed). For instance, below is my code of I am trying to find an element it will fail my test. Error message will display in NUnit. How to get that error message in my text file.
private DateTime _timestamp1;
private DateTime _timestamp2;
private string _TestNum;
private string _TestDetails;
[Test]
public void Initialize()
{
_timestamp1 = DateTime.Now;
_TestNum = "12345";
_TestDetails = "For test purpose";
TWebDriver driver = new TWebDriver();
{
driver.Navigate().GoToUrl("http://www.google.com");
driver.FindElement(By.Id("q"));
}
}
[TearDown]
public void cleanup()
{
string path = (#"..\..\Result\");
_timestamp2 = DateTime.Now;
TimeSpan timediff = (_timestamp2) - (_timestamp1);
string TotalTime = timediff.Minutes + " minutes and " + timediff.Seconds + " seconds";
if ((TestContext.CurrentContext.Result.Status == TestStatus.Passed) || (TestContext.CurrentContext.Result.State == TestState.Success))
{
string status = "Passed";
File.WriteAllText(Path.Combine(path, "Passed" + ".txt"), "Test Case No.: " + _TestNum + string.Format(Environment.NewLine) + "Test Details: " + _TestDetails + string.Format(Environment.NewLine) + "Start Time: " + _timestamp1 + string.Format(Environment.NewLine) + "End Time: " + _timestamp2 + string.Format(Environment.NewLine) + "Total Time: " + TotalTime + string.Format(Environment.NewLine) + "Status: " + status);
}
else
{
string status = "Failed";
File.WriteAllText(Path.Combine(path, "Passed" + ".txt"), "Test Case No.: " + _TestNum + string.Format(Environment.NewLine) + "Test Details: " + _TestDetails + string.Format(Environment.NewLine) + "Start Time: " + _timestamp1 + string.Format(Environment.NewLine) + "End Time: " + _timestamp2 + string.Format(Environment.NewLine) + "Total Time: " + TotalTime + string.Format(Environment.NewLine) + "Status: " + status);
}
}
NUnit Version: 2.6.4

send List<> values with Body in mail - SMTP server

I have to send mail through SMTP server. I can able to send it with single values. But, I want to send List<> values as message body in table format or some other structure. I include my code following :
MailMessage mailObj = new MailMessage("abc#gmail.com", "xyz#gmail.com", "Reg : send mail",
"Emp Name :" + "Emp1" + Environment.NewLine + "Date From : " + Mon + "Date To : " + Fri);
SmtpClient SMTPServer = new SmtpClient("smtp.gmail.com", ***);
SMTPServer.Host = "smtp.gmail.com";
SMTPServer.EnableSsl = true;
SMTPServer.Timeout = 200000;
SMTPServer.Credentials = new System.Net.NetworkCredential("asd#gmail.com", "******");
SMTPServer.Send(mailObj);
I have my list of values as follows :
List<TimesheetValues> mailBody = new SampleDAO().GetDataForMail(dt1, satDate);
How can I include this List<> values with body and send?
I try with following :
List<TimesheetValues> Msg = new List<TimesheetValues>(); string strMsg = ""; int n=1;
foreach(var item in mailBody)
{
strMsg = strMsg + "<table><tr><td>" + n + "</td><td>" + item.Project_Name + "</td><td>" + item.Task_Name + "</td><td>" + item.Notes + "</td><td>" + item.Hrs_Worked + "</td></tr></table>";
n++;
}
strMsg = strMsg + "</br>";
MailMessage mailObj = new MailMessage("abc123#gmail.com", "xyz123#gmail.com", "Reg : Timesheet",
"Emp Name :" + "Emp1" + Environment.NewLine + "Date From : " + Mon + "Date To : " + Fri);
mailObj.Body = "Emp Name : " + "Emp1" + Environment.NewLine + "Date From : " + Date2 + " Date To : " + Date6 + Environment.NewLine + strMsg;
Now I get all records but i have tr td tags with in records and not display as a table. How can i acheive this ?
can anyone help to overcome this..
Thanks in advance...
If you want to read the string into a list again, serialize is better.
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(yourList);
mailObj.Body = json;
You can also deserialize in the other side:
List<string> g = JsonConvert.DeserializeObject<List<string>>(body);
I try with this following :
string strMsg = ""
strMsg = timsheetMail + " <table style=\"border-collapse:collapse; text-align:center;\" border=\"1\"><tr><td> Date </td><td> Working Hours </td><td> Task </td><td>Comments</td></tr>";
List<TimesheetValues> Msg = new List<TimesheetValues>(); int n=1;
foreach(var item in mailBody)
{
timesheetData = new TimesheetDetailModel();
timesheetData.Task_Id = matrix.Task_Id;
timesheetData.Hours = matrix.Hours;
//timesheetData.Date = matrix.Date.Date;
timesheetData.Date = matrix.Date.AddDays(1);
timesheetData.EmpId = Convert.ToInt32(Session["EmpId"].ToString());
timesheetData.Notes = matrix.Notes;
strMsg = strMsg+ " <tr><td> " + timesheetData.Date.ToString("dd/MM/yyyy") + "</td><td>" + timesheetData.Hours + "</td><td>" + task + "</td><td>" + timesheetData.Notes + "</td></tr>";
n++;
}
strMsg = strMsg + "</table>";
Its working good now..

Browser detection

I need to separate IE and FF browsers from others
it's a pseudo-code :
If (CurrentBrowser == IE(6+) or FF(2+) )
{
...
}
else
{
...
}
in protected void Page_Load() event (think so)
if ((Request.Browser.Type == "IE") || (Request.Browser.Type == "FF"))
{
WebMsgBox.Show("1111");
}
no effects :-/ what is IE and FF types?
if (Request.Browser.Type.Contains("Firefox")) // replace with your check
{
...
}
else if (Request.Browser.Type.ToUpper().Contains("IE")) // replace with your check
{
if (Request.Browser.MajorVersion < 7)
{
DoSomething();
}
...
}
else { }
Here's a way you can request info about the browser being used, you can use this to do your if statement
System.Web.HttpBrowserCapabilities browser = Request.Browser;
string s = "Browser Capabilities\n"
+ "Type = " + browser.Type + "\n"
+ "Name = " + browser.Browser + "\n"
+ "Version = " + browser.Version + "\n"
+ "Major Version = " + browser.MajorVersion + "\n"
+ "Minor Version = " + browser.MinorVersion + "\n"
+ "Platform = " + browser.Platform + "\n"
+ "Is Beta = " + browser.Beta + "\n"
+ "Is Crawler = " + browser.Crawler + "\n"
+ "Is AOL = " + browser.AOL + "\n"
+ "Is Win16 = " + browser.Win16 + "\n"
+ "Is Win32 = " + browser.Win32 + "\n"
+ "Supports Frames = " + browser.Frames + "\n"
+ "Supports Tables = " + browser.Tables + "\n"
+ "Supports Cookies = " + browser.Cookies + "\n"
+ "Supports VBScript = " + browser.VBScript + "\n"
+ "Supports JavaScript = " +
browser.EcmaScriptVersion.ToString() + "\n"
+ "Supports Java Applets = " + browser.JavaApplets + "\n"
+ "Supports ActiveX Controls = " + browser.ActiveXControls
+ "\n";
MSDN Article
Try the below code
HttpRequest req = System.Web.HttpContext.Current.Request
string browserName = req.Browser.Browser;
private void BindDataBInfo()
{
System.Web.HttpBrowserCapabilities browser = Request.Browser;
Literal1.Text = "<table border=\"1\" cellspacing=\"3\" cellpadding=\"2\">";
foreach (string key in browser.Capabilities.Keys)
{
Literal1.Text += "<tr><td>" + key + "</td><td>" + browser[key] + "</tr>";
}
Literal1.Text += "</table>";
browser = null;
}
I would not advise hacking browser-specific things manually with JS. Either use a javascript library like "prototype" or "jquery", which will handle all the specific issues transparently.
Or use these libs to determine the browser type if you really must.
Also see Browser & version in prototype library?
For browser compatibility you can use this code. This method returns browser name and version :
private string GetBrowserNameWithVersion
{
var userAgent = Request.UserAgent;
var browserWithVersion = "";
if (userAgent.IndexOf("Edge") > -1)
{
//Edge
browserWithVersion = "Edge Browser Version : " + userAgent.Split(new string[] { "Edge/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Chrome") > -1)
{
//Chrome
browserWithVersion = "Chrome Browser Version : " + userAgent.Split(new string[] { "Chrome/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Safari") > -1)
{
//Safari
browserWithVersion = "Safari Browser Version : " + userAgent.Split(new string[] { "Safari/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Firefox") > -1)
{
//Firefox
browserWithVersion = "Firefox Browser Version : " + userAgent.Split(new string[] { "Firefox/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("rv") > -1)
{
//IE11
browserWithVersion = "Internet Explorer Browser Version : " + userAgent.Split(new string[] { "rv:" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("MSIE") > -1)
{
//IE6-10
browserWithVersion = "Internet Explorer Browser Version : " + userAgent.Split(new string[] { "MSIE" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Other") > -1)
{
//Other
browserWithVersion = "Other Browser Version : " + userAgent.Split(new string[] { "Other" }, StringSplitOptions.None)[1].Split('.')[0];
}
return browserWithVersion;
}
I tried and found the solution for the same
public static string GetBrowserDetails()
{
string BrowserDetails = HttpContext.Current.Request.Browser.Browser + " - " + HttpContext.Current.Request.Browser.Version + "; Operating System : " + HttpContext.Current.Request.Browser.Platform;
return BrowserDetails;
}
OUTPUT :
Chrome - 88.0; Operating System : WinNT
use from
Request.Browser
this link will help you :
Detect the browser using ASP.NET and C#

Categories