Cannot get SQL Query to work with SafeSqlLiteral function - sql

I have a function SafeSqlLiteral, found online. It's a function to prevent SQL injection attacks. I want to use this function inside my SQL query like so:
Dim com As String = "SELECT * FROM Person WHERE " &
SafeSqlLiteral(SearchCriteria, 2)
SearchCriteria being user input. I want the user to be able to enter: strState LIKE 'M%' and show all the records matching a state like Maine. It feels like this would work. (SELECT * FROM Person WHERE strState LIKE 'M%')
I'm getting a whole bunch of errors (probably too many to post on here, but will post them if needed), and I'm having a hard time figuring out how to make my query work with the SafeSqlLiteral function.
Here is the SafeSqlLiteral function:
Public Function SafeSqlLiteral(theValue As System.Object,
theLevel As System.Object) As String
Dim strValue As String = DirectCast(theValue, String)
Dim intLevel As Integer = CInt(theLevel)
If strValue IsNot Nothing Then
If intLevel > 0 Then
strValue = strValue.Replace("'", "''")
strValue = strValue.Replace("--", "")
strValue = strValue.Replace("[", "[[]")
strValue = strValue.Replace("%", "[%]")
End If
If intLevel > 1 Then
Dim myArray As String() = New String() {"xp_ ", "update ", "insert ", "select ", "drop ", "alter ",
"create ", "rename ", "delete ", "replace "}
Dim i As Integer = 0
Dim i2 As Integer = 0
Dim intLenghtLeft As Integer = 0
For i = 0 To myArray.Length - 1
Dim strWord As String = myArray(i)
Dim rx As New Regex(strWord, RegexOptions.Compiled Or RegexOptions.IgnoreCase)
Dim matches As MatchCollection = rx.Matches(strValue)
i2 = 0
For Each match As Match In matches
Dim groups As GroupCollection = match.Groups
intLenghtLeft = groups(0).Index + myArray(i).Length + i2
strValue = strValue.Substring(0, intLenghtLeft - 1) + " " + strValue.Substring(strValue.Length - (strValue.Length - intLenghtLeft), strValue.Length - intLenghtLeft)
i2 += 5
Next
Next
End If
Return strValue
Else
Return strValue
End If
End Function
Thanks in advance for anyone helping me solve this problem! It's greatly appreciated!

Related

Check if an item is available in a JSON.NET Newtonsoft object

I have the line of code that I want which is:
mid= jToken.Value<double?>("mid") ?? 100;
in C# but I need it in VB.NET I got it from Get value from JToken that may not exist (best practices)
But I'm have a bit of trouble in converting that to the proper syntax in VB. I've tried
Dim mid As String = item.Value(Of String)("mid") ?? ""
But it does not like the?
What I would like is to end with an empty string or blank if the value is not in the object. This is my full code
Dim obj As JObject = JObject.Parse(respHTML)
Dim records As JArray = DirectCast(obj("records"), JArray)
For i As Integer = 0 To records.Count - 1
Dim item As JObject = DirectCast(records(i), JObject)
Dim pmid As Integer = item("pmid").Value(Of Integer)
Dim pmcid As String = item("pmcid").Value(Of String)
Dim doi As String = item("doi").Value(Of String)
' Dim mid As String = item("mid").Value(Of String)
Dim mid As String = item.Value(Of String)("mid") ?? ""
MessageBox.Show(pmid.ToString + " " + pmcid + " " + doi + " " + mid)
Next
I ended up with:
Dim obj As JObject = JObject.Parse(respHTML)
Dim records As JArray = DirectCast(obj("records"), JArray)
For i As Integer = 0 To records.Count - 1
Dim item As JObject = DirectCast(records(i), JObject)
Dim pmid As String = If(item.Value(Of String)("pmid"), "")
Dim pmcid As String = If(item.Value(Of String)("pmcid"), "")
Dim doi As String = If(item.Value(Of String)("doi"), "")
Dim mid As String = If(item.Value(Of String)("mid"), "")
MessageBox.Show(pmid.ToString + " " + pmcid + " " + doi + " " + mid)
Next
The message box line will be replaced with a database call

Pairs from a list of string in vb.net

