ASP.NET generated code: where does "dateorder" come from? - asp.net

For background, we are in the process of upgrading to Windows Server 2012 R2, and testing revealed that some date input textboxes on our ASP.NET site aren't working as intended. The textboxes have a CompareValidator defined for them to check if one date is later than the other.
<asp:CompareValidator ID="CompareValidator3" runat="server" ControlToCompare="txtStartDate"
ControlToValidate="txtEndDate" ErrorMessage="..." Operator="GreaterThan" Type="Date"
Display="Dynamic"></asp:CompareValidator>
This CompareValidator is failing all the time now, on Windows Server 2012, whereas the old site hosted on Windows Server 2008 did not have this problem. I have done some digging and I think the most likely culprit is the change in default date format for the Canada region in Windows Server 2012. In the generated code for the page, the DOM element for the validator has a property "dateorder" that's always being set to "ymd". This value is "dmy" on the old site.
...
cutoffyear: "2029"
dataset: DOMStringMap
dateorder: "ymd"
dir: ""
display: "Dynamic"
...
Because our inputs take date strings like "01/01/2015", the "ymd" pattern is not matched and the validator returns false. I have changed the date format settings everywhere that I can think of, and even tried changing the IIS site's .NET Globalization settings to use another culture (en-GB), and nothing has worked. I'm really curious as to where this "ymd" setting comes from, and how to change it. Any help is greatly appreciated. Thanks!

"dateorder" comes from BaseCompareValidator which essentially reads CultureInfo.CurrentCulture
DateTimeFormatInfo dateTimeFormat = CultureInfo.CurrentCulture.DateTimeFormat;
string pattern = dateTimeFormat.ShortDatePattern;
string dateorder = (pattern.StartsWith ("y", true, Helpers.InvariantCulture) ? "ymd" : (pattern.StartsWith ("m", true, Helpers.InvariantCulture) ? "mdy" : "dmy"));
Now the gotcha as pointed here, is that Regional Settings is per-user and you might want to check the account the Application Pool was running under.

Maybe somebody changed the date format in the Windows OS on the old computer? But how about trying to force it within your application...my idea is to do it in the Global.asax file (you may have to add that file to the root of the application if it is not already there). Then, something like this:
using System.Globalization;
using System.Threading;
protected void Application_BeginRequest(Object sender, EventArgs e)
{
CultureInfo myCulture = (CultureInfo) System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
myCulture.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";
myCulture.DateTimeFormat.DateSeparator = "-";
Thread.CurrentThread.CurrentCulture = myCulture;
}

Have you try to change sort date from control panel regional setting. Dateorder and cutoffyear etc attribute are used by validation JavaScript generated by .net for validator control to function on browser. Value of these comes from server settings. IIS only picks as per server config and generats HTML.

Related

ASP.NET Application is displaying american date formats

One of my development applications has today started displaying American formatted short dates where I am expecting British formatting.
The dates are being rendered using date.ToShortDateString()
I have already checked my Regional settings, keyboard settings, browser settings and web.config. These are all set to English (UK) or not changed. I've also rebooted a number of times.
A mobile version of the same application, running from the same development server, and same website (different web application) is working correctly.
Environment:
Windows 7 64 Bit
Visual Studio 2010 Professional
IIS 7.5
Where else can Regional Settings be changed that might influence display of dates?
The windows regional settings does not affect any website, unless the website is programmed to get the regional settings from the browser preferred languages and apply them to the ASP site
Use the globalization option in the web.config
<globalization culture="es-AR" uiCulture="es" />
OR
Set the value in the global.aspx Application_BeginRequest method
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim lang As String = "es"
If HttpContext.Current.Request.Path.Contains("/en/") Then
lang = "en"
ElseIf HttpContext.Current.Request.Path.Contains("/pt/") Then
lang = "pt"
ElseIf HttpContext.Current.Request.Path.Contains("/es/") Then
lang = "es"
End If
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang)
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang)
End Sub
From MSDN
The value of the current DateTime object is formatted using the pattern defined by the DateTimeFormatInfo.ShortDatePattern property associated with the current thread culture. The return value is identical to the value returned by specifying the "d" standard DateTime format string with the ToString(String) method.
Have you tried changing the culture for the current thread? This can be set on a per page basis as well - http://msdn.microsoft.com/en-us/library/bz9tc508%28v=vs.85%29.aspx.

Conversion from string "31/03/2012" to type 'Date' is not valid

