Failed to convert parameter value from a TimeSpan to a DateTime - asp.net

I am trying to store a time from my textbox field value but I got this exception error, what am I doing wrong? Thanks!:
Failed to convert parameter value from a TimeSpan to a DateTime.
Passing textbox value:
.CamActiveDateFrom = CDate(uitxtCamDateStart.Text.Trim)
My variable and property:
Private _camActiveTimeFrom As Nullable(Of TimeSpan)
Public Property CamActiveTimeFrom() As Nullable(Of TimeSpan)
Get
Return Me._camActiveTimeFrom
End Get
Set(ByVal value As Nullable(Of TimeSpan))
Me._camActiveTimeFrom = value
End Set
End Property
Parameter:
AddInParameter(dbCommand,
"#ActiveTimeFrom", DbType.Time, 6, DBNull.Value)
If (.CamActiveTimeFrom).HasValue Then
dbCommand.Parameters("#ActiveTimeFrom").Value = .CamActiveTimeFrom
End If

DbType.Time is documented as:
A type representing a SQL Server DateTime value. If you want to use a SQL Server time value, use SqlDbType.Time.
So either use SqlDbType.Time instead, or set the value to a DateTime value instead of a TimeSpan value.
Admittedly this mapping table show the DbType.Time mapping to TimeSpan, so there's some inconsistency here - but if you can use a more specific type, that can only be good.
Of course it's easy to construct a DateTime from a TimeSpan if you want to - you should probably decide on a specific date to always use (e.g. 1st January 2000) so that you can then compare values within the database and effectively get a comparison of just the time bits.

I hav the same problem. And I soloved it just used "ToString()".
my code as following:
the date type of "info.START_TIME" is TimeSpan.
db.AddInParameter(dbCommand, "#START_TIME", DbType.Time, info.START_TIME.ToString());

