We recently migrated a very old site to a new server and are running into an odd issue. There is a simple if statement which should and did on old server read as true but it is not and not sure why. The statement is below. When I write out invflag it is equal to 1 which is what I would expect.
'does not trigger as true so iChk remains = ""
iChk = ""
if invflag = True then
iChk = "checked"
end if
'Works as expected
iChk = ""
if invflag = "1" then
iChk = "checked"
end if
'works as expected
iChk = ""
if invflag = 1 then
iChk = "checked"
end if
I know we can simply fix this as you can see but we have these types of statements littered throughout the code and if there is something with the server or database we can set that would be ideal and thought I would check.
Simply casting to CBool should do the trick for all cases:
If CBool(invflag) = True Then
iChk = "checked"
End If
or better
If CBool(invflag) Then
iChk = "checked"
End If
It turned out that during the migration from MSSQL to Mysql it converted the Bit fields to TinyInt. Once we changed the fields back to Bit the if statements worked as they did before.
Related
On a few of the Classic ASP websites I manage for the last few days I have been getting some error notifications (with no error number) that always show an error on a line number where a cookie value is being requested.
Looking at the request for each of these errors, they all have unusual cookies, and look like some sort of hack attempt.
The lines that are indicated as causing the error are all like this:
strCookieCart = Request.Cookies("cart")
Here's a couple of samples of the cookies being sent (truncated)... Note the =true (no name, just a value).
HTTP_COOKIE:=true; yuv=u97Yoe-o0UWp7ho_vaB2csT-xxaQ37gMWzhB1MARTSNk1QKpjJTXmZYMRQ095rM96MaNbhx1tEdJ
HTTP_COOKIE:pll_language=en; =true; yandexuid=6536735381437958890; st=6c9838994ffb
Is Classic ASP incapable of handling these? Is there any way to avoid these errors and ignore the bad values? Are these always likely to be hack attempts or could there be legitimate requests without cookie names?
I suppose I could check for these looking at Request.ServerVariables("HTTP_COOKIE") by manually parsing or using a regular expression check of some sort. Does anyone else do this? Any code to share?
A second answer to my own question and the solution I have now implemented is to add the following code to my common include file.
It tests whether Classic ASP can read the cookies and, using error trapping, ends the response if an error is detected.
On Error Resume Next
Request.Cookies("test")
If Err.Number <> 0 Then Response.End
On Error Goto 0
This is a better solution to my other answer as there is no point in generating a page for what is obviously an attack of some sort so ending the script as soon as possible is a better choice.
My proposed answer to my own question is to create a class that extracts all the valid keys and values for the cookies on initialisation, and has a function to return a value for a specified key.
Unfortunately it doesn't work for cookies that contain a collection of multiple values, but I don't generally use these anyway.
Here is the class:
<%
Class MyRequest
Private m_objCookies
Private Sub Class_Initialize()
Dim strCookies, i, strChar, strName, strValue, blnInValue
strCookies = Request.ServerVariables("HTTP_COOKIE")
Set m_objCookies = Server.CreateObject("Scripting.Dictionary")
i = 1
strName = ""
strValue = ""
blnInValue = False
Do
strChar = Mid(strCookies, i, 1)
If strChar = ";" Or i = Len(strCookies) Then
strValue = Trim(strValue)
If strName <> "" And strValue <> "" Then
If m_objCookies.Exists(strName) Then
m_objCookies.Item(strName) = strValue
Else
m_objCookies.Add strName, strValue
End If
End If
If i = Len(strCookies) Then Exit Do
strName = ""
strValue = ""
blnInValue = False
ElseIf strChar = "=" Then
strName = Trim(strName)
blnInValue = True
ElseIf blnInValue Then
strValue = strValue & strChar
Else
strName = strName & strChar
End If
i = i + 1
Loop
End Sub
Public Function Cookies(strKey)
Cookies = m_objCookies.Item(strKey)
End Function
End Class
%>
The changes to my code to use this class are minimal. Where I currently have...
strCookieCart = Request.Cookies("cart")
I will need to change to...
Dim objMyRequest : Set objMyRequest = New MyRequest
strCookieCart = objMyRequest.Cookies("cart")
I have tested the above with many of the bad requests I have logged and it works fine.
Add three line codes for #johna is answer, after this line:
If strChar = ";" Or i = Len(strCookies) Then
add these lines:
If i = Len(strCookies) And strChar <> ";" Then
strValue = strValue & strChar
End If
I did a simple experiment to make sure I know what is going on as I'm new to programming. This has me stumped and I'm getting angry with my computer for lying to me. :)
Here is my vb.net
If table2.Rows.Count = 0 Then
LBLCannary.Visible = True
End If
Now if I hover over during debug it tells me the count is zero. ie table2.Rows.Count 0 but for some odd reason it never goes to the next line in the if. if the table is empty. Why won't it work?
Answer: Silly newbie mistake, All this is done after return and nothing happens after a function returns something.
Can you try the reverse?
If table2 IsNot Nothing AndAlso table2.Rows.Count > 0 Then
'do nothing
Else
'if no rows or if table is empty
LBLCannary.Visible = True
End If
or widen your condition to
If table2 Is Nothing OrElse table2.Rows.Count < 1 Then
LBLCannary.Visible = True
End If
I have a conditional statement in Page_Load that checks if the value of a text box is blank. however, I also want to test for null as well. I'm having some issue with my syntax.
This is my conditional statement (works well):
If (textUserName.Text.ToString <> "") Then
textUserName.[ReadOnly] = True
End If
My question is, how can I check for null as well using "or" (preferred)?
...perhaps using elseif
This is what I've tried using "elseif":
If (textUserName.Text.ToString <> "") Then
textUserName.[ReadOnly] = True
ElseIf (textUserName.Text.ToString <> vbNull) Then
textUserName.[ReadOnly] = True
End If
Though my application functions well w/ the condition I'm using, plus the field for the username is set in the database to not allow Nulls, I was just curious as to how I would set my condition if I had to deal with a Null value. Thanks
Use String.IsNullOrEmpty to check for null strings
If textUserName.Text <> "" Or Not String.IsNullOrEmpty(textUserName.Text) Then
textUserName.[ReadOnly] = True
End If
Or... Which I believe is better:
If Not String.IsNullOrEmpty(Trim(textUserName.Text)) Then
textUserName.[ReadOnly] = True
End If
I have to make my previous stand alone project into a web application. Everything works OK, for the most part, however my counter is not. The user has an option to see how many answers they are getting correct and incorrect. I copied most of my code from the original project with the exception of a few tweeks... idk what I'm not doing right.
When you input a correct answer nothing shows, but when you input a wrong answer it shows
correct:0 incorrect:1 and it doesn't change. I tried with making numCorrect and numIncorrect equal 0 as seen below... still nothing.
Any help will be greatly appreciated!
Protected Sub CheckButton_Click(sender As Object, e As EventArgs) Handles CheckButton.Click
'assign numbers to variable for calculation
Dim correctAnswer As Integer
Dim numCorrect As Integer = 0
Dim numIncorrect As Integer = 0
num1 = CInt(Val(FirstNumLabel.Text))
num2 = CInt(Val(SecondNumLabel.Text))
answerNum = CInt(Val(AnswerTextBox.Text))
'calculate the correct answer
Select Case OperationsRadioButtonList.SelectedIndex = 0
Case True
'addition operation
correctAnswer = num1 + num2
Case False
'subtraction operation
correctAnswer = num1 - num2
End Select
'tell user if their input is correct or incorrect
'show images and messages when answer is correct
If answerNum = correctAnswer Then
MessageLabel.Text = "Nice Job!"
HFaceImage.Visible = True
SFaceImage.Visible = False
'add count for numbers correct to summary
numCorrect += 1
'clear textbox for new input and focus to textbox for new
With AnswerTextBox
.Text = ""
.Focus()
End With
'generate new random set
Call RandomNumberGenerator()
Else 'show image and message if answer is incorrect
SFaceImage.Visible = True
HFaceImage.Visible = False
'add count for numbers incorrect to summary
numIncorrect = numIncorrect + 1 '
'display message if incorrect answer was given
MessageLabel.Text = "Try Again!"
'clear textbox for new input and focus to textbox
With AnswerTextBox
.Text = ""
.Focus()
End With
'show the number of correct and incorrect input when summaryCheckBox is checked
If CheckBox.Checked Then
CorrectCounterTextBox.Text = CStr(Val(numCorrect))
IncorrectCounterTextBox.Text = CStr(Val(numIncorrect))
Else
CorrectCounterTextBox.Text = ""
IncorrectCounterTextBox.Text = ""
End If
End If
End Sub
You set the CorrectCounterTextBox and IncorrectCounterTextBox text property inside the wrong answer code block, that is why the labels don't get updated when user gave correct answer. Take it out of the If ... Else ... End If block like below:
'tell user if their input is correct or incorrect
'show images and messages when answer is correct
If answerNum = correctAnswer Then
' your existing code
Else 'show image and message if answer is incorrect
SFaceImage.Visible = True
HFaceImage.Visible = False
'add count for numbers incorrect to summary
numIncorrect = numIncorrect + 1 '
'display message if incorrect answer was given
MessageLabel.Text = "Try Again!"
'clear textbox for new input and focus to textbox
With AnswerTextBox
.Text = ""
.Focus()
End With
' your existing code moved out to below.
End If
'show the number of correct and incorrect input when summaryCheckBox is checked
If CheckBox.Checked Then
CorrectCounterTextBox.Text = CStr(Val(numCorrect))
IncorrectCounterTextBox.Text = CStr(Val(numIncorrect))
Else
CorrectCounterTextBox.Text = ""
IncorrectCounterTextBox.Text = ""
End If
PS: You might want to remove the Dim numCorrect As Integer = 0 and Dim numIncorrect As Integer = 0 lines at the top of your code, otherwise your counters will never get incremented. Save the counters into Session or Viewstate instead.
Is it possible to check if a named field is within a record set?
EG id, field1, field2, field3 have been selected. Is it possible for VBScript to detect if field2 has been selected. I am also hoping this is possible without looping
Please assume I dont know, nor can see the actual SELECT. I need to detect this after the query has been executed.
This is how its done using a loop, I am also hoping this is possible without looping:
dim rs,field,foundField
sql = "SELECT * from table;"
set rs = conn.execute(sql)
For Each field in rs.Fields
if field.Name = "someFieldName" then
foundField = true
exit for
else
foundField = false
end if
next
TYIA
I use a similar function (in VB6) to the one proposed by bfavaretto... I'm curious why the OP says it doesn't work?
Public Function FieldExists(ByVal rs As Recordset, ByVal fieldName As String) As Boolean
On Error GoTo merr
FieldExists = rs.Fields(fieldName).name <> ""
Exit Function
merr:
FieldExists = False
End Function
This function works for me... and it doesn't return false negatives as far as I know. Also, it appears to be faster than executing a loop for fields that are included in the collection; for fields that are actually missing, the execution times of both methods seems to be equivalent.
EDIT
For VBScript, the above function would look like this:
Function FieldExists(ByVal rs, ByVal fieldName)
On Error Resume Next
FieldExists = rs.Fields(fieldName).name <> ""
If Err <> 0 Then FieldExists = False
Err.Clear
End Function
And the code posted in the question would look like:
dim rs,field,foundField
sql = "SELECT * from table;"
set rs = conn.execute(sql)
foundField = FieldExists(rs, "someFieldName")
I think you need the loop. Found this on MSDN (emphasis mine):
Most of the ASP built-in objects provide collections. Collections are
data structures similar to arrays that store strings, numbers, objects
and other values. Unlike arrays, collections expand and contract
automatically as items are retrieved or stored. The position of an
item will also move as the collection is modified. You can access an
item in a collection by its unique string key, by its index (position)
in the collection, or by iterating through all the items in the
collection.
In any case, you could try this (untested):
dim rs,field,foundField
sql = "SELECT * from table;"
set rs = conn.execute(sql)
if rs.Fields("someFieldName") then
' ... if this doesn't crash, it may return
' false negatives for columns containing null or 0
end if