My web app is running perfectly in asp vb.net editor. But when i run my web app through IIS7 then i get this error. What am i missing in configuring IIS7? Is there anyone who can suggest something?
Thanks in Advance
Because your IIS7 is configured for the English Language and that date is probably Italian or something similar. You'll have to tell to the Date.Parse which culture to use.
Something like
dateValue = Date.Parse(yourDate, CultureInfo.CreateSpecificCulture("it-IT"))
Or you can change the culture in your IIS7
Here there are the instructions
for example if you use the UI
Using the UI Open IIS Manager and navigate to the level you want to
manage. (omissis)
In Features View, double-click .NET Globalization.
On the .NET Globalization page, in the property sheet, click to select
the global setting you want to edit, and select a value from the
drop-down list.
In the Actions pane, click Apply.
Or you could set the culture of your app in the web.config
<system.web>
<globalization culture="it-IT" uiCulture="it-IT"/>
</system.web>
If you are sure that the date is always in exactly that format, then you can use ParseExact instead:
var date = DateTime.ParseExact(
"31/03/2012",
"dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
You can also use the CDate function to parse the date.
Dim dDate As Date = CDate("31/03/2012")
The advantage of using this function over the DateTime parsing functions is that you can feed it any acceptable format of date string and it will convert it. It will throw an error if it can't parse the date.

ASP.net problem with Regional & Language Options (win2k3)

I have a TextBox in an Asp.net form. there is a simple javascript witch separates each three digits in TextBox. it works fine when you enter data in TextBox. I used coma , for separating digits and used dot . as floating point character.
as I said every thing works fine when I am entering data in TextBox. but when the post-back occurs and saved data returns to client, every .(s) has been removed (for example 2.3 saved as 23 and digits in TextBox are separated by . instead of ,.
this problem occurs just in a specific server (windows server 2003 sp1) and works fine in other windows server 2003 (SP1)! I am experiencing this problem for first time!
But I think the problem is because of specific Regional & Language Options in the server. This server is joined to a domain controller. when I change the regional and language options to this set:
Decimal Symbol -> .
Digit Grouping Symbol -> ,
nothing changes.
when I check the following item after customizing settings :
Apply All Settings to the current user account and to the default user profile -> checked
when I restart the Server, It jumps out from domain and need to be re-joined to domain controller! and of-course nothing changes again!
Do you had this problem? any solution please!
I can not post code here, because the code is too complex and I am sure problem is not because of code because it is working every where unless the specified server.
EDIT
Also setting regional and language options for network service user may help to solve the problem. any body knows how can I do this ?
Have you tried using the globalization tag in your web.config? This prevents you from running into trouble when multiple servers are configured differently (ie. different languagepacks).
<configuration>
<system.web>
<globalization
culture="en-US"
uiCulture="en-US" />
</system.web>
</configuration>
After goofing around with a similar problem for WAY to long I did the following with the help of a number of clues (also found on StackOverFlow, StackOverFlow rocks by the way...)
The first thing I did was dump out what the server was actually thinking (Page_Load):
var dtInfo = System.Globalization.DateTimeFormatInfo.CurrentInfo;
DisplayDebugInfo(String.Format(
"Culture({0}/{1}), DateFormat(SD:{2},DS:{3})",
System.Globalization.CultureInfo.CurrentCulture.Name,
System.Globalization.CultureInfo.CurrentUICulture.Name,
dtInfo.ShortDatePattern, dtInfo.DateSeparator));
Also on Windows 2003, I tried fixing the regional setting via the regular control panel but with no success.
I also tried setting the globalization settings in the web.config as mentioned in the other solution but with little effect.
It seems that once you start messing with the regional setting you can quickly get to the point where things are messed up. I decided to avoid messing with the registry and go for a code solution because then I would not have to worry when my code was released to production.
I added the following code to the base class for my page so that it would fix it everywhere. You could also place it in the Page_Load.
using System.Globalization;
using System.Threading;
// Fix the cultural settings...
CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
culture.DateTimeFormat.DateSeparator = "/";
Thread.CurrentThread.CurrentCulture = culture;
Problem solved. For me anyway.

dates behaving differently on different dbs?

I have an asp.net webpage, with a jQuery datepicker on it.
I am in the UK, so when I enter 28/02/2010, I expect it to resolve to 28th Feb 2010.
This is working as expected on my local dev env - but not on our QA or prod-like envs - or one of the other dev machines. In these cases it seems to attempt to resolve it to American date format - and fails validation as it is out of range.
The jQuery seems to generate the correct date each time - which leads me to think it may be a database issue.
I am using SQL Server 2005, my collation is Latin1_General_CI_AS, my colleagues are using collation SQL_Latin1_General_CP1_CI_AS, and a Chinese one.
Given that we don't have control over the prod SQL Server installation (just our db), what is the best way to make this work in a standard way? Change the db settings, or the code that uses it?
Thanks in advance!
- L
[EDIT to add code info]
This is my view code to call the datepicker:
<%=Html.TextBox("DateOfBirth", Model.DateOfBirth.ToShortDateString(), new { #class = "datepicker" })%>
Here is the js for the datepicker:
DatePickerSettings = {
setup: function () {
$(".datepicker").datepicker({
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true
});
}
};
And this is how I specify the date in the model:
[Required]
[DisplayName("Date of Birth")]
public virtual DateTime DateOfBirth { get; set; }
The date appears correct inthe controller and repository... until it hits the db.
Thanks :)
I was hoping to wait until you'd updated the question with some more information, but as I've seen some answers suggesting that you change the string format you use to talk to the database...
Don't send dates as raw text in SQL queries.
Use a parameterized query, which means you don't need to worry about formatting the value at all. Then you've just got to make sure that you can get the date format correct between the browser and ASP.NET.
Aside from anything else, if you're including user data in SQL queries directly, you'll generally be opening yourself up to SQL injection attacks. Always use parameterized queries (unless your web app is really a "run this SQL" test tool...)
If you're already using parameterized queries, then the problem is likely to be between the browser and ASP.NET, and the database part is irrelevant. Divide and conquer the problem: chase the data as it passes through different layers (browser, jQuery, ASP.NET etc) until you find out where it's gone wrong. Don't even think about a fix until you know where it's gone wrong.
Is your page Culture aware?
You can determine UI Cutlure information for different browsers(locales) and have your ASP.NET Culture constant.
The Culture value determines the results of culture-dependent functions, such as the date, number, and currency formatting, and so on. The UICulture value determines which resources are loaded for the page
Check out this MSDN link:
How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization
http://msdn.microsoft.com/en-us/library/bz9tc508(v=VS.85).aspx
Use CONVERT to change the date format to a standard that is accepted across all environments.
CAST and CONVERT
I'd have to see the code that interprets the dates to know for sure, but a likely suspect is the Region and Language settings on the machines where the code is running. Make sure it is set appropriately for your region.
However, if you can't change settings on the servers, you should probably explicitly use CAST or CONVERT in SQL Server to force it to parse it in the region specific way you expect the data will be entered.
You also need to check your ASP.Net layer, and see what it is running in.
Check the machine configuration and check they are set to run in the same date/time/region.
Change your code to use yyyymmdd format.
As far as i know it works in all the DBs
Just to add another opinion here, I find dd/mmm/yyyy the best date format to send to databases as it's completely unambiguous across cultures.

How do you globally set the date format in ASP.NET?

How do you globally set the date format in ASP.NET?
My local machine and servers have Regional Settings set to "English (New Zealand)".
When I format a date with dd/MM/yyyy I expect to see 19/11/2008 for today for example.
Until recently, that is what I did in fact get from both my local machine and the servers.
Just recently, for some mysterious reason, our local machines have changed ever so slightly. Despite still be set to "English (New Zealand)", the date delimter has changed from / to -! The same change has not occurred on the servers which still show "English (New Zealand)" and the / for the date delimter.
So now for my local machine, for the format dd/MM/yyyy I get 19-11-2008 instead of 19/11/2008.
This is a little disconcerting.
The only way around it that I can see so far is to escape the slashes and set the format to dd\/MM\/yyyy. It seems to work, but it doesn't seem to be the ideal solution.
Can anyone please help?
NOTE: This is for an intranet application and I do not care about true globalisation. I just want to fix the date format and not have it change on me.
You can change the current thread culture in your Global.asax file, and override the date format for example:
using System.Globalization;
using System.Threading;
//...
protected void Application_BeginRequest(Object sender, EventArgs e)
{
CultureInfo newCulture = (CultureInfo) System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
newCulture.DateTimeFormat.ShortDatePattern = "dd-MMM-yyyy";
newCulture.DateTimeFormat.DateSeparator = "-";
Thread.CurrentThread.CurrentCulture = newCulture;
}
In web.config, set tag as per the following documentation
<system.web>
<globalization culture="en-NZ" uiCulture="en-NZ"/>
</system.web>
A good way is configure the Web.Config, the date format appear in all components of a aspx
<system.web>
<globalization uiCulture="en" culture="en-NZ" />
</system.web>
You can set your culture without manipulation:
using System.Globalization;
using System.Threading;
//...
protected void Application_BeginRequest(Object sender, EventArgs e)
{
Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-NZ");
}
It is an old post, but I thought it might be useful to mention it here, my problem was something like what the OP has asked, but the solution was that the culture was changed in the IIS, not from control panel.
IIS has it is own culture selection, which by default will follow the local computer culture. But for some reason, it was changed to a different culture, and I started getting those weird date formats.
You can look for more answers here.
For format strings, the format character / does not actually resolve to the literal "/" as you would expect. Instead, it resolves to the current date time separator as configured in your regional settings. Try changing the DateTimeFormatInfo.DateSeparator property.
For more information, see: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Resources