use of double quotes as string - vb.net

I am developing in vb.net
Dim dtDetails As DataTable = Utility.GetDetailsTable()
Dim resource_id As String = ""
Dim dtrow = dtDetails.Select("id='" & user_id & "'")
If dtrow.Length > 0 Then
For i As Integer = 0 To dtrow.Length - 1
If i > 0 Then
resource_id += ","
End If
resource_id += Convert.ToString(dtrow(i)("instance_id"))
Next
but when I use resource_id further, it is not working, Docs returns as empty
Dim resource_ids = New BsonValue() {resource_id}
Dim querys = Query.And(
Query.EQ("user_id", user_id),
Query.In("resource_id", resource_ids)
)
Dim Docs = ceilometer.GetCollection("meter").Find(querys)
because I need it in this format BsonValue(){"resource_id1","resource_id2"}. Please help me to solve this

From how I understood your question, I believe you need to add the dynamic ids to the BsonValue array. Using an extension from this answer:
<Extension()> _
Public Sub Add(Of T)(ByRef arr As T(), item As T)
Array.Resize(arr, arr.Length + 1)
arr(arr.Length - 1) = item
End Sub
Which you can then use in your code as:
Dim dtDetails As DataTable = Utility.GetDetailsTable()
Dim resource_ids As new BsonArray
Dim dtrow = dtDetails.Select("id='" & user_id & "'")
If dtrow.Length > 0 Then
For i As Integer = 0 To dtrow.Length - 1
resource_ids.Add(Convert.ToString(dtrow(i)("instance_id")))
Next
End If
Dim queries = Query.And(
Query.EQ("user_id", user_id),
Query.In("resource_id", resource_ids)
)
Dim Docs = ceilometer.GetCollection("meter").Find(queries)

Related

I want to make a maths quiz on vb.net that uses bracket questions

