How to increment number with current year + character string? - vb.net

Public Sub incrPR()
Dim curValue As Integer
Dim result As String
Dim yr As String = Now.Year.ToString()
Dim txt As String = "PR"
Using con As SqlConnection = New SqlConnection(ConString)
con.Open()
Dim cmd = New SqlCommand("Select MAX(SpecialOrderNo) FROM SpecialOrder", con)
result = cmd.ExecuteScalar().ToString
If String.IsNullOrEmpty(result) Then
result = "000"
End If
Int32.TryParse(result, curValue)
curValue += 1
result = curValue.ToString("D3") + "-" + yr + "-" + txt
txtno.Text = result
End Using
End Sub
Expected output:
001-2018-PR
002-2018-PR
003-2018-PR

The specific reason that you're not seeing the behaviour you want is here:
Int32.TryParse(result, curValue)
If result is "001-2018-PR" then TryParse will fail, i.e. return False, and that means that curValue will be zero. That means that you are going to get zero EVERY time. If you want to parse the first part of the text then do that rather than parsing the whole thing, e.g.
Int32.TryParse(result.Split("-"c)(0), curValue)
I would change things significantly but that will fix your immediate issue.

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:

Evaluate string on record table,

How to evaluate match on the record table with vb I have a code like this
Dim absenperintah As SqlCommand = New SqlCommand("Select * from mytable where kodetp ='109'", cekdata)
absenperintah.CommandType = CommandType.Text
cekdata.Open()
Dim valuex = "500"
Using cekbaca As SqlDataReader =
absenperintah.ExecuteReader(CommandBehavior.CloseConnection)
If cekbaca.Read = True Then
Dim nilxbaca = cekbaca("rumus_k") --> record in the table is 1906650*(3.7/100)
Dim nilmy = valuex + nilxbaca
Dim result = New DataTable().Compute(nilmy, Nothing)
MsgBox(result)
End If
cekbaca.Close()
End Using
cekdata.Close()
I get the result 185,070,546 it should be result =70,564.55
how to get result =70,564.55 from Dim nilHy = valuex + nilxbaca
Your problem is that you are declaring these numbers as strings and they are being calculated accordingly.
What you think you are doing:
500 + 1906650*(3.7/100) = 70,564.55
If you were processing these as numbers, it would perform math and your calculation would work.
However, you have declared these values as strings. Therefore the code is actually running like this:
"500" + "1906650*(3.7/100)" 'String concatenation. Not math.
5001906650*(3.7/100) = 185,070,546
Try this code instead:
Dim absenperintah As SqlCommand = New SqlCommand("Select * from mytable where kodetp ='109'", cekdata)
absenperintah.CommandType = CommandType.Text
cekdata.Open()
Dim valuex = "500"
Using cekbaca As SqlDataReader =
absenperintah.ExecuteReader (CommandBehavior.CloseConnection)
If cekbaca.Read = True Then
Dim nilxbaca = cekbaca("rumus_k") 'record in the table is "1906650*(3.7/100)"
Dim nilmy = valuex & " + " & nilxbaca 'makes "500 + 1906650*(3.7/100)"
'Note: your next line of code, DataTable.Compute() will evaluate a
' (string) formula over several rows.
Dim result = New DataTable().Compute(nilmy, Nothing)
'Based on this code here, you are only processing one row.
'Maybe .Compute() is totally unnecessary here.
'You would be better to say: result = 500 + nilxbaca
' or maybe declare valuex as integer, to help the compiler treat it like a number instead of a string.
' or maybe your original code did apply this formula over several rows.
' ... In that case, my example would fix your Compute() formula.
MsgBox(result)
End If
cekbaca.Close()
End Using
cekdata.Close()

Split String into Textboxes

