Datetime.Now method in ASP.NET - asp.net

I am using ASP.NET to provide some variables for the data that has to be added to a SQL database.
Code I am using:
I am using DateTime.Now to select the current time.
How I use it:
I have two pages, one is a page to insert the posts of the users. Other page is used for ajax purpose, to add some text comments to the posts.
In both page I use the same code.
But the code is executing different values. You can have a look here:
In the post the time is saved as "9/1/2013" which means 1st September, 2013! In comment it is saved as Sep 1 2013, which means the same.
My question: how does the code know that the request is an ajax one or the post one. The post page code is wrapped in if(IsPost) { however the comment is an ajax call.
What is the reason behind this?

I found what the issue was.
I had set the column DataType to nvarchar(50) in the database table. After editing it to DataType DateTime I was able to get the same result. So the issue was not the Culture or DateTime. It was the DataType of the column in SQL Server Database.

Assuming that your AJAX call is not changing the format string of your DateTimes, I would assume the threads which process those 2 different requests are operating under different cultures, which would explain why they're being displayed differently (not sure why though, check your settings perhaps). Try the following and you'll see how culture can effect DateTime output:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine (DateTime.Now.ToString());
Thread.CurrentThread.CurrentCulture = new CultureInfo("gu-IN");
Console.WriteLine (DateTime.Now.ToString());
Here's some additional information on CultureInfo.

Code knows from Current thread's Culture information. You should use DateTime.Now.ToString("yyyy-MMM-dd") or any other formate according to your needs to be sure of output.

Related

Send query string parameter from a non-web application

Ok, I've been bugging with this for too long.
I need to call my website from a rough VB.net app. Then only thing I need is to attach a query string parameter to the calling url, so I can distinguish the pages to be shown to different VB app users.
So I want to click a button and launch that website, giving this parameter.
First I was bugging with adding the system.web libraries. Now I can't use Request/Response.QueryString as well.
I tried getting some example help from this post. but as I said before - I cannot make use of Request.QueryString as I cannot import it.
I am stuck here:
Process.Start("http://localhost:56093/WebSite1?id=")
I need to attach a query string parameter to the url and then open the website with that url.
Can someone just give me a sample code for my problem.
Query parameters are parsed by the web server/http handler off the URL you use to call the page. They consist of key and value pairs that come at the end of the URL. Your code is nearly there. Say you needed to pass through the parameters:
ID = 1234
Page = 2
Display = Portrait
Then you'd turn them into a URL like this:
http://localhost:56093/WebSite1?ID=1234&Page=2&Display=Portrait
Therefore in your code you'd have:
Process.Start("http://localhost:56093/WebSite1?ID=1234&Page=2&Display=Portrait");

Which culture is used by ObjectDataSource to convert string to DateTime

I've just described my problem here: ObjectDataSource fails to parse string to DateTime . After a few google queries I came across this link: ObjectDataSource – Cannot convert value of parameter value from System.String to System.DateTime , and short explanation:
One bug I’ve come across a few times and again just recently is when using an ObjectDataSource with a GridView to update dates. When doing the update the ObjectDataSource always uses the en-US culture and not the culture defined for the application.
The bug has been acknowledged by Microsoft but never fixed.
The workaround that involves manual parsing is ... unacceptable :) Do you know any other, more programmer friendly solution to that issue?
Although this issue was apparently never fixed, there are several workarounds that you may use provided in this link. Not sure why parsing would be unacceptable. It can be done in 1 line of code:
DateTime myDate = DateTime.Parse(myTextBox.Text, CultureInfo.CurrentCulture.DateTimeFormat);
Observe that the culture is not hardcoded (which is the only reason I could think of that would make this unacceptable).

How to pass value from web form to another web form?

Can anybody tell me how to pass a value from one web form to another web form without using a query string and session?
You can pass the Values over different pages via QueryString like:
Response.Redirect("yourNextpage.aspx?identifier=DesiredValue");
On your next page you can retrieve the value like this:
Request.QueryString["identifier"];
Other Preferred way would be Server.Transer() and Postbackurl.
Refer this link for various possible ways.
there are several ways you can pass parameters between pages.
Using a Query String
Getting Post Information from the Source Page
Using Session State
Getting Public Property Values from the Source Page
Getting Control Information from the Source Page in the Same Application
for more detail visit followng link.
http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
You could use a Querystring in this case:
Page.Response.Redirect("show.aspx?id=1");
And then read it on the other end:
int id = Page.Request.QueryString["id"];
Using PostBackURL, ex:
PostBackUrl="~/result.aspx"
and on result.cs (Page Load)
lblEmployeeNumber.Text = HttpContext.Current.Request.Form["txtEmployeeNumber"];
With Session:
For example you login the system and your id is 123123123.
string userid = 123123123;
Session["userid"] = userid;
When you go another page/pages your session is alive when your session timeout.
<system.web>
<sessionState timeout="1250"/>
</system.web>
It seems what you're looking for is something like the flash-, view- or conversation scope in Java EE and Ruby on Rails.
For ASP.NET you could perhaps take a look at this one: Is there an equivalent of JSF #ViewScope in ASP MVC?
depends on type and how much information you wish to transfer. for instance, if you want to transfer some variable (strings or integer values) you consider to use querystring (you can found here major information). for instance, if you want to transfer typed objects (class instance) you consider to use session (you can found here major information).

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 to render local time given UTC datetime values in ASP.Net without using Javascript?

Is it possible to display local times to users without using Javascript when you store the values as UTC?
You would need serverside to be aware of the clients timezone. There isn't enough information in the typical request to make that determination, the closest you can get is the Accept_Language header which might give you a clue but is hardly useful enough (esp. if the client is in a country that has multiple timezones).
Hence you would need to user to tell you what their timezone is and then use a logon or cookie to store that info.
You could do the conversion on the serverside in vb.net, c# or whatever .net language your using. You are going to have to convert to the local time somewhere.
Your asking a very broad question with no detail so I can't recommend how to do this on the server.
Edit
Based on the comments I see the problem your having is that you want to figure out what the users timezone is without javascript. I always have the user tell me their timezone when they register.
One approach which won't be perfect would be would to be use a geo-ip lookup service that will tell you most likely where your user and give your better granularity then using the language settings.
Think this is the closest you can do:
using System.Globalization;
// get the first language from request (en, fr, ru)
var primaryLanguage = Request.UserLanguages.First().Split(";").First();
// find a culture by this language
var culture = new CultureInfo(primaryLanguage);
// if the culture is neutral, try to find the specific one
if (culture.IsNeutralCulture)
culture = CultureInfo.GetCultures(CultureTypes.SpecificCultures).FirstOrDefault(o => o.TwoLetterISOLanguageName == primaryLanguage);
// get the string from a datetime
var datetimeText = culture ? DateTime.Now.ToString(culture) : DateTime.Now.ToString();

Resources