DateAdd() in Special Format - asp-classic

I've tried all the ways I see to add a month to a certain date then return that in a specific format but I'm at a loss. Here's my code but I need to format it:
replace( formatdatetime( dateadd( "m" , 1 , request("date") ), 0 ) , "/" , "-" ) & "' )
request("date") is in yyyyy-dd-mm hh:mm:ss format and that's how I need the new date.

The following should work perfect:
replace( formatdatetime( dateadd( "m" , 1 , cDate(request("date")) ), 0 ) , "/" , "-" )
Notice the use of the cDate function to convert a value to a date explicitly.
Edit:
I removed last part of your code & "' ), it gave me an error otherwise.

When working with dates, it's especially important to take care of the proper data (sub)types. Feeding a string to a function that expects a date (and relying on 'VBScript - and your local settings - will do the right thing') is dangerous.
Using replace will never change the order of the date parts.
FormatDateTime depends on the local/regional settings and should be avoided as a sure path to disaster.
One way to solve this problem + most of all other problems concerning fancy formatting in VBScript is to use a .Net System.Text.StringBuilder:
Given Lib.vbs:
' Lib.vbs - simple VBScript library/module
' use
' ExecuteGlobal goFS.OpenTextFile(<PathTo\Lib.vbs>).ReadAll()
' to 'include' Lib.vbs in you main script
Class ToBeAShamedOf
Public a
Public b
End Class ' ToBeAShamedOf
Class cFormat
Private m_oSB
Private Sub Class_Initialize()
Set m_oSB = CreateObject("System.Text.StringBuilder")
End Sub ' Class_Initialize
Public Function formatOne(sFmt, vElm)
m_oSB.AppendFormat sFmt, vElm
formatOne = m_oSB.ToString()
m_oSB.Length = 0
End Function ' formatOne
Public Function formatArray(sFmt, aElms)
m_oSB.AppendFormat_4 sFmt, (aElms)
formatArray = m_oSB.ToString()
m_oSB.Length = 0
End Function ' formatArray
End Class ' cFormat
and main.vbs:
' main.vbs - demo use of library/module Lib.vbs
' Globals
Dim gsLibDir : gsLibDir = ".\"
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
' LibraryInclude
ExecuteGlobal goFS.OpenTextFile(goFS.BuildPath(gsLibDir, "Lib.vbs")).ReadAll()
WScript.Quit demoDateFormat()
WScript.Quit main()
Function main()
Dim o : Set o = New ToBeAShamedOf
o.a = 4711
o.b = "whatever"
WScript.Echo o.a, o.b
main = 1 ' can't call this a success
End Function ' main
Function demoDateFormat()
Dim sD : sD = "2012-05-16 01:02:03" ' near future; not yyyyy!
Dim dtD : dtD = CDate(sD)
Dim dtDM : dtDM = DateAdd("m", 1, dtD)
Dim oFmt : Set oFmt = New cFormat
WScript.Echo oFmt.formatArray( _
" sD: {1}{0} dtD: {2}{0} dtDM: {3}{0}dtDM': {4}" _
, Array(vbCrLf, sD, dtD, dtDM, oFmt.formatOne("{0:yyyy-MM-dd hh:mm:ss}", dtDM)))
demoDateFormat = 0 ' seems to be decent
End Function ' demoDateFormat
you'll get:
cscript main.vbs
sD: 2012-05-16 01:02:03
dtD: 16.05.2012 01:02:03
dtDM: 16.06.2012 01:02:03
dtDM': 2012-06-16 01:02:03
(to be seen in the context of this answer)

This may help:
FormatDateTime(DateAdd("M",1,DateSerial(Left(request("date"),4),Mid(request("date"),9,2),Mid(request("date"),6,2))) & " " & Mid(request("date"),12,8),d,0)
It basically converts the string to a valid date in the native format, adds the 1 requested month and then rebuilds the string.
NOTE: request("date") looks as though it returns the current datetime so running it in this way may generate a final value that is a second or so out, if that's a problem then you will be better storing a static value in a variable, otherwise this should hopefully be ok.

Related

DateTime.ParseExact Equivalent for VB6?