I have this URL:
http://www.website.com/base.htm?age=<number>&Team=<number>&userID=<number>
How to get parts of this into Textboxes?
ie:
Textbox1 = number after ?age=
Textbox2 = number after &Team=
Textbox3 = number after &userID=
If you want to output to a TextBox and can guarantee a set amount of parameters this is quite simple:
Dim url As String = "http://www.website.com/base.htm?age=15&Team=3&userID=1"
TextBox1.Text = url.Split("?"c)(1).Split("&"c)(0).Split("="c)(1)
TextBox2.Text = url.Split("?"c)(1).Split("&"c)(1).Split("="c)(1)
TextBox3.Text = url.Split("?"c)(1).Split("&"c)(2).Split("="c)(1)
The code looks a little unreadable but it does the job. Note the increase in number on the second Split. This is the output:
Now what I would do is further checking to ensure the parameters are there and that they have values:
Dim url As String = "http://www.website.com/base.htm?age=15&Team=3&userID=1"
Dim parameters As String = Nothing
If url.Contains("?") Then
parameters = url.Split("?"c)(1)
End If
Dim age As Integer = 0
Dim team As Integer = 0
Dim userId As Integer = 0
If parameters IsNot Nothing Then
For Each parameter In parameters.Split("&"c)
If parameter.Contains("=") Then
If parameter.ToLower().StartsWith("age") Then
Integer.TryParse(parameter.Split("="c)(1), age)
ElseIf parameter.ToLower().StartsWith("team") Then
Integer.TryParse(parameter.Split("="c)(1), team)
ElseIf parameter.ToLower().StartsWith("userid") Then
Integer.TryParse(parameter.Split("="c)(1), userId)
End If
End If
Next
End If
TextBox1.Text = age.ToString()
TextBox2.Text = team.ToString()
TextBox3.Text = userId.ToString()
The output is the same as above but I have done further checking. I'm sure even more checking could be put in place but I think this will give you a good start.
What I like to do is store both the name and the value of the parameter using a Dictionary which can come in handy so thought I would show you this approach:
Dim url As String = "http://www.website.com/base.htm?age=<number>&Team=<number>&userID=<number>"
Dim urlParameters As New Dictionary(Of String, String)
If url.Contains("?") AndAlso url.Contains("&") Then
For Each param In url.Split("?"c)(1).Split("&"c)
Dim kp() As String = param.Split("="c)
urlParameters.Add(kp(0), kp(1))
Next
End If
'ouput
For Each parameter In urlParameters
Debug.WriteLine("Key: " & parameter.Key & " Value:" & parameter.Value)
Next
This is a screenshot of the output:
If you only want to look at the value of the parameter and output that then you could simply do this instead of adding to a Dictionary:
If url.Contains("?") AndAlso url.Contains("&") Then
For Each param In url.Split("?"c)(1).Split("&"c)
Debug.WriteLine(param.Split("="c)(1))
Next
End If
In this case the output will be:
Dim url As String = "http://www.website.com/base.htm?age=15&Team=100&userID=1109"
Dim temp As String = url.Substring(url.IndexOf("?")+1)
Dim args() As String
args = temp.Split("&")
Dim pair() As String
For Each arg As String In args
pair = arg.Split("=")
console.WriteLine(pair(0))
console.WriteLine(pair(1)) ' <--- value after =
Next

How to select a value from a comma delimited string?