So I've used visual basics (vb.net) for a bit now and understand some stuff. Right now I want to make a maths quiz that when I click a button it takes me to a new form and starts the quiz. When the quiz starts I want it so it gives the user random numbers and the user needs to answer it in a textbox and if correct it moves on to the next question (Basic, I should be able to do). IMPORTANT - my question is, there's a maths rule called BODMAS (Bracket.Order.Division.Multiply.Add.Subtract) and I want to add this rule into my coding instead of doing regular simple maths...
EXAMPLE question is 2 x (2+3) - 1 = ?
2 x 5 - 1 = ?
10 - 1 = ?
9 = 9
person writes answer to textbox and moves to next similar question
This is my first time using this but I wanted to write in-depth so people can understand. Please help me if you find a video explaining what I'm looking for or if someone has a file with a similar code I could download would be greatly appreciated!
Basically,you need to determine the range of numbers you use, and then match them randomly among '*', '/', '+', '-'. Then randomly insert brackets into it.
Private codeStr As String
Private Function GenerateMathsQuiz() As String
Dim r As Random = New Random()
Dim builder As StringBuilder = New StringBuilder()
'The maximum number of operations is five, and you can increase the number [5] to increase the difficulty
Dim numOfOperand As Integer = r.[Next](1, 5)
Dim numofBrackets As Integer = r.[Next](0, 2)
Dim randomNumber As Integer
For i As Integer = 0 To numOfOperand - 1
'All numbers will be random between 1 and 10
randomNumber = r.[Next](1, 10)
builder.Append(randomNumber)
Dim randomOperand As Integer = r.[Next](1, 4)
Dim operand As String = Nothing
Select Case randomOperand
Case 1
operand = "+"
Case 2
operand = "-"
Case 3
operand = "*"
Case 4
operand = "/"
End Select
builder.Append(operand)
Next
randomNumber = r.[Next](1, 10)
builder.Append(randomNumber)
If numofBrackets = 1 Then
codeStr = InsertBrackets(builder.ToString())
Else
codeStr = builder.ToString()
End If
Return codeStr
End Function
Public Function InsertBrackets(ByVal source As String) As String
Dim rx As Regex = New Regex("\d+", RegexOptions.Compiled Or RegexOptions.IgnoreCase)
Dim matches As MatchCollection = rx.Matches(source)
Dim count As Integer = matches.Count
Dim r As Random = New Random()
Dim numIndexFirst As Integer = r.[Next](0, count - 2)
Dim numIndexLast As Integer = r.[Next](1, count - 1)
While numIndexFirst >= numIndexLast
numIndexLast = r.[Next](1, count - 1)
End While
Dim result As String = source.Insert(matches(numIndexFirst).Index, "(")
result = result.Insert(matches(numIndexLast).Index + matches(numIndexLast).Length + 1, ")")
Return result
End Function
When you finish this, you will get a math quiz, then you need to know how to compile and run code at runtime.
Private Function GetResult(ByVal str As String) As String
Dim sb As StringBuilder = New StringBuilder("")
sb.Append("Namespace calculator" & vbCrLf)
sb.Append("Class calculate " & vbCrLf)
sb.Append("Public Function Main() As Integer " & vbCrLf)
sb.Append("Return " & str & vbCrLf)
sb.Append("End Function " & vbCrLf)
sb.Append("End Class " & vbCrLf)
sb.Append("End Namespace" & vbCrLf)
Dim CompilerParams As CompilerParameters = New CompilerParameters()
CompilerParams.GenerateInMemory = True
CompilerParams.TreatWarningsAsErrors = False
CompilerParams.GenerateExecutable = False
CompilerParams.CompilerOptions = "/optimize"
Dim references As String() = {"System.dll"}
CompilerParams.ReferencedAssemblies.AddRange(references)
Dim provider As VBCodeProvider = New VBCodeProvider()
Dim compile As CompilerResults = provider.CompileAssemblyFromSource(CompilerParams, sb.ToString())
If compile.Errors.HasErrors Then
Dim text As String = "Compile error: "
For Each ce As CompilerError In compile.Errors
text += "rn" & ce.ToString()
Next
Throw New Exception(text)
End If
Dim Instance = compile.CompiledAssembly.CreateInstance("calculator.calculate")
Dim type = Instance.GetType
Dim methodInfo = type.GetMethod("Main")
Return methodInfo.Invoke(Instance, Nothing).ToString()
End Function
Finally, you can use these methods like:
Private Sub GetMathQuizBtn_Click(sender As Object, e As EventArgs) Handles GetMathQuizBtn.Click
Label1.Text = GenerateMathsQuiz()
End Sub
Private Sub ResultBtn_Click(sender As Object, e As EventArgs) Handles ResultBtn.Click
If TextBox1.Text = GetResult(Label1.Text) Then
MessageBox.Show("bingo!")
TextBox1.Text = ""
Label1.Text = GenerateMathsQuiz()
Else
MessageBox.Show("result is wrong")
End If
End Sub
Result:

Cannot get SQL Query to work with SafeSqlLiteral function

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!

How can I get String values rather than integer

