Error in ASP Code - asp-classic

Below ASP code have some error in 'Dim MonthNum=Month("Ctxtdatefrom") '
Can help to solve this.
If session("cmbLeaveType")=2 then
set rs2 = objconn.execute("select * form Particulars where empid='" & session("empid") & "'")
if Nationality = ABC then
Dim MonthNum=Month("Ctxtdatefrom")
Dim MonthNum2=Month("ctxtdateto")
If(MonthNum=5 and monthnum2=5)
if tdays>1 then
else
set rs = objconn.execute("insert into leavebank (empid, datesubmit, datefrom, dateto....
END IF
END IF
END IF
END IF
If Nationality is "Country A" ,Number of Leave allowed to take on 5th month is 1.
If(MonthNum=5 and monthnum2=5)
if tdays>1 then
-> Can you please correct

I'm guessing that you are seeing an error like:
Microsoft VBScript compilation error '800a0401'
Expected end of statement
/test.asp, line 11
Dim MonthNum = Month("Ctxtdatefrom")
-------------^
This error is being thrown because you cannot dim and assign in one line in VBScript.
If you rewrite that to:
Dim MonthNum
MonthNum = Month("Ctxtdatefrom")
You will be closer to your aim - though you will then almost certainly hit another error - your call to the month function does not do what you think it does.
By wrapping your variable Ctxtdatefrom in double quotes you are actually passing a literal string containing the value Ctxtdatefrom to the VBScript Month function.
What you want to do is:
Dim MonthNum
MonthNum = Month(Ctxtdatefrom)
That should work so long as that variable contains a valid VBScript date format.
You can find some reading here.
The above said - based on your code, you are almost certainly going to see more errors, I'd recommend you find someone who can mentor you in ASP classic and VBScript, read some online tutorials or take things one step at a time and post detailed and specific questions here.

Related

Retrieving a Date value from a GridView in VB

I am trying to retrieve a value from a GridView and save it as a Date variable, using the following code:
Dim invoice_date As Date = Convert.ToDateTime((TryCast(row.Cells(2).Controls(0), TextBox)).Text)
I am getting an error:
System.Web.UI.WebControls.TextBox) returned Nothing.
From what I have read, if the TryCast fails, it will return a value of nothing.
I have a similar command for an Integer, which works fine on another column.
Dim order_value As Integer = Convert.ToInt32((TryCast(row.Cells(3).Controls(0), TextBox)).Text)
Can somebody please help with the correct syntax to work with a Date value?
You are right that TryCast returns Nothing if it cannot cast to the target type. So, the problem that you have is most likely that row.Cells(2).Controls(0) is not a TextBox. To debug this, split the line:
Dim invoice_date As Date = Convert.ToDateTime((TryCast(row.Cells(2).Controls(0), TextBox)).Text)
like this:
Dim textbox As TextBox = TryCast(row.Cells(2).Controls(0), TextBox)
Dim invoice_date As Date = Convert.ToDateTime(textbox.Text)
and look at the value of textbox.
Try and use DirectCast() and see if that works.

Not a valid month asp.net / oracle

