ASP.NET/VB date works on localhost but not remoteserver - asp.net

I'm having alot of trouble trying to get the date from a DateTime picker to save to my database. It works fine when run from Localhost, but when running it on the public server it doesn't.
Originally i used the cDate function, plus also tried Convert.ToDateTime. But on the server it now gives me an error "String was not recognized as a valid DateTime."
I researched and found that its best to used the DateTime.TryParse function. After finding an example i changed it for my project and now im getting the error "Must declare the scalar variable "#articledate"."
When i debug the project, the value added into the "result1" DateTime is correct. But it still throws the error at ExecuteNonQuery?
If it makes a difference, the main server is hosted with GoDaddy, Localhost is my PC.
Any help or advice would be greatly appreciated.
cnSQL1 = New SqlConnection(MSSQL.cRemoteConnectionString)
cnSQL1.Open()
sSQL = "SELECT NewsID FROM News WHERE Season = #season AND Heading = #heading AND ArticleDate = #articledate AND Author = #author AND Club = #club AND State = #state AND AddedDate = #addeddate AND AddedBy = #addedby AND Release = #release"
Dim com1 As New SqlCommand(sSQL)
com1.Connection = cnSQL1
com1.Parameters.AddWithValue("#season", General.sSeason)
com1.Parameters.AddWithValue("#heading", General.UppercaseFirstLetter(txtHeading.Text))
Dim result1 As DateTime
com.Parameters.AddWithValue("#articledate", DateTime.TryParseExact(txtArticleDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result1))
'com1.Parameters.AddWithValue("#articledate", Convert.ToDateTime(txtArticleDate.Text))
com1.Parameters.AddWithValue("#author", txtAuthor.Text)
com1.Parameters.AddWithValue("#club", ddlClub.SelectedItem.Value)
com1.Parameters.AddWithValue("#state", dsState.Tables(0).Rows(0).Item(0))
com1.Parameters.AddWithValue("#addeddate", Date.Today)
com1.Parameters.AddWithValue("#addedby", Session("UserID"))
com1.Parameters.AddWithValue("#updatedate", Date.Today)
com1.Parameters.AddWithValue("#updateby", Session("UserID"))
com1.Parameters.AddWithValue("#release", s)
com1.ExecuteNonQuery()

The error "Must declare the scalar variable "#articledate" is caused by a typo. When you add the parameter you should use the SqlCommand variable named com1 not the variable com.
But after this you have a more critical error. All the TryParse methods return booleans. The converted date is written in the last parameter passed to TryParse.
In this way you are passing a boolean to AddWithValue and this method takes whatever you put in the value parameter. It has no way to know that you want a date, so it happily complies with your request.
You should do (Notice that the SqlCommand to use is com1 not com)
Dim result1 As DateTime
if DateTime.TryParseExact(txtArticleDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result1) Then
com1.Parameters.AddWithValue("#articledate", resul1)
Else
.....
In general it is better to avoid AddWithValue exactly because it takes whatever you pass to it. The preferred way is with
if DateTime.TryParseExact(txtArticleDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result1) Then
com1.Parameters.Add("#articledate", SqlDbType.Datetime).Value = result1
com1.Parameters.AddWithValue("#season", General.sSeason)
com1.Parameters.AddWithValue("#heading", General.UppercaseFirstLetter(txtHeading.Text))
com1.Parameters.AddWithValue("#author", txtAuthor.Text)
com1.Parameters.AddWithValue("#club", ddlClub.SelectedItem.Value)
com1.Parameters.AddWithValue("#state", dsState.Tables(0).Rows(0).Item(0))
com1.Parameters.AddWithValue("#addeddate", Date.Today)
com1.Parameters.AddWithValue("#addedby", Session("UserID"))
' This is not used by the query, commented out
' com1.Parameters.AddWithValue("#updatedate", Date.Today)
' This is not used by the query, commented out
' com1.Parameters.AddWithValue("#updateby", Session("UserID"))
com1.Parameters.AddWithValue("#release", s)
com1.ExecuteNonQuery()
Else
MessageBox.Show("Date is not valid")
End If
I have also removed two parameters that are not used in the query above (though they should not cause the error message above)

Related

Getting error: Conversion from string "" to type 'Date' is not valid

If anyone can rewrite this for me I'd really appreciate it. I'm trying to change stored date if null. I've tried Me.vipEndDate ="0000-00-00" and much more.
If DR("vipEndDate") Is Nothing Then
Me.vipEndDate = "0"
Else
Me.vipEndDate = DR("vipEndDate").ToString
End If
Well you could add some error protection. The TryParse attempts to convert a string to a date, if it does not convert it returns false so you code will not execute with an error.
Dim dt As Date
If Date.TryParse(DR("vipEndDate").ToString, dt) Then
'this part only executes if string convert
Me.vipEndDate = dt
End If

Date field changing from UK to US culture upon SaveChanges (EF6.1)