How To get StartString And EndString
Dim startNumber As Integer
Dim endNumber As Integer
Dim i As Integer
startNumber = 1
endNumber = 4
For i = startNumber To endNumber
MsgBox(i)
Next i
Output: 1,2,3,4
I want mo make this like sample: startString AAA endString AAD
and the output is AAA, AAB, AAC, AAD
This is a simple function that should be easy to understand and use. Every time you call it, it just increments the string by one value. Just be careful to check the values in the text boxes or you can have an endless loop on your hands.
Function AddOneChar(Str As String) As String
AddOneChar = ""
Str = StrReverse(Str)
Dim CharSet As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim Done As Boolean = False
For Each Ltr In Str
If Not Done Then
If InStr(CharSet, Ltr) = CharSet.Length Then
Ltr = CharSet(0)
Else
Ltr = CharSet(InStr(CharSet, Ltr))
Done = True
End If
End If
AddOneChar = Ltr & AddOneChar
Next
If Not Done Then
AddOneChar = CharSet(0) & AddOneChar
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim S = TextBox1.Text
Do Until S = TextBox2.Text
S = AddOneChar(S)
MsgBox(S)
Loop
End Sub
This works as a way to all the codes given an arbitrary alphabet:
Public Function Generate(starting As String, ending As String, alphabet As String) As IEnumerable(Of String)
Dim increment As Func(Of String, String) = _
Function(x)
Dim f As Func(Of IEnumerable(Of Char), IEnumerable(Of Char)) = Nothing
f = _
Function(cs)
If cs.Any() Then
Dim first = cs.First()
Dim rest = cs.Skip(1)
If first = alphabet.Last() Then
rest = f(rest)
first = alphabet(0)
Else
first = alphabet(alphabet.IndexOf(first) + 1)
End If
Return Enumerable.Repeat(first, 1).Concat(rest)
Else
Return Enumerable.Empty(Of Char)()
End If
End Function
Return New String(f(x.ToCharArray().Reverse()).Reverse().ToArray())
End Function
Dim results = New List(Of String)
Dim text = starting
While True
results.Add(text)
If text = ending Then
Exit While
End If
text = increment(text)
End While
Return results
End Function
I used it like this to produce the required result:
Dim alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim results = Generate("S30AB", "S30B1", alphabet)
This gave me 63 values:
S30AB
S30AC
...
S30BY
S30BZ
S30B0
S30B1
It should now be very easy to modify the alphabet as needed and to use the results.
One option would be to put those String values into an array and then use i as an index into that array to get one element each iteration. If you do that though, keep in mind that array indexes start at 0.
You can also use a For Each loop to access each element of the array without the need for an index.
if the default first two string value of your output is AA.
You can have a case or if-else conditioning statement :
and then set 1 == A 2 == B...
the just add or concatenate your default two string and result string of your case.
I have tried to understand that you are looking for a series using range between 2 textboxes. Here is the code which will take the series and will give the output as required.
Dim startingStr As String = Mid(TextBox1.Text, TextBox1.Text.Length, 1)
Dim endStr As String = Mid(TextBox2.Text, TextBox2.Text.Length, 1)
Dim outputstr As String = String.Empty
Dim startNumber As Integer
Dim endNumber As Integer
startNumber = Asc(startingStr)
endNumber = Asc(endStr)
Dim TempStr As String = Mid(TextBox1.Text, 1, TextBox1.Text.Length - 1)
Dim i As Integer
For i = startNumber To endNumber
outputstr = outputstr + ", " + TempStr + Chr(i)
Next i
MsgBox(outputstr)
The First two lines will take out the Last Character of the String in the text box.
So in your case it will get A and D respectively
Then outputstr to create the series which we will use in the loop
StartNumber and EndNumber will be give the Ascii values for the character we fetched.
TempStr to Store the string which is left off of the series string like in our case AAA - AAD Tempstr will have AA
then the simple loop to get all the items fixed and show
in your case to achive goal you may do something like this
Dim S() As String = {"AAA", "AAB", "AAC", "AAD"}
For Each el In S
MsgBox(el.ToString)
Next
FIX FOR PREVIOUS ISSUE
Dim s1 As String = "AAA"
Dim s2 As String = "AAZ"
Dim Last As String = s1.Last
Dim LastS2 As String = s2.Last
Dim StartBase As String = s1.Substring(0, 2)
Dim result As String = String.Empty
For I As Integer = Asc(s1.Last) To Asc(s2.Last)
Dim zz As String = StartBase & Chr(I)
result += zz & vbCrLf
zz = Nothing
MsgBox(result)
Next
**UPDATE CODE VERSION**
Dim BARCODEBASE As String = "SBA0021"
Dim BarCode1 As String = "SBA0021AA1"
Dim BarCode2 As String = "SBA0021CD9"
'return AA1
Dim FirstBarCodeSuffix As String = Replace(BarCode1, BARCODEBASE, "")
'return CD9
Dim SecondBarCodeSuffix As String = Replace(BarCode2, BARCODEBASE, "")
Dim InternalSecondBarCodeSuffix = SecondBarCodeSuffix.Substring(1, 1)
Dim IsTaskCompleted As Boolean = False
For First As Integer = Asc(FirstBarCodeSuffix.First) To Asc(SecondBarCodeSuffix)
If IsTaskCompleted = True Then Exit For
For Second As Integer = Asc(FirstBarCodeSuffix.First) To Asc(InternalSecondBarCodeSuffix)
For Third As Integer = 1 To 9
Dim tmp = Chr(First) & Chr(Second) & Third
Console.WriteLine(BARCODEBASE & tmp)
If tmp = SecondBarCodeSuffix Then
IsTaskCompleted = True
End If
Next
Next
Next
Console.WriteLine("Completed")
Console.Read()
Take a look into this check it and let me know if it can help

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