Does anyone know if there's an actual equivalent method in VB6 for .NET's DateTime.ParseExact() method? I've tried using DateSerial(), IsDate() and CDate(), but, due to all of VB6's "helpfulness", I'm coming up with some unexpected results.
To be more specific, I'm trying to parse a text string from user input to validate whether or not it's an actual date. As an example, I'll be using the date 8/25/16. The usual expected input may or may not have delimiters between the month, day and year, so it may be entered as 82516.
Here's a sample of the code that's not working as intended (the value of 82516 is stored in the TempStr variable):
If IsDate(Format(TempStr, "#/##/##")) And IsDate(Format(TempStr, "##/#/##")) Then
TempDate = #12:00:00 AM#
ElseIf IsDate(Format(TempStr, "#/##/##")) Then
TempDate = CDate(Format(Tempstr, "#/##/##"))
ElseIf IsDate(Format(TempStr, "##/#/##")) Then
TempDate = CDate(Format(TempStr, "##/#/##"))
End If
Using the stated value, the first condition triggers. Knowing how it works, I understand why it's happening (it's "rearranging" the month, day and year to try to match a valid date), but I'm really trying to get it to parse the date in a specific order. I know that .NET's DateTime.ParseExact() method would get me there, but I have to do this in VB6 (maintaining some legacy code).
I tried using DateSerial():
If DateSerial(CInt(Right(TempStr, 2)), CInt(Left(TempStr, 1)), CInt(Mid(TempStr, 2, 2))) > #12:00:00 AM# Then
If DateSerial(CInt(Right(TempStr, 2)), CInt(Left(TempStr, 2)), CInt(Mid(TempStr, 3, 1))) > #12:00:00 AM# Then
TempDate = #12:00:00 AM#
Else
TempDate = DateSerial(CInt(Right(TempStr, 2)), CInt(Left(TempStr, 1)), CInt(Mid(TempStr, 2, 2)))
End If
Else
If DateSerial(CInt(Right(TempStr, 2)), CInt(Left(TempStr, 2)), CInt(Mid(TempStr, 3, 1))) > #12:00:00 AM# Then
TempDate = DateSerial(CInt(Right(TempStr, 2)), CInt(Left(TempStr, 2)), CInt(Mid(TempStr, 3, 1)))
Else
TempDate = #12:00:00 AM#
End If
End If
But that also comes along with an automatic correction if the values for any of the parameters fall outside of the acceptable ranges.
I also tried the following variation of the above code:
If IsDate(Format(TempStr, "m/dd/yy")) And IsDate(Format(TempStr, "mm/d/yy")) Then
...
But the first test results in an entirely different value of 3/12/26, which is WAY off from the original input.
Is there any way to accurately emulate the .NET DateTime.ParseExact() method in VB6, or am I just going to have to toss these types of user input values out as invalid/ambiguous?
I will personally write a function for ensuring the correct date is returned -
First get the string/integer, break it down into chunks and add values to those chunks and return a combined date...
Option Explicit
Public Function MakeCorrectDate()
Dim xMakeDate As Long, xDay As Integer, xMonth As Integer, xYear As Integer, xCentury As Integer, strCorrectDate As String
''xMake as long because of size, strCorrectDate as string to allow the /...
xMakeDate = txtInput.Text
''Assuming the format will ALWAYS be the same days, months and year (12/20/16) and length is ALWAYS 6...
xDay = Left$(xMakeDate, 2)
xMonth = Mid$(xMakeDate, 3, 2)
xYear = Right(xMakeDate, 2)
''First get the correct part to 1900 or 2000...
If xYear = "00" Then
xCentury = 20
ElseIf xYear < 99 And xYear > 20 Then ''Year 2000 and year 2020
xCentury = 19
Else
xCentury = 20
End If
strCorrectDate = xDay & "/" & xMonth & "/" & xCentury & xYear
txtYear.Text = strCorrectDate
End Function
Private Sub cmdGetCorrectDate_Click()
If Not Len(txtInput.Text) = 6 Then
MsgBox "Incorrect information, must be 6 or more characters."
Exit Sub
Else
Call MakeCorrectDate
End If
End Sub
Private Sub txtInput_Change()
''Ensure the user adds only numerical text...
Dim WshShell As Object
Set WshShell = CreateObject("WScript.Shell")
If Not IsNumeric(txtInput.Text) Then
WshShell.SendKeys "{BackSpace}"
End If
End Sub
Okay, so here's what I've come up with as a solution for my current needs. Similar to what #Andre-Oosthuizen posted above, I've decided to drastically simplify the validation from what I was doing before. This series of functions requires the user to enter a six-digit date (two-digit month, two-digit day, and two-digit year). I don't believe the century is going to be a factor in this specific application, so I'm going to leave that test out.
This should be acceptable to our users as they've had similar restrictions in other systems. While I'd personally prefer a more "bullet-proof" solution (such as using a DatePicker or other manipulation of the UI), I think this is going to be the most effective for our environment.
'----------------------------------------------------------------------
' LostFocus event handler for the txtEffectiveDate TextBox.
' Test for a valid date when the user attempts to leave the field.
'----------------------------------------------------------------------
Private Sub txtEffectiveDate_LostFocus()
' *********************************************************************
' ** Don't have the event handler try to do any parsing. Just pass **
' ** the .Text value to the validation function. If a date comes **
' ** back, reformat it to "look" like a date and move on. Otherwise **
' ** pop up an "error" message and return focus to the TextBox for **
' ** the user to correct their input. **
' *********************************************************************
Dim TempDate As Date
TempDate = CheckForValidDate(Me.txtEffectiveDate.Text)
If TempDate > #12:00:00 AM# Then
' If a valid Date is returned, put the formatted String value
' into the TextBox and move on.
Me.txtEffectiveDate.Text = Format(TempDate, "mm/dd/yy")
Else
' If the Date value is not valid (#12:00:00 AM#), notify the
' user and refocus on the TextBox to force the user to
' correct the input before continuing.
MsgBox "The date you entered was not valid." & vbCrLf & vbCrLf & _
"Please enter two digits for the month, two digits for the day and" & vbCrLf & _
"two digits for the year." & vbCrLf & vbCrLf & _
"For example, today's date should be entered as either " & Format(Now, "mmddyy") & vbCrLf & _
" or " & Format(Now, "mm/dd/yy") & ".", _
vbOKOnly + vbExclamation, "INVALID INPUT FORMAT"
Me.txtEffectiveDate.SetFocus
Me.txtEffectiveDate.SelStart = 0
Me.txtEffectiveDate.SelLength = Len(Me.txtEffectiveDate.Text)
End If
End Sub
'----------------------------------------------------------------------
' Attempts to convert the String input to a Date value. If the String
' value is already a Date (i.e., "1/1/16" or similar), go ahead and
' assume that the user wants that date and return it as a Date value.
' Otherwise, strip any non-numeric characters and break apart the input
' to pass along for further validation.
'----------------------------------------------------------------------
Private Function CheckForValidDate(ByVal DateStr As String) As Date
Dim TempDate As Date
If IsDate(DateStr) Then
' If the String value is already in a date format,
' just return the Date value of the String.
TempDate = CDate(DateStr)
Else
Dim TempStr As String
Dim CurrentChar As String
Dim TempYear As Integer
Dim TempMonth As Integer
Dim TempDay As Integer
Dim I As Integer
' Strip all non-numeric characters to get a purely numeric string.
For I = 1 To Len(DateStr)
CurrentChar = Mid(DateStr, I, 1)
If IsNumeric(CurrentChar) Then
TempStr = TempStr & CurrentChar
End If
Next I
' The all-numeric string should be exactly six characters
' (for this application).
If Len(Trim(TempStr)) = 6 Then
Dim NewDateStr As String
' Break the numeric string into the component parts -
' Month, Day, and Year. At six characters, there should
' be two characters for each element.
TempMonth = CInt(Left(TempStr, 2))
TempDay = CInt(Mid(TempStr, 3, 2))
TempYear = CInt(Right(TempStr, 2))
' Now pass the individual values to the second part of
' the validation to ensure each of the individual values
' falls within acceptable ranges.
NewDateStr = GetValidDateString(TempMonth, TempDay, TempYear)
' If the returned String value is not empty, then convert
' it to a Date value for returning to the calling method
If Len(Trim(NewDateStr)) > 0 Then
TempDate = CDate(NewDateStr)
End If
End If
End If
CheckForValidDate = TempDate
End Function
'----------------------------------------------------------------------
' Using numeric values for Month, Day, and Year, attempt to build a
' valid Date in mm/dd/yy format.
'----------------------------------------------------------------------
Private Function GetValidDateString(ByVal intMonth As Integer, ByVal intDay As Integer, ByVal intYear As Integer) As String
Dim ReturnStr As String
ReturnStr = ""
If intMonth >= 1 And intMonth <= 12 Then
Select Case intMonth
Case 1, 3, 5, 7, 8, 10, 12
' January, March, May, July, August, October and December
' have 31 days.
If intDay >= 1 And intDay <= 31 Then
ReturnStr = intMonth & "/" & intDay & "/" & intYear
End If
Case 4, 6, 9, 11
' April, June, September and November
' have 30 days
If intDay >= 1 And intDay <= 30 Then
ReturnStr = intMonth & "/" & intDay & "/" & intYear
End If
Case 2
' Depending on whether it is a Leap Year (every four years),
' February may have 28 or 29 days.
If intYear Mod 4 = 0 Then
If intDay >= 1 And intDay <= 29 Then
ReturnStr = intMonth & "/" & intDay & "/" & intYear
End If
Else
If intDay >= 1 And intDay <= 28 Then
ReturnStr = intMonth & "/" & intDay & "/" & intYear
End If
End If
End Select
End If
' Return the recombined string to the calling function.
GetValidDateString = ReturnStr
End Function
There's still obviously going to be some room for error, but I believe this will solve the issue for now. It's not perfect, but hopefully we'll be able to move away from this VB6 system soon. Thank you for all of the ideas and suggestions. They were very helpful in narrowing down the best solution for this specific implementation.