I am using a custom overloaded SaveChanges to implement some auditing functionality. The functionality works perfectly with the exception of some unexpected behaviour in relation to dates. In this example I'm changing a date field value from 1st May 2014 to 2nd May 2014:
A change is made to the database here:
Public Function UpdateTask(request As DataSourceRequest, ThisTask As JobTasksVM) As JsonResult
Dim cu As ApplicationUser = GetCurrentUser()
Dim CurrentTask = db.events.Find(ThisTask.id)
CurrentTask.start_date = ThisTask.start '<--- 2/5/2014 (ie 2nd May 2014), was previously 1/5/2014
CurrentTask.date = ThisTask.end
CurrentTask.task_name = ThisTask.Title
db.SaveChanges(cu.Employee_id)
End Function
This is intercepted by my custom SaveChanges:
Public Overloads Function SaveChanges(userID As Integer) As Integer
For Each entry As dbentityentry In Me.ChangeTracker.Entries().Where(Function(e) e.State <> EntityState.Unchanged)
Dim startOriginal As DateTime = entry.OriginalValues.Item("start_date")
Dim StartCurrent As DateTime = entry.CurrentValues.Item("start_date")
etc....
The bizarre thing is that whilst CurrentTask.start_date that is committed clearly shows the correct (UK) date of 2/5/2014 (2nd May 2014) the values within the overloaded SaveChanges are:
startOriginal: 5/1/2014 (ie 5th Jan 2014) <-- seems to have changed to US culture
startCurrent: 2/5/2014 (ie 2nd May 2014) <---as expected
I need to use the Original values in my audit functionality so this is causing a problem. I have also tried:
entry.CurrentValues.SetValues(entry.GetDatabaseValues)
But this also loads in the erroneous (ie US format 5/1/2014) into the start_date field.
I've checked all the culture settings on the system and they are all correctly English-UK. This behaviour seems fundamentally inconsistent - am I missing something?!
Thanks
DateTime types do not have a format, they are simply a value (number of ticks since 1/1/0001).
You did not say where you are seeing the "wrong" format, whether ToString() output or in intellisense. If you use ToString to the Output window, you should see the UK format since ToString will use/respect the local culture setting of the computer.
Intellisense is culture agnostic and tries to use an unambiguous format: MM/dd/yyyy. This is the same "format" or order you have to use when creating a DateTime var from a literal:
Dim dt As DateTime = #1/5/2014# ' e.g. MM/dd/yyyy
' same as:
Dim dt As New DateTime(1, 5, 2014) ' mm, dd, yyyy
This is InvariantCulture (not US). When you hold the mouse over the var, the VB IDE will use the same order. It tries to make clear it is using the required literal/InvariantCulture format by displaying it with the hashes: #1/5/2014#.
Dim dt As DateTime = #2/11/2011#
Console.WriteLine(dt.ToString)
In the US, 2/11/2011 will display based on the culture
In the UK, it will be 11/2/2011
Intellisense will be #2/11/2011#

DateTime.TryParse in a conditional is throwing an exception

On both examples I'm giving it a String like the following: 26-03-17
Dim mvarValor As String
Dim dateVarValor As DateTime
This code snippet is throwing an exception on the TryParse:
If Not mvarValor = Nothing AndAlso DateTime.TryParse(mvarValor, dateVarValor) Then
Return Format(dateVarValor, mvarFormat)
Else
Return strNull
End If
The next code snippet is not throwing an exception, but a False like it should:
DateTime.TryParse(mvarValor, dateVarValor)
If dateVarValor = Nothing Then
Return strNull
Else
Return Format(dateVarValor, mvarFormat)
End If
Why is the first code snippet giving me an exception?
Thanks in advance!
DateTime.TryParse throws three types of exceptions
http://msdn.microsoft.com/en-us/library/9h21f14e(v=vs.100).aspx
you must be getting one of those. Here is the proper usage of DateTime.TryParse
var culture = CultureInfo.CreateSpecificCulture("en-US");
string parsedDateTime = null;
if (DateTime.TryParse(parseMe, culture, DateTimeStyles.None, out dateResult))
{
parsedDateTime = dateResult;
}
this snippet will parse the datetime without throwing an exception.
I hope this helps :)
You need to pass in a Y2K compliant date. The parser can't tell the year from 2 digits. If you pass 2003-12-25 it will validate that the date does in fact exist, but 03-12-25 is ambiguous.

SQLite JDBC rs.getDate() getTimestamp() etc. all return wrong values