I'm trying to pair elements of a list of string together, ie, out of a list of a,b,c,d; I'd like to see ab, bc, cd. Here's the code I have so far:
Dim C As New List(Of String)
For i = 0 To S.Count - 1
For j =i + 1 To S.Count - 1
C.Add("{" & S(i) & "," & S(j) & "}")
Next
Next
Dim value As String = String.Join(",", C)
TextBox2.Text = value
Currently, this code returns a power set of {a,b},{a,c},{a,d},{b,c},{b,d},{c,d}..
Is there an efficient way to do this?
It looks like you only want adjacent pairs so this should work for you:
Dim C As New List(Of String)
For i = 0 To S.Count - 2
C.Add("{" & S(i) & "," & S(i + 1) & "}")
Next
Dim value As String = String.Join(",", C)
TextBox2.Text = value
If so, simpler still:
Dim C As New List(Of String)
For i = 0 To S.Count - 2
C.Add(String.Format("{{{0},{1}}}", {S(i), S(i + 1)}))
Next
TextBox2.Text = String.Join(",", C)
As simple as that:
Dim input As String = "a,b,c,d"
Dim output As String = String.Empty
Dim toggleIgnoreComma As Boolean = True
For Each s As String In input
If s.Equals(","c) Then
If toggleIgnoreComma Then
toggleIgnoreComma = False
Continue For
Else
toggleIgnoreComma = True
End If
End If
output += s
Next

extracting text from comma separated values in visual basic

I have such kind of data in a text file:
12343,M,Helen Beyer,92149999,21,F,10,F,F,T,T,T,F,F
54326,F,Donna Noble,92148888,19,M,99,T,F,T,F,T,F,T
99999,M,Ed Harrison,92147777,28,F,5,F,F,F,F,F,F,T
88886,F,Amy Pond,92146666,31,M,2,T,F,T,T,T,T,T
37378,F,Martha Jones,92144444,30,M,5,T,F,F,F,T,T,T
22444,M,Tom Scully,92145555,42,F,6,T,T,T,T,T,T,T
81184,F,Sarah Jane Smith,92143333,22,F,5,F,F,F,T,T,T,F
97539,M,Angus Harley,92142222,22,M,9,F,T,F,T,T,T,T
24686,F,Rose Tyler,92142222,22,M,5,F,F,F,T,T,T,F
11113,F,Jo Grant,92142222,22,M,5,F,F,F,T,T,T,F
I want to extract the Initial of the first name and complete surname. So the output should look like:
H. Beyer, M
D. Noble, F
E. Harrison, M
The problem is that I should not use String Split function. Instead I have to do it using any other way of string handling.
This is my code:
Public Sub btn_IniSurGen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_IniSurGen.Click
Dim vFileName As String = "C:\temp\members.txt"
Dim vText As String = String.Empty
If Not File.Exists(vFileName) Then
lbl_Output.Text = "The file " & vFileName & " does not exist"
Else
Dim rvSR As New IO.StreamReader(vFileName)
Do While rvSR.Peek <> -1
vText = rvSR.ReadLine() & vbNewLine
lbl_Output.Text += vText.Substring(8, 1)
Loop
rvSR.Close()
End If
End Sub
You can use the TextFieldParserClass. It will parse the file and return the results directly to you as a string array.
Using MyReader As New Microsoft.VisualBasic.FileIO.
TextFieldParser("c:\logs\bigfile")
MyReader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
' Include code here to handle the row.
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
" is invalid. Skipping")
End Try
End While
End Using
For your wanted result, you may changed
lbl_Output.Text += vText.Substring(8, 1)
to
'declare this first
Dim sInit as String
Dim sName as String
sInit = vText.Substring(6, 1)
sName = ""
For x as Integer = 8 to vText.Length - 1
if vText.Substring(x) = "," Then Exit For
sName &= vText.Substring(x)
Next
lbl_Output.Text += sName & ", " & sInit
But better you have more than one lbl_Output ...
Something like this should work:
Dim lines As New List(Of String)
For Each s As String In File.ReadAllLines("textfile3.txt")
Dim temp As String = ""
s = s.Substring(s.IndexOf(","c) + 1)
temp = ", " + s.First
s = s.Substring(s.IndexOf(","c) + 1)
temp = s.First + ". " + s.Substring(s.IndexOf(" "c), s.IndexOf(","c) - s.IndexOf(" "c)) + temp
lines.Add(temp)
Next
The list Lines will contain the strings you need.

Get value of a string that is passed as parameter

