VBS Type mismatch CLng - vbscript

I am using VBScript for the first time as it is the only language that a program can read.
Relevant section of code
Dim input
Function printer ()
input = InputBox("Printer", "Input Required")
printer = input
End Function
The software then calls the value of 'printer', and everything works fine when I input numbers, but if I try any text, it throws the below error message
Error: 13, Type mismatch: 'CLng'
in the line:

Related

Difference in string when passing a carriage return

In Go, I run the application from the command line as follows:
myapp -message "FOK \nHost:"
In my code:
var args = os.Args
var command = args[1]
var message= args[2]
the message will have the value "FOK \nHost:". Printing the value of message gives me:
fmt.Println("message-> " + message)
output
message-> FOK \nHost:
but if I set the value of the message in the application using the same value, the output is different.
message = "FOK \nHost:"
output
message mod-> FOK
Host:
I'm trying to accomplish the second result, so I'm trying to figure out why are the arguments string different thane when I assign it in the code.

ASP Len() function returns Type Mismatch error

Below is my server side asp code of my classic ASP application:
Function isValidPACSSession()
...
Dim sessionID : sessionID = Request.QueryString("forSessionID")
isValidPACSSession = SessionID2PACSUserID(sessionID)
...
End Function
Function SessionID2PACSUserID(sSessionID)
if (Not IsNull(sSessionID) AND Len(sSessionID) > 0) then
...it fails here at the Len function.
else
...
end if
End Function
Len() function throws "Type Mismatch" error for this partcular instance, wheras other calls made to SessionID2PACSUserID() by other components are just fine. Please help.
looks like you're just trying to check if a value is present, why not do something like:
dim sessionLength : sessionLength = 0
if (Not IsNull(sSessionID) AND sSessionID <> "") then
sessionLength = Len( sSessionID )
I also agree with the above statement of the VS debugger not working very well with classic asp
found a solution.. Actually i had a local variable by the name "len" on the calle web page which was causing the len() to fail. Changed len variable name to nLength and Len() now works fine.

VBS running code from string

I have one string storing hexadecimal data (\xEA\x...). Is it anyway to run that code using vbs? Maybe doing some kind of casting to function pointer or similar.
The C version of what I'm trying to do would be:
unsigned char opcode[] = "\xc0\x...."
main()
{
int (*run)() = (int(*)())opcode;
run();
}
Thank you so much.
You can use function pointers (or function references) with the GetRef function:
dim fp : set fp = GetRef("ShowMessage")
call fp("Woosh")
function ShowMessage(msg)
msgbox msg
end function
To make this work for any string with normally illegal characters for function naming (like the backslash in hexadecimal data) you can use brackets in you function declaration:
dim fp : set fp = GetRef("99 problems")
call fp()
' note: functions normally cannot start with a digit or contain spaces
function [99 problems]()
msgbox "but this aint one"
end function
The only character you cannot use is a closing bracket: ]

SQL server reporting Validate parameter is in correct format

On my reporting application which is developed using SSRS 2005, I have a parameter of type string which accepts time. the time should be in the format "HH:mm:ss" How can I check if the input string is of correct format?
I tried to do the following
IsDate(TimeValue(parametr!stime.Value))
This returns true as long as the value is within range. But if the value is 24:00:00 or a wrong value then an exception is thrown.
I also tried to create a function in the report code as follows:
Public Function CheckNum(sNum as String) as Boolean
Dim msg as String
msg = ""
Try
If IsDate(TimeValue(sNum))=1 Then
Return True
Else
msg="Parameter must be a number"
End If
Catch ex as Exception
Return False
End Try
If msg <> "" Then
MsgBox(msg, 16, "Parameter Validation Error")
Err.Raise(6,Report) 'Raise an overflow
End If
End Function
And when I input a value 24:00:00 I still get an error
" The conversion of a char type to datetime data type resulted in an out of range date time value"
How can I handle the exception so that I don't the error?
EDIT:
public Function CheckNum(sNum as String) as Boolean
Dim REGEX_TIME = "^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$"
If System.Text.RegularExpressions.Regex.IsMatch(sNum, REGEX_TIME) Then
Return True
Else
Return False
End If
End Function
Then I assigned a parameter(validateTime) value as =Code.CheckNum(Parameters!sTime.Value)
But the value of the parameter is always true. When I specify a value greater than 23, I still see the error. Please see the image
Instead of using IsDate function, use VB.NET regular expressions. SSRS allows full use of .NET functions.
See an example of time regex.
A good tutorial on regex.
Example Code Console Application
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim REGEX_TIME = "^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$"
Dim InputList As List(Of String) = New List(Of String)
InputList.Add("25:00:21")
InputList.Add("22:00:21")
InputList.Add("AA:00:21")
InputList.Add("17:21:02")
For Each input As String In InputList
If Regex.IsMatch(input, REGEX_TIME) Then
Console.WriteLine("TIME " + input + " IS OK")
Else
Console.WriteLine("TIME " + input + " IS NOT OK")
End If
Next
End Sub
End Module
Output is :
TIME 25:00:21 IS NOT OK
TIME 22:00:21 IS OK
TIME AA:00:21 IS NOT OK
TIME 17:21:02 IS OK
I think, you can capture a InvalidCastException.

VB6 Can IsNumeric be wrong?