When using the JDBC for SQLite for some reason Date and Timestamp values are stored correctly in the DB, are displayed correctly when using the command line sqlite3 tool, but when using the ResultSet functions to retrieve these values it doesn't work. Below is a small test class that demonstrates what I mean.
import java.sql.*;
public class Test {
public static void main(String[] args) throws Exception {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
Statement stat = conn.createStatement();
stat.executeUpdate("drop table if exists people;");
stat.executeUpdate("create table people (name, occupation, date date);");
stat.executeUpdate("insert into people values ('Turing', 'Computers', date('now'));");
ResultSet rs = stat.executeQuery("select * from people;");
while (rs.next()) {
System.out.println("name = " + rs.getString("name"));
System.out.println("job = " + rs.getString("occupation"));
System.out.println("date = " + rs.getDate("date"));
System.out.println("dateAsString = " + rs.getString("date"));
}
rs.close();
conn.close();
}
}
The output I get is:
name = Turing
job = Computers
date = 1970-01-01
dateAsString = 2011-03-24
Like Scott says: SQLite does not have a Date type.
You could have SQLite do the conversion for you with the strftime function: strftime('%s', date). Then you can use rs.getDate on the Java side.
You can also retrieve the SQLite date as string, and parse that into a date:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
Date today = df.parse(rs.getString("date"));
System.out.println("Today = " + df.format(today));
} catch (ParseException e) {
e.printStackTrace();
}
SQLite3 does not have a Date type so you will have to get the String of the dates when writing your code.
http://www.sqlite.org/datatype3.html
SQLite does not use 'types' and instead uses what's known as 'type affinity';
From the documentation itself:
The important idea here is that the type is recommended, not required
You can store the dates as strings and parse them however you like with formatting classes like SimpleDateFormat or DateTimeFormatter, or you can use something crude like Date.from(Instant.parse(rs.getString("date"))).
Java 8
Amongst the other answers here, I'd say that LocalDate#parse() and LocalDateTime#parse() is also a good option for Java 8 moving forwards.
They accept a date in String format
LocalDate.parse("2016-05-24")
Or a String with a DateTimeFormatter as the second argument
LocalDate.parse("2016-05-24", DateTimeFormatter.ofPattern(yyyy-MM-dd))
Conversion
And if you're looking to use LocalDate or LocalDateTime but want to support Date, maybe in an adapter pattern;
LocalDateTime to Date:
This example uses the system default timezone as the ZoneId argument of atZone, however you can use a static/hard-coded timezone if you want to. Essentially you are creating an Instant from AtZone which can be used to build a Date from the static method Date#from(Instant)
Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()));
LocalDate To Date:
This example is pretty much the same, only here all that's required to get a ZoneId in order to create an Instant is the LocalDate instance itself.
Date.from(localDate.atZone(ZoneId.systemDefault()).toInstant()));
I've not gone into technical detail here, it may not even be necessary, but do correct me if I'm wrong.

ASP Classic - Type mismatch: 'CInt' - Easy question

Having an issue with type conversion in ASP classic.
heres my code:
Set trainingCost = Server.CreateObject("ADODB.Recordset")
strSQL3 = "SELECT cost1 FROM tblMain WHERE (Booked = 'Booked') AND (Paid IS NULL) AND (PaidDate BETWEEN '01/04/" & startyear & "' AND '31/03/" & endyear & "')"
trainingCost.Open strSQL3, Connection
trainingCost.movefirst
totalTrainCost = 0
do while not trainingCost.eof
trainCost = trainingCost("cost1")
If NOT isNull(trainCost) then
trainCostStr = CStr(trainCost)
trainCostStr = Replace(trainCostStr, "£", "")
trainCostStr = Replace(trainCostStr, ",", "")
totalTrainCost = totalTrainCost + CInt(trainCostStr)
end if
trainingCost.movenext
loop
trainingCost.close
when I run this I get the following error:
Microsoft VBScript runtime (0x800A000D)
Type mismatch: 'CInt'
/systems/RFT/v1.2/Extract.asp, line 43
which is "totalTrainCost = totalTrainCost + CInt(trainCostStr)"
Im guessing that the problem is to do with the String value being uncastable to Int in which case is there any way to catch this error? I havent worked with asp classic much so any help would be usefull
cheers
-EDIT-
the type of column cost1 is String as it may contain a number or a sequence of chars eg £10.00 or TBC
You have a couple of choices. You can be proactive by checking ahead of time whether the value is numeric using the IsNumeric function:
If IsNumeric(trainCostStr) Then
totalTrainCost = totalTrainCost + CInt(trainCostStr)
Else
' Do something appropriate
End If
...or you can be reactive by using error catching; in Classic ASP probably easiest to define a function and use On Error Resume Next:
Function ConvertToInt(val)
On Error Resume Next
ConvertToInt = CInt(val)
If Err.Number <> 0 Then
ConvertToInt = Empty
Err.Clear
End If
End Function
Or return 0 or Null or whatever suits you, then use it in your trainCost code.
Note that CInt expects an integer and will stop at the first non-digit, so "123.45" comes back as 123. Look at the other conversions, CDouble, CCur, etc.
Rather than casting to a string, why not use CCur (Cast as Currency) so that your commas and any currency symbols (I think) are effectively ignored while doing arithmetic operations?
Potentially solving the wrong problem, depends on the type of Cost1 within the database but the code is looping through the records to generate a total.
strSQL3 = "SELECT sum(cost1) FROM tblMain WHERE (Booked = 'Booked') AND (Paid IS NULL) AND (PaidDate BETWEEN '01/04/" & startyear & "' AND '31/03/" & endyear & "')"
trainingCost.Open strSQL3, Connection
etc and just read off the value as a total.
I don't see why the RS is being looped to generate a sum when the database can do that work for you. All the conversion work it has generated just looks artifical.
Heh heh. Classic ASP. You have my pity :) Anyway,
On error resume next
And then on the next line, check that it worked.
Though maybe you want CDouble. Is that a function? I can't remember.

Resources