I have a string that contains comma delimited text. The comma delimited text comes from an excel .csv file so there are hundreds of rows of data that are seven columns wide. An example of a row from this file is:
2012-10-01,759.05,765,756.21,761.78,3168000,761.78
I want to search through the hundreds of rows by the date in the first column. Once I find the correct row I want to extract the number in the first position of the comma delimited string so in this case I want to extract the number 759.05 and assign it to variable "Open".
My code so far is:
strURL = "http://ichart.yahoo.com/table.csv?s=" & tickerValue
strBuffer = RequestWebData(strURL)
Dim Year As String = 2012
Dim Quarter As String = Q4
If Quarter = "Q4" Then
Dim Open As Integer =
End If
Once I can narrow it down to the right row I think something like row.Split(",")(1).Trim) might work.
I've done quite a bit of research but I can't solve this on my own. Any suggestions!?!
ADDITIONAL INFORMATION:
Private Function RequestWebData(ByVal pstrURL As String) As String
Dim objWReq As WebRequest
Dim objWResp As WebResponse
Dim strBuffer As String
'Contact the website
objWReq = HttpWebRequest.Create(pstrURL)
objWResp = objWReq.GetResponse()
'Read the answer from the Web site and store it into a stream
Dim objSR As StreamReader
objSR = New StreamReader(objWResp.GetResponseStream)
strBuffer = objSR.ReadToEnd
objSR.Close()
objWResp.Close()
Return strBuffer
End Function
MORE ADDITIONAL INFORMATION:
A more complete picture of my code
Dim tickerArray() As String = {"GOOG", "V", "AAPL", "BBBY", "AMZN"}
For Each tickerValue In Form1.tickerArray
Dim strURL As String
Dim strBuffer As String
'Creates the request URL for Yahoo
strURL = "http://ichart.yahoo.com/table.csv?s=" & tickerValue
strBuffer = RequestWebData(strURL)
'Create Array
Dim lines As Array = strBuffer.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
'Add Rows to DataTable
dr = dt.NewRow()
dr("Ticker") = tickerValue
For Each columnQuarter As DataColumn In dt.Columns
Dim s As String = columnQuarter.ColumnName
If s.Contains("-") Then
Dim words As String() = s.Split("-")
Dim Year As String = words(0)
Dim Quarter As String = words(1)
Dim MyValue As String
Dim Open As Integer
If Quarter = "Q1" Then MyValue = Year & "-01-01"
If Quarter = "Q2" Then MyValue = Year & "-04-01"
If Quarter = "Q3" Then MyValue = Year & "-07-01"
If Quarter = "Q4" Then MyValue = Year & "-10-01"
For Each line In lines
Debug.WriteLine(line)
If line.Split(",")(0).Trim = MyValue Then Open = line.Split(",")(1).Trim
dr(columnQuarter) = Open
Next
End If
Next
dt.Rows.Add(dr)
Next
Right now in the For Each line in lines loop, Debug.WriteLine(line) outputs 2,131 lines:
From
Date,Open,High,Low,Close,Volume,Adj Close
2013-02-05,761.13,771.11,759.47,765.74,1870700,765.74
2013-02-04,767.69,770.47,758.27,759.02,3040500,759.02
2013-02-01,758.20,776.60,758.10,775.60,3746100,775.60
All the way to...
2004-08-19,100.00,104.06,95.96,100.34,22351900,100.34
But, what I expect is for Debug.WriteLine(line) to output one line at a time in the For Each line in lines loop. So I would expect the first output to be Date,Open,High,Low,Close,Volume,Adj Close and the next output to be 2013-02-05,761.13,771.11,759.47,765.74,1870700,765.74. I expect this to happen 2,131 times until the last output is 2004-08-19,100.00,104.06,95.96,100.34,22351900,100.34
You could loop through the lines and call String.Split to parse the columns in each line, for instance:
Dim lines() As String = strBuffer.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
For Each line As String In lines
Dim columns() As String = line.Split(","c)
Dim Year As String = columns(0)
Dim Quarter As String = columns(1)
Next
However, sometimes CSV isn't that simple. For instance, a cell in a spreadsheet could contain a comma character, in which case it would be represented in CSV like this:
example cell 1,"example, with comma",example cell 3
To make sure you're properly handling all possibilities, I'd recommend using the TextFieldParser class. For instance:
Using parser As New TextFieldParser(New StringReader(strBuffer))
parser.TextFieldType = FieldType.Delimited
parser.SetDelimiters(",")
While Not parser.EndOfData
Try
Dim columns As String() = parser.ReadFields()
Dim Year As String = columns(0)
Dim Quarter As String = columns(1)
Catch ex As MalformedLineException
' Handle the invalid formatting error
End Try
End While
End Using
I would break it up into a List(of string()) - Each row being a new entry in the list.
Then loop through the list and look at Value(0).
If Value(0) = MyValue, then Open = Value(1)
You can use String.Split and this linq query:
Dim Year As Int32 = 2012
Dim Month As Int32 = 10
Dim searchMonth = New Date(Year, Month, 1)
Dim lines = strBuffer.Split({Environment.NewLine}, StringSplitOptions.None)
Dim dt As Date
Dim open As Double
Dim opens = From line In lines
Let tokens = line.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
Where Date.TryParse(tokens(0), dt) AndAlso dt.Date = searchMonth AndAlso Double.TryParse(tokens(1), open)
If opens.Any() Then
open = Double.Parse(opens.First().tokens(1))
End If