In order to use AddInParameter with a column of data type time, you need to use the SqlDbType instead of DbType (as described in Jon Skeet's answer)
db.AddInParameter(dbCommand, "#ActiveTimeFrom", SqlDbType.Time, 6, DBNull.Value)
instead of
db.AddInParameter(dbCommand, "#ActiveTimeFrom", DbType.Time, 6, DBNull.Value)
BUT.
In order you use SqlDbType.Time instead of DbType.Time, you must declare your Database object as an SqlDatabase, that is
SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
instead of
Database db = DatabaseFactory.CreateDatabase();
as otherwise it won't take the parameter.

Related

How to have a value of NULL for DateTime?

In my SQL database, I've declared DpsDate and AdmDate as DATE, also I've set them to allow nulls. When I run my application and leave these columns blank, I get this error:
Failed to convert parameter value from a String to a DateTime.
This is where I'm a bit confused because I've set them to allow nulls so shouldn't the database accept no value? The application works if I set both dates to "01/01/1900". I've tried setting them to "00/00/0000" but I get the same error.
Here's what I have:
If tbNotifyDate.Text = "" Then
cmd.Parameters.Add("#DpsDate", SqlDbType.Date, 50).Value = "01/01/1900"
Else
cmd.Parameters.Add("#DpsDate", SqlDbType.Date, 50).Value = tbNotifyDate.Text
End If
If tbAdmDate.Text = "" Then
cmd.Parameters.Add("#AdmDate", SqlDbType.Date, 50).Value = "01/01/1900"
Else
cmd.Parameters.Add("#AdmDate", SqlDbType.Date, 50).Value = tbAdmDate.Text
End If
You need to use DBNull.Value to represent NULL in ADO.NET. Things like table adapters and Entity Framework, which are built on top of ADO.NET, can support nullable value types and thus use Nothing to represent NULL but ADO.NET itself predates nullable value types, so Microsoft had to invent a type specifically for the purpose of representing NULL.
I would suggest using the If operator to make the code more concise:
Dim value As Date
cmd.Parameters.Add("#AdmDate", SqlDbType.Date).Value = If(Date.TryParse(tbAdmDate.Text, value),
value,
CObj(DBNull.Value))
The CObj is required because the two possible results of If must be the same type and Date and DBNull are not the same type. By casting one possible result as type Object, they are both interpreted as type Object and the compiler is happy.
Note that, as I have written that example, this will save NULL if the TextBox contains anything that isn't a valid representation of a Date. You can use whatever validation is appropriate in your specific case or, if you've already validated, just check for an empty TextBox and use CDate.

Option Strict disallows late binding using IEnumerable

Dim distinctJoints As IEnumerable
distinctJoints = From row In spotsTable.AsEnumerable()
Group row By Key = row("FUNCJOINTCODE") Into Group
Select Key, Group
_evaluatedJointsCount = (From row In spotsTable.AsEnumerable()
Group row By Key = row("FUNCJOINTCODE") Into Group
Select Key, Group).Count()
'Process each joint
For Each currentJoint In distinctJoints
Dim currentJointKey As String = currentJoint.Key
For the above code currentJoint.Key is showing error of late binding after option strict is on.
Could you please help me out of this.
First, let me congratulate your for moving your code towards Option Strict On! It might be some work in the beginning, but it pays off in the long run since a lot of errors will be found at compile-time rather than at run-time.
That said, let's look at your problem. Here:
Dim distinctJoints As IEnumerable
you declare distinctJoints as a non-generic IEnumerable. A non-generic IEnumerable returns items of type Object when iterated over. The type Object does not contain a Key method. This is why you get a compile-time error.
Since your LINQ query returns a generic IEnumerable of an anonymous type, the solution is to use type inference instead. Activate Option Infer On (if you have not already done so) in your project properties and let the compiler infer the correct data type:
' Dim distinctJoints As IEnumerable <-- remove this
Dim distinctJoints = From row In spotsTable.AsEnumerable()
Group row By Key = row("FUNCJOINTCODE") Into Group
Select Key, Group

UnsupportedOperationException for updateItem Date attribute in Dynamodb

I am trying to update one date attribute of an item in dynamodb by following piece of code:
AttributeUpdate attributeUpdates = new AttributeUpdate("workDate");
Date workDate = finalMap.get(tID);
attributeUpdates.put(workDate);
PrimaryKey primaryKey = new PrimaryKey("tID", tID);
UpdateItemOutcome outcome = table.updateItem(primaryKey, attributeUpdates);
Last line, where I am calling table.updateItem, is giving UnSupportedOperationException as follows.
Exception in thread "main" java.lang.UnsupportedOperationException: value type: class java.util.Date
Does anyone have any clue regarding how to do that. Thanks.
DynamoDB does not accept dates as a data type. You will need to convert that date into a string, then do the update.
To facilitate easy date-handling, try saving the long integer millisecond time represented by the Date object:
Date workDate = finalMap.get(tID);
attributeUpdates.put(workDate.getTime());
This can be easily and unambiguously translated back to a Date object when you load the record, by using
new Date(long Date)

List (of T) and Eval

I am using a List(of T) in my VB.Net/ASP.Net project. While displaying the list on ASP.net, I am using #Eval, but my date (After formattin) is always displaying the MinVal insteaad of Null Spacs. How to check for date.min on #Eval to get the date as " " when its equal to Date.Min Val
DateTime object can not be Null by default until you define it Nullable. If you want DateTime object to be able to hold null as value then you need to define the object data type as Nullable and explicitly assign Null. By default, any DateTime object is assigned the Min value.
If you want to check if date has Min value, either you can user DateTime.MinValue property or create a new DateTime object (It will be assigned Min value by default) then compare with that object.
[Example]
Public Property MyDate As DateTime?
' get value
<asp:someElement attr='<%# If(Eval("MyDate") Is Nothing, " ", CType(Eval("MyDate"), DateTime?).Value.ToShortDateString()) %>'></asp:someElement>

Returning in Oracle INSERT is not returning proper value

I have an ASP.NET web application (VB.NET) using an Oracle database. On an insert, I need to get the identity of the inserted row back. I am trying to use RETURNING, but I keep getting a value of 1 returned.
Dim strInsert As String = "INSERT INTO L.TRANSACTIONS (LOCATION_KEY, TRANS_CREATOR, TRANS_EMAIL, TRANS_PHONE) VALUES (:location_key, :trans_creator, :trans_email, :trans_phone) RETURNING TRANS_ID INTO :ukey"
Try
If oConn.State <> ConnectionState.Open Then
oConn.Open()
End If
Dim oCmnd As New OracleCommand(strInsert, oConn)
oCmnd.Parameters.Add("location_key", Session.Item("location").ToString.Trim())
oCmnd.Parameters.Add("trans_creator", Session.Item("userID").ToString.Trim())
oCmnd.Parameters.Add("trans_email", Session.Item("mail").ToString.Trim())
oCmnd.Parameters.Add("trans_phone", Session.Item("phone").ToString.Trim())
oCmnd.Parameters.Add("ukey", Oracle.DataAccess.Client.OracleDbType.Varchar2, System.Data.ParameterDirection.ReturnValue)
Dim strUkey As String = oCmnd.ExecuteNonQuery()
When I run the application, the record gets inserted and the TRANS_ID is incrementing but the returned value is always "1".
You're assigning the result of ExecuteNonQuery to the variable, rather than getting the value assigned to the parameter you've created. I believe you want to change the last line to something like this (untested):
oCmnd.ExecuteNonQuery
Dim strUkey As String = oCmnd.Parameters.GetParameter("ukey").Value
That's because the ExecuteNonQuery will return the number of rows affected:
For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command. For CREATE TABLE and DROP
TABLE statements, the return value is 0. For all other types of
statements, the return value is -1.
You can see that exist another question that covers the practices for doing it:
Best practices: .NET: How to return PK against an oracle database?

Resources