Date conversion on Live Server issue - asp.net

I have a web application that when working in development is fine, but going to Live it does not work.
What the situation is to do with dates. A user enters in a date in the UK format through a text, and I use DateTime.ParseExact(txtDate.Text, "dd-MM-yyyy", Nothing) to tell the date datatype that the date must remain in UK style. As I say, everything is fine in development, but when it goes to Live, it says the that the string is not a valid datetime format.
I have tried Convert.ToDateTime, and all sorts of things, but it just won't work!
Anyone have any suggestions?

I suspect that the culture setting on the live server is different to that of the dev machine.
From the docs:
If provider is a null reference (Nothing in Visual Basic), the current culture is used.
So you need to specify the InvariantCulture try this:
DateTime.ParseExact(datetimeString, "dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture)

Related

Why does Win32_Product.InstallDate2 always return null when using WMI?

UPDATE: If you want to help test this quickly in your locale. Launch PowerShell (hold down the Windows key, tap R, release the Windows key, type in "powershell" and press OK) and run this
command - (is the InstallDate2 column empty? Please let us know what you see.):
Get-WmiObject Win32_Product | Format-Table -Property InstallDate, InstallDate2, Name
I should start by saying that this issue is not critical for me (yet), but I am baffled. I am accessing the WMI object Win32_Product, and there are two properties related to dates: InstallDate and InstallDate2 respectively.
InstallDate seems to be a string representation of a DateTime value without the time part. Sort of a cut-off UTC format. Example: 20170819. The field is a string value, and not a DateTime format.
InstallDate2 is supposed to be in real DateTime format, but it is consistently null for all Win32_Product items on all my systems (Windows 7, Windows 10, various editions).
Using WMIExplorer.exe I see this description of InstallDate: "...the InstallDate property has been deprecated in favor of the InstallDate2 property which is of type DateTime rather than String. New implementations should use the InstallDate2 property."
As stated I get null back on all my machines, so I was assuming that InstallDate2 was simply not implemented properly, but then I found this article: Working with Software Installations. This article clearly shows InstallDate2 returning a WMI DateTime (with missing time part?): InstallDate2 = 20060506000000.000000-000.
I am simply wondering what can be causing this InstallDate2 null value on all my systems when I see it working on other systems? Some possibilities that has crossed my mind (one more far fetched than the next perhaps):
OS issue? I don't have access to older OSs, but I see null on several different editions (home, ulitmate, etc...) of Windows 7 and Windows 10 systems. Perhaps it worked on XP and older? I find this unlikely.
Locale issue? I am in a Norwegian locale. Could this affect things? I tried briefly to change the locale on a Windows 10 system, but it had some language pack issues and the result was the same.
Domain (network) issue? Is it conceivable that machines in workgroups work differently than machines that are part of a domain?
Patch level? Could a recent Windows Update have changed something in WMI?
What else could conceivably affect this?
And a second part of the question (in addition to what the cause of the null value for InstallDate2 is). The string I get back for InstallDate (the string format date): 20170819. I am assuming this is just a chopped of version of Universal Time Coordinate (UTC) format. And that it is a locale-independent format? It seems like it when I read about CIM_DATETIME.
I tried filling the rest of the chopped off date string with zeros and passing it to a SWbemDateTime scripting object, and it seemed to work, but that really smells as a "solution". Doesn't seem reliable at all:
Set dateTime = CreateObject("WbemScripting.SWbemDateTime")
dateTime.Value = "20170601000000.000000+000"
MsgBox dateTime.Year
MsgBox dateTime.UTC
It shows 2017 for year, and 0 for UTC. With such a "solution" I obviously really want to get the InstallDate2 DateTime field working correctly so I get a proper Datetime back.
So in all its verbosity, basically a two-part question:
What could be causing Win32_Product.InstallDate2 to consistently report null seemingly only on my systems?
The short string returned by InstallDate - is this in a locale-independent format?
Since I am in a Norwegian locale and see what looks like an English style format, it would seem that it is? Since the field is just a string, the content could basically be "anything" though.
It would be great if someone in another locale could verify that the format returns as: Win32_Product.InstallDate = yyyymmdd.
Reading about CIM_DATETIME seems to indicate the string is locale-independent (even if chopped off).
If you want to test, the quickest way is probably using wbemtest.exe (or better yet PowerShell if you have it available on your box - as mentioned by JosefZ in the comment below):
Launch wbemtest.exe (Hold down the Windows key, tap R, release the Windows key, type in "wbemtest.exe" and press OK).
Click "connect" and then OK (namespace defaults to root\cimv2), and click "connect" again.
Click "Query" and type in this WQL command: SELECT Name,InstallDate2 FROM Win32_Product and click "Use" (or equivalent).
Double click any entry returned, and check InstallDate2 in the middle list box (scroll down).
In my opinion you won't get a full date-time back. The only information available is effectively from MsiGetProductInfo (...INSTALLPROPERTY_INSTALLDATE....). This format is YYYYMMDD. You're only ever going to get the data because that seems to all there is. Note that the documentation for INSTALLPROPERTY_INSTALLDATE says that it is the installation date only if there has been no other servicing since the product was installed, so it appears that you can't even rely on it being the date the product was installed.
See Detecting the time when the program was installed
I suspect the best way to get the time the product was installed is to get the local package path with MsiGetProductInfo (Ex) ...INSTALLPROPERTY_LOCALPACKAGE... and get the cached MSI's CreationDate.

Date/DateTime object type in AmbientDataFramework

I'm having a bit of an issue with the Date (java) / DateTime (.net) type when using the Ambient Data Framework in SDL Tridion 2009.
I'm setting a claim value in java like this:
Date myDate = rs.getDate("DATE_FIELD_IN_DB");
store.put(CLAIM_URI_DATE, myDate);
This is great and life is fantastic :)
In my web application (which is .net) I need to get this value from the claim store, when I try to do so, it fails:
My code is:
if (_store.Contains(new Uri("taf:claim:company:date"))) {
DateTime claimdata = _store.Get<DateTime>("taf:claim:company:date");
Response.Write(claimdata.ToString());
}
And the error message is:
[RuntimeException] Codemesh.JuggerNET.NTypeValue.Throw(Int64 inst)
+373 Codemesh.JuggerNET.JavaClass.ThrowTypedException(Int64 inst) +1365 Codemesh.JuggerNET.JavaMethod.CallInt(JavaProxy jpo) +233 Tridion.ContentDelivery.AmbientData.JuggerNetTypeHelper.FromProxyObject(Object
proxyObject) +738
Tridion.ContentDelivery.AmbientData.ClaimStore.Get(Uri claimUri) +109
I've also tried obtaining as an object, which i then cast to DateTime. I'm obviously making a really basic error here, any help would be greatly appreciated.
I have also read the SDL documentation here : http://sdllivecontent.sdl.com/LiveContent/content/en-US/SDL_Tridion_2011_SPONE/concept_26FDE76C277D43F893175E512EFDF09A which shows the java Data object is converted to the .net DateTime.
Thanks
John
UPDATE
As per the suggestions of Peter, i've check and ensured the correct jar files are in place.
It might be worth mentioning that the date is stored in a SQL database as a 'Date' type, a typical value doesn't include a timestamp, for example '2011-09-03'. Still this all functions great in Java and I can work with the value as a date. Still when getting the value in .Net the typed exception is thrown.
It should convert it automatically. Are you sure you are not using a different Date object than java.util.Date, though? There's quite a few of them out there...
If you really cannot get it to work, you can work around it by storing the date as a string (in ISO 8601 format) and then using DateTime.Parse on the .NET side.
But like I said: it normally works fine so there's probably something else going wrong.
Is your ADF working fine for other things in .NET? Maybe it's missing a setup step for the .NET side of things...
A bit of a long shot, but can you verify that the right JDBC driver is installed as mentioned in this question/answer?
Exception loading CustomMeta from Tridion Broker Service (2009 SP1)
The Date value, does it contain the time? Can you ensure that it does when you get the value from the store?

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.

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.

Saving DateTime object on UK Dev Server vs US Live Server

I have a site that saves a date in my model to the database.
After launching my site I realised that the server has US regional settings so I had to make sure that all date's on the public site were formatted in the UK format.
However now when I go to my 'Create' page and choose a date and click save I get the error The value '22/11/2009' is not valid for the Date field. which must be coming from the default DataAnnotations on my model.
Is there something I can do to get it to accept UK formatted dates?
I managed to get it working by putting this into the web.config
<globalization culture="en-GB"/>
Have you tried this? If this site is only used in the UK, you can probably put this in the Global.asax Application_Init. If it is based on the user, you can put it in Application_BeginRequest. This will provide the default formatting and parsing for all dates and numbers in the application.
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-gb");
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-gb");
Do what SO does: persist all dates in UTC and render them as UCT with an appended "Z" for GMT/UTC/Zulu. It might not be ideal but sometimes the gain from simplicity outweighs the costs of the alternative. Think about that.

Resources