I have two values that have dates inside in the format dd/MM/yyyy and am trying to get the dates in between these two values. The values look like these(17/06/2013) in ONE and TWO variables. And then I send from my asp to an oracle procedure to execude a query and i get ORA-01843 not a valid month. Ive searched for this error but none of the solutions seemed to work for me. The thing is that this code used to work, I didnt change anything on these code and now it doesnt work for some reason.
Here is the code from my asp:
ONE = fromDate.Value
TWO = toDate.Value
Generic.searchBetweenDates(ONE, TWO, dt)
Public Function searchBetweenDates(ByVal PFROMDATE As String, ByVal PTODATE As String, ByRef PUSERINFO As DataTable)
Dim myDataTable As New DataTable
Dim myDataAdapter As New OracleDataAdapter
Dim oraCmd As New OracleCommand("cantine_test.searchbetweendates")
oraCmd.CommandType = System.Data.CommandType.StoredProcedure
oraCmd.Parameters.Add(New OracleParameter("PFROMDATE", OracleType.VarChar, 30)).Value = PFROMDATE
oraCmd.Parameters.Add(New OracleParameter("PTODATE", OracleType.VarChar, 300)).Value = PTODATE
oraCmd.Parameters.Add(New OracleParameter("PUSERINFO", OracleType.Cursor)).Direction = ParameterDirection.Output
Dim oConn As New OracleConnection(ConnectionString)
Try
oConn.Open()
oraCmd.Connection = oConn
cleanParams(oraCmd.Parameters)
myDataAdapter.SelectCommand = oraCmd
myDataAdapter.Fill(myDataTable)
If Not myDataTable Is Nothing Then
PUSERINFO = myDataTable 'return reference using byref param
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
oraCmd.Dispose()
oConn.Close()
myDataAdapter.Dispose()
End Try
Return PUSERINFO
End Function
And here is the code from my Oracle procedure:
PROCEDURE searchbetweendates
(PFROMDATE IN VARCHAR2, PTODATE IN VARCHAR2, PUSERINFO OUT SYS_REFCURSOR)
AS
BEGIN
OPEN PUSERINFO FOR
SELECT ORDERDATE,ORDERID,ORDERTIME,ORDERLIST,QUANTITY,ITEMPRICE,ORDERPRICE,LOCATION
FROM ORDERSDETAIL
WHERE ORDERDATE >= to_date(PFROMDATE, 'dd/MM/yyyy')
AND ORDERDATE <= to_date(PTODATE,'dd/MM/yyyy');
END;
Any ideas?
Oracle hurls ORA-01843 when we pass a string which doesn't match the specified date format: for instance when the string has the US format and the format mask doesn't:
SQL> select to_date('01/13/2013', 'dd/mm/yyyy') from dual
2 /
select to_date('01/13/2013', 'dd/mm/yyyy') from dual
*
ERROR at line 1:
ORA-01843: not a valid month
SQL>
So, the most likely explanation is that you are passing values which you think have a common format but in fact don't. This is fantastically common when "dates" are stored as strings. In other words, this is a debugging question.
Although, one thought occurs: is ORDERSDETAIL.ORDERDATE itself of a DATE datatype.
#6/17/2013#{Date} is the sort of string which will definitely lead to an ORA-1843 error. So you need to trace your code to discover where it comes from.
"how should i check if the value in my columns are correct"
Debugging dot Net is not my strong point. However, there are traditionally two ways. One is to step through the code in a debugging tool. If you're using Visual Studio or a similar IDE you should be able to do this. The other suggestion is to embed logging commands in your code and write trace messages e.g. to a file.
Which approach suits you best? Only you can tell.

Inserting null values into date fields?