How to insert values of string builder to an Integer Stack? (VB.Net)

This code basically takes a mathematical expression and evaluates it.
The following code i have written in VB.net shamelessly taken from here : Expression Evaluation
which has been written in Java.
Public Function evaluate(expression As [String]) As Integer
Dim tokens As Char() = expression.ToCharArray()
' Stack for numbers: 'values'
Dim values As New Stack(Of UInteger)()
' Stack for Operators: 'ops'
Dim ops As New Stack(Of Char)()
For i As Integer = 0 To tokens.Length - 1
' Current token is a whitespace, skip it
If tokens(i) = " "c Then
Continue For
End If
' Current token is a number, push it to stack for numbers
If tokens(i) >= "0"c AndAlso tokens(i) <= "9"c Then
Dim sbuf As New StringBuilder(100)
'Dim sbuf As New String("", 128)
' There may be more than one digits in number
If i < tokens.Length AndAlso tokens(i) >= "0"c AndAlso tokens(i) <= "9"c Then
sbuf.Append(tokens(System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)))
End If
If sbuf Is Nothing AndAlso sbuf.ToString().Equals("") Then
Else
Dim intgr As Integer
Dim accpt As Boolean = Integer.TryParse(sbuf.ToString(), intgr)
If accpt = True Then
values.Push([Integer].Parse(sbuf.ToString()))
Else
Dim space As String = " "
values.Push(space)
End If
End If
' Current token is an opening brace, push it to 'ops'
ElseIf tokens(i) = "("c Then
ops.Push(tokens(i))
' Closing brace encountered, solve entire brace
ElseIf tokens(i) = ")"c Then
While ops.Peek() <> "("c
values.Push(applyOp(ops.Pop(), values.Pop(), values.Pop()))
End While
ops.Pop()
' Current token is an operator.
ElseIf tokens(i) = "+"c OrElse tokens(i) = "-"c OrElse tokens(i) = "*"c OrElse tokens(i) = "/"c Then
' While top of 'ops' has same or greater precedence to current
' token, which is an operator. Apply operator on top of 'ops'
' to top two elements in values stack
While Not ops.Count = 0 AndAlso hasPrecedence(tokens(i), ops.Peek())
values.Push(applyOp(ops.Pop(), values.Pop(), values.Pop()))
End While
' Push current token to 'ops'.
ops.Push(tokens(i))
End If
Next
' Entire expression has been parsed at this point, apply remaining
' ops to remaining values
While Not ops.Count = 0
values.Push(applyOp(ops.Pop(), values.Pop(), values.Pop()))
End While
' Top of 'values' contains result, return it
Return values.Pop()
End Function
Public Function hasPrecedence(op1 As Char, op2 As Char) As [Boolean]
If op2 = "("c OrElse op2 = ")"c Then
Return False
End If
If (op1 = "*"c OrElse op1 = "/"c) AndAlso (op2 = "+"c OrElse op2 = "-"c) Then
Return False
Else
Return True
End If
End Function
' A utility method to apply an operator 'op' on operands 'a'
' and 'b'. Return the result.
Public Function applyOp(op As Char, b As Integer, a As Integer) As Integer
Select Case op
Case "+"c
Return a + b
Case "-"c
Return a - b
Case "*"c
Return a * b
Case "/"c
If b = 0 Then
'Throw New UnsupportedOperationException("Cannot divide by zero")
End If
Return a \ b
End Select
Return 0
End Function
this is how im using the code :
formula = "10 + 2 * 6"
Dim result As Double = evaluate(formula)
and i keep getting this following error:
Unhandled exception at line 885, column 13 in http:**** DEDOM5KzzVKtsL1tWZwgsquruscgqkpS5bZnMu2kotJDD8R38OukKT4TyG0z97U1A8ZC8o0wLOdVNYqHqQLlZ9egcY6AKpKRjQWMa4aBQG1Hz8t_HRmdQ39BUIKoCWPik5bv4Ej6LauiiQptjuzBMLowwYrLGpq6dAhVvZcB-4b-mV24vCqXJ3jbeKi0&t=6119e399
0x800a139e - Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: Conversion from string " " to type 'UInteger' is not valid.
Im a beginner but i think that the error is occurring because its not able to covert space into integer.How to deal with the spaces??
Any help is much appreciated:).
VB.NET is strongly-typed, so you simply cannot push anything other than integers onto a Stack(Of Integer). Therefore this code:
Dim space As String = " "
values.Push(space)
will always fail at runtime. (By the way, you want to set Option Explicit On and Option Strict On at the top of every module. If you do that, the line above will already be marked as an error at build time).
I haven't tried executing your code, but why would you need to save the spaces if what you're building is an expression evaluator? It doesn't seem to add anything to the evaluation. Perhaps if you simply don't add the spaces to the stack it will work anyway.