I need to pass in parameters to my sub/function.
When the parameter is passed, the value in the string, I would like to get the value evaluated and sent as:
Dim strParams As String = drRow(0)
' drRow is a row from DB Table. the value in drRow(0) =
' "#FromDate=""" & Now.AddDays(-10).ToShortDateString & """&#ToDate=""" & Now.AddDays(-4).ToShortDateString "
I would like to see this converted to:
Dim strFinal as string
strFinal = ProcessString(strParams)
End Result should be:
strFinal = "#FromDate=10/09/2011&#ToDate=10/15/2011"
Any ideas how I can do this. I am getting the initial string from DB, I need to convert to the final string, I am not able to figure out how to write the "ProcessString" function.
Thanks for looking.
"IF" you can change your parameter statement to something simple like:
#FromDate=;-10;#ToDate=;-4
Then you can do something like this:
Dim strParams As String = "#FromDate=;-10;#ToDate=;-4"
Dim value As String = String.Empty
Dim parts() As String = strParams.Split(";"c)
If parts.Length = 4 Then
Dim fromDays As Integer
Dim toDays As Integer
If Integer.TryParse(parts(1), fromDays) AndAlso Integer.TryParse(parts(3), toDays) Then
value = parts(0) + Now.AddDays(fromDays).ToShortDateString + parts(2) + Now.AddDays(toDays).ToShortDateString
End If
End If
MessageBox.Show("Value = " & value)
If it's anything more complicated than that then you will have to start parsing every part of your string with lots of If and Select statements-- you should probably heed Jim Mischel's advice and try a different approach.
This is the end result of what i used based on suggestions.. Thanks Guys.
Public Function ProcessParameters(ByVal strParams As String) As String
Dim arrParams() As String
'strParams = "#FromDate=-10;&#ToDate=-4;&#CompanyID=1"
arrParams = strParams.Split(";")
Dim arrP() As String
Dim strFinalParams As String = ""
For Each strP As String In arrParams
arrP = strP.Split("=")
If arrP(0).ToString.EndsWith("Date") Then
strFinalParams &= arrP(0) & "=" & Now.AddDays(arrP(1)).ToShortDateString
Else
strFinalParams &= arrP(0) & "=" & arrP(1)
End If
Next
Return strFinalParams
End Function
}

vb.net xls to csv with quotes?