Finding Missing numbers in a given range

So i have a problem with my codings and was wondering if anyone can help me.
Basically i'm using VB.NET and MSSQL to make a program on finding missing numbers in between a given range set by the user. The program will read from the table and give the output on a textbox. And the above codes are so far what i can come up with. But the problem is, i get wrong output and not what i want. Here's an image of the output.
Function FindingMissingNumber() As String
Dim intX As Integer = Nothing
Dim intY As Integer = Nothing
Dim strSting As String = Nothing
Dim strSqlQUery As String = Nothing
Dim cmdSqlCommand As Data.SqlClient.SqlCommand = Nothing
Dim rdrDataReader As Data.SqlClient.SqlDataReader = Nothing
'------------------------------------------------------------------------------------------------------------------------
'-> Process
'------------------------------------------------------------------------------------------------------------------------
strSqlQUery = "Select ExReportPolicyNo From DBReport Order by ExReportPolicyNo"
Dim msSqlConnection As New Data.SqlClient.SqlConnection()
'NOTE - You may need to CHECK your connection string!!! in the line below
msSqlConnection.ConnectionString = "Data Source=SISBSQL\SISBSQL;Initial Catalog=ExceptionReport;User ID=sa;Password=123;"
cmdSqlCommand = New Data.SqlClient.SqlCommand(strSqlQUery, msSqlConnection)
If cmdSqlCommand.Connection.State = Data.ConnectionState.Closed Then cmdSqlCommand.Connection.Open()
rdrDataReader = cmdSqlCommand.ExecuteReader()
If rdrDataReader.HasRows Then
Do While rdrDataReader.Read()
intX = txtRangeLeft.Text
intY = txtRangeRight.Text
'intY = rdrDataReader.GetValue(rdrDataReader.GetOrdinal("ExReportPolicyNo"))
Do While intX <> intY
intX = intX + 1
If intX <> intY Then
strSting = strSting & intX & ", " 'if it is not, then record the non sequential number into the string
Else
Exit Do
End If
Loop
Loop
End If
If cmdSqlCommand.Connection.State = Data.ConnectionState.Open Then cmdSqlCommand.Connection.Close()
'return string
Return strSting
'tidy up
intX = Nothing
intY = Nothing
strSting = Nothing
strSqlQUery = Nothing
cmdSqlCommand = Nothing
rdrDataReader = Nothing
End Function
As you can see the program loops it multiple times, and give out the wrong output. The output should read only "286118, 286120, 286121". Question is where did i went wrong?
Try this (using linq)
Change query to return rows between start and end value
Select distinct ExReportPolicyNo From DBReport
Where ExReportPolicyNo between #start and #end
Order by ExReportPolicyNo
Create List from your query:
Dim originalList as List(Of Integer)
If rdrDataReader.HasRows Then
Do While rdrDataReader.Read()
originalList.Add(rdrDataReader.GetInt(0))
Loop
End If
Create List of range from your start and end number
//Dim rangeList = Enumerable.Range(286117, 286121 - 286117 + 1).ToList()
Dim starti = Int32.Parse(txtRangeLeft.Text)
Dim endi = Int32.Parse(txtRangeRight.Text)
Dim rangeList = Enumerable.Range(starti, endi - starti + 1).ToList()
Find all missing numbers
Dim missingList = originalList.Except(rangelist)
Create CSV string from list above
strString = String.Join(",", missingList.Select(x => x.ToString()).ToArray())