Getting Null value on parameter in querystring parameter - c#

in my application i have send one link to User's email id he can download software on clicking this link....now my url is look like....
http://www.abc.co.in/Download.aspx?period=11/04/2013%2012:29:20%20PM&ProductName=Otja
and my code for retriving this value on pageload download.aspx page is
string PName = Request.QueryString["ProductName"] as string;
string myDate = Request.QueryString["period"];
if (!String.IsNullOrEmpty(myDate))
{
myDate = myDate.Replace("!", ":");
}
DateTime dt1 = Convert.ToDateTime(myDate);
DateTime dt2 = DateTime.Now;
TimeSpan variable = dt2 - dt1;
if (variable.TotalMinutes > 5)
{
//Response.Write("Download time is expired now");
lblmsg.Visible = true;
lblmsg.Text = "Download time is expired now";
}
else
{
lblmsg.Visible = true;
lblmsg.Text = "U can Still Download";
}
but this is not working i tested and before 5 Minute and after minutes it is only shows "You can still download" so i think my error is that i can not retrive that productname and period value on querystring on this download.aspx page..please help me.. thanks
i think there should be error..... String was not recognized as a valid DateTime. thats why it is pass null value so any solution ???

You said you think that your code is not able to retrieve the query params. Why don't you confirm that by printing the values first.
The Request.QueryString() looks correct.
There could be issue with your logic which may case the else to execute.
Based on more information provided by you please try this -
Variable myDate value must be “11-04-2013 06 36”. Please confirm.
Instead of Convert.ToDateTime(myDate); try this
DateTime.ParseExact(myDate, "dd-MM-yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture);

Related

if else statement between datetime but disregard time

Can you help me in removing the time in my code or rather correct my code for possible errors.
Thanks. Here's my code and ill state the error later.
else if (this.dateTimePicker1.Value != DateTime.Now)
{
this.chkBxLessNinety.Enabled = false;
string dateInString = Convert.ToString(Convert.ToDateTime(_dr[4]));
DateTime startdate = DateTime.Parse(dateInString);
DateTime datelimit = startdate.AddDays(90);
//string date = Convert.ToString(Convert.ToDateTime(datelimit.Date).ToString("mm/dd/yyyy"));
string mydate1 = this.dateTimePicker1.Value.ToShortDateString();
if (mydate1 > datelimit)
{
MessageBox.Show("Cannot Sync data more or equal to 90 days");
}
else
{
}
the line if (mydate1 > datelimit) shows an error which says > cannot be applied as operand of type string an datetime.
Please help.
Thanks in advance.
You want to compare DateTimes with each other. Since you want to exclude the time portion then the Date property will make both dates at midnight hour.
DateTime mydate1 = this.dateTimePicker1.Value;
if (mydate1.Date > datelimit.Date)
{
MessageBox.Show("Cannot Sync data more or equal to 90 days");
}
Just remove .ToShortDateString()
And also:
string dateInString = Convert.ToString(Convert.ToDateTime(_dr[4]));
DateTime startdate = DateTime.Parse(dateInString);
Don't convert from DateTime to string and then back to DateTime, it's pointless
You can't use the > to compare a string and a DateTime. Instead, you should replace
string mydate1 = this.dateTimePicker1.Value.ToShortDateString();
with
DateTime mydate1 = this.dateTimePicker1.Value;
This way, you'll be comparing things of the same type (DateTime).

Date format conversion c#

Guys I have a string having a date in the format dd/mm/YYYY.
However I need to use it a datetimepicker control.
I cannot assign the value to the datetimepicker, i tried as
string exp = "SELECT UserPwdExpiry FROM " + MainForm.schema + "Adm.SysUser WHERE USerId ='" + cmbUserID.Text + "'";
cmd = ccs.CreateCommand();
ccs.Open();
cmd.CommandText = exp;
DateTime expiry_ = ((DateTime)cmd.ExecuteScalar());
//string _expiry_= expiry_.ToShortDateString();
ccs.Close();
assigning here
dtpPasswordExpiry.Value = Convert.ToDateTime(_expiry_);
It gives me an error saying, FORMAT SHOW BE BETWEEN MaxDate and MinDate.
Help please.
if DateTime expiry_ = ((DateTime)cmd.ExecuteScalar()); this line running without errors you already have Datetime object. So you can directly set it as
tpPasswordExpiry.Value =expiry_;
But above line will fail if you store datetime as string in database then
string _User_modify= (string)cmd.ExecuteScalar();
DateTime dt;
if(DateTime.TryParseExact(_User_modify,
"dd/MM/YYYY",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
tpPasswordExpiry.Value =dt;
}
We already have:
DateTime expiry = ((DateTime)cmd.ExecuteScalar());
so: we know the value is a DateTime. The DateTimePicker control's .Value property is a DateTime, so the correct syntax here is:
dtpPasswordExpiry.Value = expiry;
The only thing that leaves, based on the error message, is the MinDate and MaxDate. I suspect you need to change the values of those two properties such that your expiry is a legal value not outside the range MinDate - MaxDate. If unsure, simply print out the values of expiry, dtpPasswordExpiry.MinDate and dtpPasswordExpiry.MaxDate.

DateTime Error in URL

I'm developing an application in which I pass one URL on inquiry.aspx page and that URL will send a message to the user's email address.
That URL looks like:
mail.Body += string.Format("<a href=\"http://www.abc.co.in/Download.aspx?period="
+ DateTime.Now.ToString("dd-MM-yyyy hh mm")
+ "&ProductName=" + productName + "\">Demo Download</a>");
Now I'm retrieving this to the pageload event of download.aspx page. My code is:
string PName = Request.QueryString["ProductName"] as string;
string myDate = Request.QueryString["period"] as string;
DateTime dt1 = Convert.ToDateTime(myDate);
DateTime dt2 = DateTime.Now;
int day1, day2;
day1 = dt1.Day;
day2 = dt2.Day;
TimeSpan variable = dt2 - dt1;
if (day1!=day2)
{
//Response.Write("Download time is expired now");
lblmsg.Visible = true;
lblmsg.Text = "Download time is expired now";
}
else
{
lblmsg.Visible = true;
lblmsg.Text = "U can Still Download";
}
I'm getting the error:
String was not recognized as a valid DateTime
My output URL after user clicking on that link from his email id looks like:
http://www.abc.co.in/Download.aspx?period=11-04-2013%2006%2036&ProductName=Otja
Here datetime is used for condition that after same day means mail is send to user today and today only he can download. Tommorrow onward it will show message that you are not able to download software now. So that is the reason to pass datetime on URL, but I'm getting error. Please someone help me it's required badly.
Couple of things you can try.
first and foremost change your Date format to Universal Date format and not regional. Assume you are using .net web application, I have seen issues where client execution is different for server.
yyyy-MM-dd
secondly, your datetime format string is not quite right, i.e. missing colon between hour and min. Also if you are trying the said format you must specify your TT or 24 hour. At the end of the say your format would look as follows
yyyy-MM-dd hh:mm tt
or
yyyy-MM-dd HH:mm
in addition the above you may want to use date -compare
DateTime dt1 = Convert.ToDateTime(myDate).Date;
DateTime dt2 = DateTime.Now.Date;
if(dt1 != dt2)
{
//...
}
else
{
//...
}
Since you are using DateTime.ToString("dd-MM-yyyy hh mm") when creating the URL, you should use the same format string when parsing it:
DateTime dt1 = DateTime.ParseExact(myDate, "dd-MM-yyyy hh mm", System.Globalization.CultureInfo.InvariantCulture);
Best practice requires you to also pass the culture when creating the URL:
DateTime.ToString("dd-MM-yyyy hh mm", CultureInfo.InvariantCulture).
By the way, you should not pass the date in URL in your code sample. Instead you would store the date together with a token in database and pass that token instead. Alternatively you could encrypt the date. The problem is that the recipient is able to change the date and thus overriding your checks for download availability.

DateTime.Parse Converting String to DateTime Format Equals to DateTime Field in Database

I am trying to convert a date value of YYYY/MM/DD from a textbox to datetime, when the value is correct it is ok but when I tried to input an incorrect data to check with the database, the error return as String was not recognized as a valid DateTime.
Here is my code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string format = "YYYY-MM-DD HH:MM:SS";
DateTime birthday = DateTime.Parse(txtBday.Text);
DataSet ds = new DataSet();
ds = (newService.checkAccount());
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dRow in ds.Tables[0].Rows)
{
string accountNo = dRow["ACCTNO"].ToString();
DateTime birthDate = DateTime.Parse(dRow["DATEOFBIRTH"].ToString());
if (accountNo == txtAccountNo.Text.ToString() && birthDate == birthday)
{
lblMessage.Text = "<br>Account Number Exist. You may now proceed with the registration<br><br>";
HttpCookie lmsCookie = new HttpCookie("id");
lmsCookie.Value = txtAccountNo.Text;
Response.Cookies.Add(lmsCookie);
Response.Redirect("Step2.aspx");
}
else
{
Image2.Visible = false;
lblMessage.Text = "<br>Please check your information and try again." + "<br>Be sure you are entering the correct information.For further assistance, call (+632) 404-2790.<br><br>";
}
}
}
}
For example I will enter a data that will match in the database, the program will proceed otherwise if I am going to input a data that does not match with any of the existing records in the database, the program will triggers an error, String was not recognized as valid datetime.
When you parsing can fail for a reason other than a bug, instead of this:
DateTime birthDate = DateTime.Parse(dRow["DATEOFBIRTH"].ToString())
(which throws an exception as you've seen), use DateTime.TryParse:
DateTime birthDate;
if (DateTime.TryParse(dRow["DATEOFBIRTH"].ToString(), out birthDate))
{
// Success case
}
else
{
// Handle error case
}
I note that you're not using your format variable, by the way. If you know what the format will be (and your question disagrees with your code, btw) it would be better to use TryParseExact:
if (DateTime.TryParseExact(dRow["DATEOFBIRTH"].ToString(), "YYYY/MM/dd",
CultureInfo.InvariantCulture, DateTimeStyles.None,
out birthDate))
...
Definitely, it will throw an exception when an unsupported format is tried to convert into a datetime. So, before converting you should Parse it by using DateTime.TryParse method.
Sovel ,
Step 1:
this._checkInOutDTO.NgayCham = DateTime.Parse(this.DGVDuLieuVaoRa.Rows[num15].Cells[1].Value.ToString());
// this._checkInOutDTO.NgayCham = Convert.ToDateTime(this.DGVDuLieuVaoRa.Rows[num15].Cells[1].Value.ToString());
Step 2:
Format : dd/MM/yyyy

DateTime and String Validation

I have a simple question about DateTime in c#.
I have a textbox where I ask the user to input a date.
I want to validate that the textbox is not empty before parsing the string to a datetime to validate if the date is in the right format.
Here is a bit of my code:
String strStartDate = txtStartDate.txt;
DateTime StartDate = DateTime.Parse(strStartDate);
I have other text boxes for the names and such and I also validate if they are empty with a if statement like this (same if statement to validate if strStartDate is empty):
if (strFirstName.Trim() == "")
{
txtFirstName.BackColor = System.Drawing.Color.Yellow;
errorMessage = errorMessage + "First Name may not be empty. ";
}
else
{
txtFirstName.BackColor = System.Drawing.Color.White;
}
The debugger stops as soon as I try the submit button, it says that String was not recognized as a valid DateTime.
Is there a way to see if the string is empty before validating the DateTime?
You can also use TryParse:
string SomeDate = "1/1/2012";
DateTime dt;
var success = DateTime.TryParse(SomeDate, out dt);
Then you can check success to see if it was a valid date or not. This will protect you from any invalid date string, not just an empty or null string.
String.IsNullOrEmpty will do what you want

Categories

Resources