Help with using an array to insert items into a textbox vb.net

I'm still a student without much experience using vb.net and I am having some trouble splitting a string within an array into 2 values. For example in my textbox I have several lines of measurements that are Length x Width: 20x14, 10x8, 16x13. Each measurement is on its own line. I'm trying to split all Width values that are greater than 12 into 2 separate measurements, so with that last example, I would have 5 measurements (LxW): 20x12, 20x2, 10x8, 16x12, 16x1, then I would like to add these measurements to a new textbox with each measurement on its own line.
Here is the code I have so far. Again, I am very new to programming and this is the first serious project for me since "Hello World", so what I have might be way off. Thanks in advance.
Dim room As String = RoomsTextBox.Text
If room.EndsWith(vbCrLf) Then room = room.Substring(0, room.Length - vbCrLf.Length)
Dim roomarray() As String = room.Split(vbCrLf)
Dim Cuts(roomarray.Length - 1, 0) As String
RoomsTextBox.Select(0, 0)
Dim CutLength As Integer
Dim CutWidth As Integer
Dim i As Integer
Dim j As Integer
CutsTextBox.Select()
Cuts(i, j) = (Val(roomarray(i).Split("x")(0))) & Val(roomarray(j).Split("x")(1))
For i = 0 To Cuts.GetUpperBound(0)
For j = 0 To Cuts.GetUpperBound(1)
Cuts(i, j) = 0
Next
If Val(roomarray(i)) > 12 Then
CutWidth = Val(roomarray(i)) - 12
CutLength = Val(roomarray(j))
Else
CutWidth = Val(roomarray(i))
CutLength = Val(roomarray(j))
End If
Dim inserttext = CutsTextBox.Text
Dim insertposition As Integer = CutsTextBox.SelectionStart
CutsTextBox.Text = CutsTextBox.Text.Insert(0, CutLength.ToString & "x" & _
CutWidth.ToString)
CutsTextBox.SelectionStart = insertposition + inserttext.Length
Next i
I even tried it with inserting the measurements into a ListBox. Here is the code for that:
Dim room As String = RoomsTextBox.Text
Dim roomarray() As String = room.Split(vbCrLf)
Dim Cuts(roomarray.Length - 1, 0) As String
Dim CutLength As Integer
Dim CutWidth As Integer
Dim i As Integer
Dim j As Integer
CutsTextBox.Select()
Cuts(i, j) = (Val(roomarray(i).Split("x")(0))) & Val(roomarray(j).Split("x")(1))
For i = 0 To Cuts.GetUpperBound(0)
For j = 0 To Cuts.GetUpperBound(1)
Cuts(i, j) = 0
Next
If Val(roomarray(i)) > 12 Then
CutWidth = Val(roomarray(i)) - 12
CutLength = Val(roomarray(j))
Else
CutWidth = Val(roomarray(i))
CutLength = Val(roomarray(j))
End If
ListBox1.Items.Add(CutLength.ToString & "x" & CutWidth.ToString)
Next i
Try this out.
Dim dimensions As String() = txtInput.Text.Split(vbCrLf)
Dim final As New List(Of String)
For Each item In dimensions
Dim lw As String() = item.Split("x")
Dim length As String = lw(0)
Dim width As Integer = CInt(lw(1))
If width > 12 Then
Dim new1 As String
Dim new2 As String
new1 = length & "x" & (width - 12).ToString
new2 = length & "x12"
final.Add(new1)
final.Add(new2)
Else
final.Add(item)
End If
Next
For Each item In final
txtOutPut.Text += item & vbCrLf
Next