asp classic : checking values in an array

I am making a simple questionnaire for a client in Classic ASP.
The idea is that there will be 10 questions. The user registers and is being sent to the first question. When this is answered they move on to the 2nd question etc.
Questions can be skipped and returned to at a later date, and each question can only be answered once.
I have a comma separated list in the database of each question a user has answered.
So, a user logs in and an array is created with the list of answered questions.
What would be the best way to loop through this list and go to the first unanswered question?
An example of the array of answered questions would look something like this "1,4,6"
so this user would have answered questions number 1, 4 and 6. When a user logs in I'd like to direct them to the first unanswered question, in this case 2. Once the second question is answered the user would be redirected to the next unanswered question.
Any suggestions please?
#Dog, I think this offers the functionality you are looking for.
Tip: See this answer for information on downloading Microsoft's authoritative WSH reference as a Windows help file.
Option Explicit
Dim oQsm : Set oQsm = New QuestionStatusManager
With oQsm
.NumberOfQuestions = 10
.RestoreStatus("1,4,6")
.MarkQuestionAnswered(2)
WScript.Echo "Questions " & .ToString() & " have been answered."
WScript.Echo "Next unanswered question is: " & .GetNextUnansweredQuestion()
End With
Set oQsm = Nothing
' ------------------------------------------------------------------------
Class QuestionStatusManager
Private m_nNumberOfQuestions
Private m_aQuestionList()
Sub Class_Initialize()
m_nNumberOfQuestions = -1
End Sub
Sub Class_Terminate()
Erase m_aQuestionList
End Sub
Public Property Let NumberOfQuestions(n)
Dim bValid : bValid = False
If IsNumeric(n) Then
If n = CInt(n) Then
bValid = True
End If
End If
If Not bValid Then
Err.Raise vbObjectError + 1, "", _
"Value '" & n & "' is not an integer."
End If
m_nNumberOfQuestions = CInt(n)
ReDim m_aQuestionList(n)
End Property
Public Property Get NumberOfQuestions()
CheckState
NumberOfQuestions = m_nNumberOfQuestions
End Property
Private Sub CheckState()
If m_nNumberOfQuestions = -1 Then
Err.Raise vbObjectError + 1, "", _
"Property 'NumberOfQuestions' has not been set."
End If
End Sub
Sub RestoreStatus(sAlreadyAnswered)
CheckState
Dim aAlreadyAnswered : aAlreadyAnswered = Split(sAlreadyAnswered, ",")
Dim i
For i = 0 To UBound(m_aQuestionList)
m_aQuestionList(i) = False
Next
For i = 0 To UBound(aAlreadyAnswered)
m_aQuestionList(CInt(aAlreadyAnswered(i))) = True
Next
End Sub
Sub MarkQuestionAnswered(n)
Dim sDesc
CheckState
On Error Resume Next
m_aQuestionList(n) = True
If Err Or n = 0 Then
sDesc = Err.Description
On Error GoTo 0
Err.Raise vbObjectError + 1, "", _
"Can't mark question number '" & n & "' as answered: " & sDesc
End If
End Sub
Function GetNextUnansweredQuestion()
CheckState
Dim i
For i = 1 To UBound(m_aQuestionList)
If Not m_aQuestionList(i) Then
GetNextUnansweredQuestion = i
Exit Function
End If
Next
GetNextUnansweredQuestion = -1
End Function
Function ToString()
CheckState
Dim sDelim : sDelim = ""
Dim i
ToString = ""
For i = 1 To UBound(m_aQuestionList)
If m_aQuestionList(i) Then
ToString = ToString & sDelim & CStr(i)
sDelim = ","
End If
Next
End Function
End Class