I have a xls file, or a csv without quotes, and using vb.net need to turn it into a csv with quotes around every cell. If I open the xls/csv without quotes in MS Access, set every column to text and then export it, its in the format I need. Is there an easier way? If not, how do I do replicate this in vb.net? Thanks.
If you use the .Net OLE DB provider, you can specify the .csv formatting details in a schema.ini file in the folder your data files live in. For the 'unquoted' .csv the specs
should look like
[noquotes.csv] <-- file name
ColNameHeader=True <-- or False
CharacterSet=1252 <-- your encoding
Format=Delimited(,) <--
TextDelimiter= <-- important: no " in source file
Col1=VendorID Integer <-- your columns, of course
Col2=AccountNumber Char Width 15
for the 'quoted' .csv, just change the name and delete the TextDelimiter= line (put quotes around text fields is the default).
Then connect to the Text Database and execute the statement
SELECT * INTO [quotes.csv] FROM [noquotes.csv]
(as this creates quotes.csv, you may want to delete the file before each experimental run)
Added to deal with "Empty fields must be quoted"
This is a VBScript demo, but as the important things are the parameters for .GetString(), you'll can port it to VB easily:
Dim sDir : sDir = resolvePath( "§LibDir§testdata\txt" )
Dim sSrc : sSrc = "noquotes.csv"
Dim sSQL : sSQL = "SELECT * FROM [" & sSrc & "]"
Dim oTxtDb : Set oTxtDb = New cADBC.openDb( Array( "jettxt", sDir ) )
WScript.Echo goFS.OpenTextFile( goFS.BuildPath( sDir, sSrc ) ).ReadAll()
Dim sAll : sAll = oTxtDb.GetSelectFRO( sSQL ).GetString( _
adClipString, , """,""", """" & vbCrlf & """", "" _
)
WScript.Echo """" & Left( sAll, Len( sAll ) - 1 )
and output:
VendorID;AccountNumber;SomethingElse
1;ABC 123 QQQ;1,2
2;IJK 654 ZZZ;2,3
3;;3,4
"1","ABC 123 QQQ","1,2"
"2","IJK 654 ZZZ","2,3"
"3","","3,4"
(german locale, therefore field separator ; and decimal symbol ,)
Same output from this VB.Net code:
Imports ADODB
...
Sub useGetString()
Console.WriteLine("useGetString")
Const adClipString As Integer = 2
Dim cn As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim sAll As String
cn.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=M:\lib\kurs0705\testdata\txt\;" _
& "Extended Properties=""text;"""
cn.Open()
rs = cn.Execute("SELECT * FROM [noquotes.csv]")
sAll = rs.GetString( adClipString, , """,""", """" & vbCrLf & """", "" )
cn.Close()
sAll = """" & Left( sAll, Len( sAll ) - 1 )
Console.WriteLine( sAll )
End Sub
Check out the method at this link.
What you can do to make sure quotes go around is append quotes to the beginning and end of each column data in the loop that is putting the column data in the file.
for example make the loop like this:
For InnerCount = 0 To ColumnCount - 1
Str &= """" & DS.Tables(0).Rows(OuterCount).Item(InnerCount) & ""","
Next
Public Class clsTest
Public Sub Test
Dim s as string = "C:\!Data\Test1.csv"
Dim Contents As String = System.IO.File.ReadAllText(s)
Dim aryLines As String() = Contents.Split(New String() { Environment.Newline }, StringSplitOptions.None)
Dim aryParts() As String
Dim aryHeader() As String
Dim dt As System.Data.DataTable
For i As Integer = 0 To aryLines.Length - 1
aryParts = SplitCSVLine(aryLines(i))
If dt Is Nothing And aryHeader Is Nothing Then
aryHeader = CType(aryParts.Clone, String())
ElseIf dt Is Nothing And aryHeader IsNot Nothing Then
dt = DTFromStringArray(aryParts, 1000, "", aryHeader)
Else
DTAddStringArray(dt, aryParts)
End If
Next
dt.dump
End Sub
Public Shared Function SplitCSVLine(strCSVQuotedLine As String) As String()
Dim aryLines As String() = strCSVQuotedLine.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
Dim aryParts As String() = Nothing
For i As Integer = 0 To aryLines.Length - 1
Dim regx As New Text.RegularExpressions.Regex(",(?=(?:[^\""]*\""[^\""]*\"")*(?![^\""]*\""))")
aryParts = regx.Split(aryLines(i))
For p As Integer = 0 To aryParts.Length - 1
aryParts(p) = aryParts(p).Trim(" "c, """"c)
Next
Next
Return aryParts
End Function
Public Shared Function DTFromStringArray(ByVal aryValues() As String, Optional ByVal intDefaultColumnWidth As Integer = 255, Optional ByVal strTableName As String = "tblArray", Optional ByVal aryColumnNames() As String = Nothing) As DataTable
If String.IsNullOrWhiteSpace(strTableName) Then strTableName = "tblArray"
Dim dt As DataTable = New DataTable(strTableName)
Dim colNew(aryValues.GetUpperBound(0)) As DataColumn
If aryColumnNames Is Nothing Then
ReDim aryColumnNames(aryValues.Length)
Else
If aryColumnNames.GetUpperBound(0) < aryValues.GetUpperBound(0) Then
ReDim Preserve aryColumnNames(aryValues.Length)
End If
End If
For x As Integer = aryColumnNames.GetLowerBound(0) To aryColumnNames.GetUpperBound(0)
If String.IsNullOrWhiteSpace(aryColumnNames(x)) Then
aryColumnNames(x) = "Field" & x.ToString
Else
aryColumnNames(x) = aryColumnNames(x)
End If
Next
For i As Integer = 0 To aryValues.GetUpperBound(0)
colNew(i) = New DataColumn
With colNew(i)
.ColumnName = aryColumnNames(i) '"Value " & i
.DataType = GetType(String)
.AllowDBNull = False
.DefaultValue = ""
.MaxLength = intDefaultColumnWidth
.Unique = False
End With
Next
dt.Columns.AddRange(colNew)
Dim pRow As DataRow = dt.NewRow
For i As Integer = aryValues.GetLowerBound(0) To aryValues.GetUpperBound(0)
pRow.Item(i) = aryValues(i)
Next
dt.Rows.Add(pRow)
Return dt
End Function
Public Shared Sub DTAddStringArray(ByRef dt As DataTable, ByVal aryRowValues() As String)
Dim pRow As DataRow
pRow = dt.NewRow
For i As Integer = aryRowValues.GetLowerBound(0) To aryRowValues.GetUpperBound(0)
pRow.Item(i) = aryRowValues(i)
Next
dt.Rows.Add(pRow)
End Sub
End Class