I have a FormView where I pull data from one table (MS Access), and then insert it (plus more data) into another table. I'm having issues with the dates.
The first table has two date fields: date_submitted and date_updated. In some records, date_updated is blank. This causes me to get a data mismatch error when attempting to insert into the second table.
It might be because I'm databinding the date_updated field from the first table into a HiddenField on the FormView. It then takes the value from the HiddenField and attempts to insert it into the second table:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
myDateRequestUpdated = hfDateRequestUpdated.Value
'... It then attempts to insert myDateRequestUpdated into the database.
It works when there is a value there, but apparently you can't insert nothing into a date/time field in Access. I suppose I could make a second insert statement that does not insert into date_updated (to use when there is no value indate_updated), but is that the only way to do it? Seems like there should be an easier/less redundant way.
EDIT:
Okay. So I've tried inserting SqlDateTime.Null, Nothing, and DBNull.Value. SqlDateTime.Null results in the value 1/1/1900 being inserted into the database. "Nothing" causes it to insert 1/1/2001. And if I try to use DBNull.Value, it tells me that it cannot be converted to a string, so maybe I didn't do something quite right there. At any rate, I was hoping that if there was nothing to insert that the field in Access would remain blank, but it seems that it has to fill it with something...
EDIT:
I got DBNull.Value to work, and it does insert a completely blank value. So this is my final working code:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
Dim myDateRequestUpdated = Nothing
If hfDateRequestUpdated.Value = Nothing Then
myDateRequestUpdated = DBNull.Value
Else
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value)
End If
Thanks everyone!
Sara, have you tried casting the date/time before you update it? The data mismatch error likely comes from the fact that the hfDateRequestUpdated.Value you're trying to insert into the database doesn't match the column type.
Try stepping through your code and seeing what the type of that value is. If you find that it's a string (which it seems it might be, since it's coming from a field on a form), then you will need a check first to see if that field is the empty string (VBNullString). If so, you will want to change the value you're inserting into the database to DBNull, which you can get in VB.Net using DBNull.Value.
We can't see your code, so we don't know exactly how you get the value into the database, but it would look something like this
If theDateValueBeingInserted is Nothing Then
theDateValueBeingInserted = DBNull.Value
EndIf
Keep in mind that the above test only works if the value you get from the HiddenField is a string, which I believe it is according to the documentation. That's probably where all this trouble you're having is coming from. You're implicitly converting your date/time values to a string (which is easy), but implicitly converting them back isn't so easy, especially if the initial value was a DBNull
aside
I think what Marshall was trying to suggest was the equivalent of the above code, but in a shortcut expression called the 'ternary operator', which looks like this in VB.Net:
newValue = IF(oldValue is Nothing ? DBNull.Value : oldValue)
I wouldn't recommend it though, since it's confusing to new programmers, and the syntax changed in 2008 from IFF(condition ? trueResult : falseResult)
Your code
Dim myDateRequestUpdated As DateTime
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value) : DBNull.Value()
has a couple of problems:
When you declare myDateRequestUpdated to be DateTime, you can't put a DbNull.Value in it.
I'm not sure you need the () for DbNull.Value: it's a property, not a method (I don't know enough VB to say for sure)
VB doesn't know that : operator
What you probably want is a Nullable(Of DateTime) to store a DateTime value that can also be missing.
Then use something like this to store the value:
myDateRequestUpdated = If(String.IsNullOrWhiteSpace(hfDateRequestUpdated.Value),
Nothing, DateTime.Parse(hfDateRequestUpdated.Value))
If hfDateRequestUpdated.Value is empty, then use Nothing as the result; else parse the value as date (which might fail if it is not a valid date!).
Try this:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim str As String
If TextBox1.Text.Length <> 0 Then
str = "'" & TextBox1.Text & "'"
Else
str = "NULL"
End If
sql = "insert into test(test1) values(" & str & ")"
dsave_sql(sql)
End Sub
Function save_sql(ByVal strsql As String, Optional ByVal msg As String = "Record Saved Sucessfully") As String
Dim sqlcon As New SqlConnection(strConn)
Dim comm As New SqlCommand(strsql, sqlcon)
Dim i As Integer
Try
sqlcon.Open()
i = CType(comm.ExecuteScalar(), Integer)
save_sql = msg
Catch ex As Exception
save_sql = ex.Message
End Try
sqlcon.Close()
Return i
End Function

how do I compare two dates?

We would like to compare a date from the db with current date.
Here is what I have tried so far:
'Obtain current date
Dim curdate As String = Now.ToString("yyyy")
'Now compare curdate with date from db called eventdate. Event date is of dateTime datatype.
If drv("eventdate").ToString = "" And Year(drv("eventdate").ToString) = curdate Then
'Then do some processing
End if
When I run this code, I get following error:
Conversion from string "" to type 'Date' is not valid.
Please help!
Thank you very much experts.
If Today.CompareTo(CDate(drv("eventdate")).Date) = 0 Then
'Do something
End If
I'm making the assumption here that you only care about the day, and not the time. Otherwise, the odds of having a match within a given day would be about 1 in 2.5 million.
Based on the comment:
If Today.Year.CompareTo(CDate(drv("eventdate")).Year) = 0 Then
'Do something
End If
or
If Today.Year = CDate(drv("eventdate")).Year Then
'Do something
End if
And one more thing: it really sounds like this is a check that should be done by your database. Make it part of the query that returns the results. This will be much faster, and it's where that kind of check belongs. All you'd need is add a check to your where clause like so:
Year(eventdate) = Year(current_timestamp)
If drv has an instance of DataReader then verify DBNull.
IF Not drv.IsDBNull(column_index_of_eventdate) Then
...
If drv.GetDateTime(column_index).Year=Date.Now.Year Then
...
End If
End If
I believe you have either a null or empty value, also your comparisn is wrong, try:
If drv("eventdate").ToString <> "" Andalso Year(drv("eventdate").ToString) = curdate Then
'Then do some processing
End if

Detect culture of number in VB.Net i.e. period or comma for decimal point / thousands separator

In VB.Net, is there a way of auto-detecting the culture of a string representation of a number? I'll explain the situation:
Our asp.net web site receives xml data feeds for boat data. Most of the time, the number format for the prices use either a simple non-formatted integer e.g. "999000". That's easy for us to process.
Occaisionally, there are commas for thousands separators and periods for the decimal point. Also, that's fine as our data import understands this. Example "999,000.00".
We're starting to get some data from France where some of the prices have been entered with the periods and thousands separators the other way around as that's the way it's done in many European countries. E.g. "999.000,00". This is where our system would interpret that as nine hundred and ninety nine pounds instead of the nine hundred and ninety nine thousand pounds that was intended.
Unfortunately, the data feed contains prices in a mixture of the formats without any culture indicator on each one. Does anyone know of any in-built .net functions that will auto-detect the culture of a string number based on where the period and comma are?
I found a thread on vbforums suggesting how to get the decimal separator by culture.
I made a converter that converts between different files using oledb, excel object, mysql and more. Using "decimalSeparator" was the solution to get the number format working correctly when I converted to Excel and Access files.
Dim decimalSeparator As String = Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
cellValue = cellValue.Replace(".", decimalSeparator ).Replace(",", decimalSeparator )
There is no built-in way to determine the CultureInfo from a numeric string, as far as I know. And I seriously doubt it'll ever be, because there is no 100% safe way to do it.
Until you find a better solution (eg: some change on the sender-side), I guess the best you can do is to decrease the chances of error in two steps:
1) Input data cleanup and standardization:
Dim input as String = " 99 9.000,00 "
' This way you can remove unwanted characters (anything that is not a digit, and the following symbols: ".", "-", ",")
Dim fixedInput as String = Regex.Replace(input, "[^\d-,\.]", "")
' fixedInput now is "999.000,00"
2) Guess yourself the format:
Dim indexOfDot as Integer = fixedInput.IndexOf(".")
Dim indexOfComma as Integer = fixedInput.IndexOf(",")
Dim cultureTestOrder as List(Of CultureInfo) = new List(Of CultureInfo)
Dim parsingResult as Double?
Try
If indexOfDot > 0 And indexOfComma > 0 Then
' There are both the dot and the comma..let's check their order
If indexOfDot > indexOfComma Then
' The dot comes after the comma. It should be en-US like Culture
parsingResult = Double.Parse(fixedInput, NumberStyles.Number, CultureInfo.GetCultureInfo("en-US"))
Else
' The dot comes after the comma. It should be it-IT like Culture
parsingResult = Double.Parse(fixedInput, NumberStyles.Number, CultureInfo.GetCultureInfo("it-IT"))
End If
Else If indexOfDot = fixedInput.Length-3 Then
' There is only the dot! And it is followed by exactly two digits..it should be en-US like Culture
parsingResult = Double.Parse(fixedInput, NumberStyles.Number, CultureInfo.GetCultureInfo("en-US"))
Else If indexOfComma = fixedInput.Length-3 Then
' There is only the comma! And it is followed by exactly two digits..it should be en-US like Culture
parsingResult = Double.Parse(fixedInput, NumberStyles.Number, CultureInfo.GetCultureInfo("it-IT"))
End If
Catch
End Try
If Not parsingResult.HasValue Then
Try
' There is no dot or comma, or the parsing failed for some reason. Let's try a less specific parsing.
parsingResult = Double.Parse(fixedInput, NumberStyles.Any, NumberFormatInfo.InvariantInfo)
Catch
End Try
End If
If Not parsingResult.HasValue Then
' Conversion not possible, throw exception or do something else
Else
' Use parsingResult.Value
End If
You are not 100% safe this way, but it should be still better than your current code (and at least works as expected on the example data your provided).
Without knowing the specifics of how many differne ways the string can be formatted... This works for the three examples you gave
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim v As String = "999.123,45"
Debug.WriteLine(foo(v))
v = "999,123.45"
Debug.WriteLine(foo(v))
v = "999123"
Debug.WriteLine(foo(v))
End Sub
Private Function foo(value As String) As Double
Dim style As NumberStyles = NumberStyles.AllowThousands Or NumberStyles.AllowDecimalPoint
Dim culture As CultureInfo = CultureInfo.InvariantCulture
Dim rv As Double
If Double.TryParse(value, style, culture, rv) Then
Debug.WriteLine(",.Converted '{0}' to {1}.", value, rv)
Else
Dim styleES As NumberStyles = NumberStyles.AllowThousands Or NumberStyles.AllowDecimalPoint
Dim cultureES As CultureInfo = CultureInfo.CreateSpecificCulture("es-ES")
If Double.TryParse(value, styleES, cultureES, rv) Then
Debug.WriteLine(".,Converted '{0}' to {1}.", value, rv)
Else
Throw New ArgumentException
End If
End If
Return rv
End Function
'This variable is True in case the O.S. Regional settings use a dot as decimal separator, false in the other cases.
Dim bAmerican as boolean=Cdec("0,2") > 1
Original post:
https://www.linkedin.com/groups/8141257/8141257-6347113651027079171

Resources