Is it possible to test a string with IsNumeric() and for it to return true, but when you cast that same string to an integer using CInt() and assign it to a variable of type integer that it will give a type mismatch error?
I ask because I was getting a type mismatch error, so I used IsNumeric() to check the string was numeric before trying to cast it, but I still get the error.
I am tearing my hair out with this.
Here is the code in question.
iGlobalMaxAlternatives = CInt(strMaxAlternatives) is where the error is occuring.
Dim strMaxAlternatives As String
Dim iGlobalMaxAlternatives As Integer
iGlobalMaxAlternatives = 0
bSurchargeIncInFare = True
strMaxAlternatives = ReadStringKeyFromRegistry("Software\TL\Connection Strings\" & sConn & "\HH", "MaxAlt")
If IsNumeric(strMaxAlternatives) And strMaxAlternatives <> "" Then
iGlobalMaxAlternatives = CInt(strMaxAlternatives)
End If
You may have an overflow due the maximum integer size; the currency type actually does very well for large numbers (but beware of any regional issues). See edits below for Int64 discussion.
According to MSDN documentation on IsNumeric:
IsNumeric returns True if the data
type of Expression is Boolean, Byte,
Decimal, Double, Integer, Long,
SByte, Short, Single, UInteger,
ULong, or UShort, or an Object that
contains one of those numeric types.
It also returns True if Expression is
a Char or String that can be
successfully converted to a number.
IsNumeric returns False if Expression
is of data type Date or of data type
Object and it does not contain a
numeric type. IsNumeric returns False
if Expression is a Char or String
that cannot be converted to a number.
Since you are getting a Type Mismatch, perhaps a Double is interfering with the conversion. The IsNumeric does not guarantee it is an Integer, just that it matches one of the numeric possibilities. If the number is a double, perhaps regional settings (comma versus period and so on) are causing the exception.
You might try converting it to a double and then to an integer.
' Using a couple of steps
Dim iValue As Integer
Dim dValue As Double
dValue = CDbl(SourceValue)
iValue = CInt(iValue)
' Or in one step (might make debugging harder)
iValue = CInt(CDbl(SourceValue))
EDIT: After your clarification, it appears you are getting an overflow conversion. First try using a Long and CLng() instead of CInt(). There is still a chance the entry is Int64 though, which is more difficult using VB6.
I have used the following code for the LARGE_INTEGER and Integer8 types (both Int64), but it may not work for your situation:
testValue = CCur((inputValue.HighPart * 2 ^ 32) + _
inputValue.LowPart) / CCur(-864000000000)
This example was from an LDAP password expiration example, but like I said it may or may not work in your scenario. If you don't have the LARGE_INTEGER type, it looks like:
Private Type LARGE_INTEGER
LowPart As Long
HighPart As Long
End Type
Search for LARGE_INTEGER and VB6 for more information.
EDIT: For debugging, it may be useful to temporarily avoid error handling and then turn it back on after passing the troubling lines:
If IsNumeric(strMaxAlternatives) And strMaxAlternatives <> "" Then
On Error Resume Next
iGlobalMaxAlternatives = CInt(strMaxAlternatives)
If Err.Number <> 0 Then
Debug.Print "Conversion Error: " & strMaxAlternatives & _
" - " & Err.Description
EndIf
On Error Goto YourPreviousErrorHandler
End If
Yes, "3.41" would be numeric but not an integer.
VB6 doesn't provide good methods to guarantee CInt won't fail. I've found the simplest way is to just use error-handling.
function TryParse(byval text as string, byref value as integer) as boolean
on error resume next
value = CInt(text)
TryParse = (err.number = 0)
endfunction
Of course your error-handling preferences may vary.
Yes. Try this:
If IsNumeric("65537") Then
Dim i As Integer
i = CInt("65537") 'throws an error on this line!
End If
This one's an overflow, but I think it illustrates the unreliability of IsNumeric() in general (especially for ints - for doubles it's much more reliable).
According to the VB6 documentation, "IsNumeric returns True if the data type of Expression is Boolean, Byte, Decimal, Double, Integer, Long, SByte, Short, Single, UInteger, ULong, or UShort, or an Object that contains one of those numeric types. It also returns True if Expression is a Char or String that can be successfully converted to a number."
Many of those cannot be converted to an Integer. For example "1.5" is numeric but it's not an integer. So, you can convert it to a number, but not necessarily an integer.
The following code works without a Type Mismatch error in Visual BASIC 6
Dim I As Integer
I = CInt("3.41")
The same for this variant
Dim I As Integer
Dim TempS As String
TempS = "3.41"
I = CInt(TempS)
Posting the code in question would help answer your question. Basically there are several function in VB6 that are used to convert strings into number.
CInt and Int convert into number but handle rounding different. Direct assignment works and equivalent to using CInt. Howver I recommend continuing to use CInt to make the operation clear to you and your fellow developers in the future.
CInt works on number with commas like "3,041.41" However VB6 has problem handling region settings so if you are using notation other than standard American English you will get strange results and errors.
Your best bet is to start logging the errors with the actual values it's working with so you can figure out whats going on.
IsNumeric will return true if it can convert the string to a number. Even if there are non-numeric characters in the string. I always loop though the string one character at a time and test each character. If one character fails then I can return an error.
Just found this nugget. If you run the following, script #1 returns TRUE but script #2 & #3 will fail:
SELECT ISNUMERIC('98,0') AS isNum -- Fails
SELECT CONVERT(INT, '98,0') -- Fails
SELECT CONVERT(NUMERIC(11,4), '98,0') -- Fails
Two options...
Change
If IsNumeric(strMaxAlternatives) And strMaxAlternatives <> "" Then
iGlobalMaxAlternatives = CInt(strMaxAlternatives)
End If
To
If IsNumeric(strMaxAlternatives) And strMaxAlternatives <> "" Then
iGlobalMaxAlternatives = CDbl(strMaxAlternatives) ' Cast to double instead'
End If
Or
If IsNumeric(strMaxAlternatives) And strMaxAlternatives <> "" Then
If CDbl(strMaxAlternatives) Mod 1 = 0 Then ' Make sure there\'s no decimal points'
iGlobalMaxAlternatives = CInt(strMaxAlternatives)
End If
End If

Resources