Sql injection script

This title of the question may seem to be previously asked and answered but its different scenario for me. I use this script to stop sql injection in my ASP site. As per my knowledge or injecting script i have tried everything . Is it still possible to break through this code or do you feel this is fine .
Here is the script
<%
Function IsInject(strCheck, boolForm)
IsInject = False
If Not boolForm And Len(strCheck) > 50 Then IsInject = True
' Dim sCmdList, arrCmds, i
If boolForm Then
sCmdList = "declare,varchar,convert,delete,create,is_srvrolemember,ar(,cast("
Else
sCmdList = "update,union,select,drop,declare,varchar,convert,delete,create,is_srvrolemember,ar(,cast(,char("
End If
arrCmds = Split(sCmdList, ",")
For i = 0 To UBound(arrCmds)
If Instr(UCase(CStr(strCheck)), UCase(arrCmds(i))) > 0 Then
IsInject = True
Exit For
End If
Next
Erase arrCmds
End Function
Function CleanInject(strClean, boolInt)
If boolInt Then CleanInject = CInt(strClean) Else CleanInject = Replace(strClean, "'", "''")
End Function
'-----------------------------------------------------------
'redirect user if specific IP
'Dim ipaddress, bFBIRedirect, sInjectType
bFBIRedirect = True
ipaddress = Request.ServerVariables("REMOTE_ADDR")
Select Case ipaddress
Case "90.120.206.10"
Case Else
bFBIRedirect = False
End Select
If bFBIRedirect Then Response.Redirect "http://www.fbi.gov"
'-----------------------------------------------------------
'Dim bIsInject, sHackString
bIsInject = False
If Not bInject Then
' Dim qsItm
For Each qsItm In Request.QueryString
If IsInject(Request.QueryString(qsItm), False) Then
bIsInject = True
sHackString = qsItm & "=" & Request.QueryString(qsItm)
sHackType = "QueryString"
sInjectType = "qs-" & Request.QueryString(qsItm)
Exit For
End If
Next
End If
If Not bInject Then
' Dim frmItm
' For Each frmItm In Request.Form
' If IsInject(Request.Form(frmItm), True) Then
' bIsInject = True
' sHackString = Request.Form(frmItm)
' sHackString = frmItm & "=" & Request.Form(frmItm)
' sHackType = "Form"
' Exit For
' End If
' Next
End If
If bIsInject Then
Session("hacktype") = sHackType
Session("hackstr") = sHackString
Session("thepagefrom") = Request.ServerVariables("PATH_INFO")
Session("theip") = Request.ServerVariables("REMOTE_ADDR")
' Dim arrWhereAt, iWhereAt, sRedirect
arrWhereAt = Split(Request.ServerVariables("PATH_INFO"), "/")
iWhereAt = UBound(arrWhereAt)
sRedirect = "unknownerror.asp?ip=" & Request.ServerVariables("REMOTE_ADDR") & "&err=" & sInjectType & "&pg=" & Request.ServerVariables("PATH_INFO")
If iWhereAt = 1 Then sRedirect = "../" & sRedirect
If iWhereAt = 2 Then sRedirect = "../../" & sRedirect
If iWhereAt = 3 Then sRedirect = "../../../" & sRedirect
Response.Redirect sRedirect
End If
%>
Using blacklists to remove commands is not really a good idea. You have to make sure you cover all possible commands, and still someone might sneak something past. This would also probably fail if you get data from a user that is not an attack, but still contains an attack string. Example "Back in the days of the Soviet Union".
As Nikolai suggests, see if you can find some type of prepared statements to use. Or find a really good library to properly escape data for you.
rather doing that I think I would use ADO Parameter object when creating SQL queries, the second best thing is to do type conversion of the inputfields for the dynamic SQL queries, such as converting strings to SQL strings (replace any ' with two ''), making sure number is a number etc.

ASP.Net String Split not working

Here's my code
Dim RefsUpdate As String() = Session("Refs").Split("-"C)
Dim PaymentsPassedUpdate As String() = Session("PaymentsPassed").Split("-"C)
Dim x as Integer
For x = 1 to RefsUpdate.Length - 1
Dim LogData2 As sterm.markdata = New sterm.markdata()
Dim queryUpdatePaymentFlags as String = ("UPDATE OPENQUERY (db,'SELECT * FROM table WHERE ref = ''"+ RefsUpdate(x) +"'' AND bookno = ''"+ Session("number") +"'' ') SET alpaid = '"+PaymentsPassedUpdate(x) +"', paidfl = 'Y', amountdue = '0' ")
Dim drSetUpdatePaymentFlags As DataSet = Data.Blah(queryUpdatePaymentFlags)
Next
I don't get any errors for this but it doesn't seem to working as it should
I'm passing a bookingref like this AA123456 - BB123456 - CC123456 - etc and payment like this 50000 - 10000 - 30000 -
I basically need to update the db with the ref AA123456 so the alpaid field has 50000 in it.
Can't seem to get it to work
Any ideas?
Thanks
Jamie
I'm not sure what isn't working, but I can tell you that you are not going to process the last entry in your arrays. You are going from 1 to Length - 1, which is one short of the last index. Therefore, unless your input strings end with "-", you will miss the last one.
Your indexing problem mentioned by Mark is only one item, but it will cause an issue. I'd say looking at the base your problem stems from not having trimmed the strings. Your data base probably doesn't have spaces leading or trailing your data so you'll need to do something like:
Dim refsUpdateString as string = RefsUpdate(x).Trim()
Dim paymentsPassedUpdateString as string = PaymentsPassedUpdate(x).Trim()
...
Dim queryUpdatePaymentFlags as String = ("UPDATE OPENQUERY (db,'SELECT * FROM table WHERE ref = ''" & refsUpdateString & "'' AND bookno = ''" & Session("number") & "'' ') SET alpaid = '" & paymentsPassedUpdateString & "', paidfl = 'Y', amountdue = '0' ")
Also, I would recommend keeping with the VB way of concatenation and use the & character to do it.

Resources