Why does the value type declared in this loop keeps the value from the previous iteration? - vb.net

First time posting a question here. Sorry if the title needs work. :)
Consider the following code (not the original code, but a simplified version):
Imports System.Threading.Tasks
Module Module1
Sub Main()
' just a sample array to loop in parallel.forEach.
' the sample parallel loop does not consume for this demonstration.
Dim things() As String = {"thing1", "thing2"}
Dim parallelLoopBody = Sub(s As String)
For i As Integer = 1 To 10
Dim j As Integer
For k As Integer = 1 To 10
j += (k * i)
Next
Console.WriteLine(j)
Next
End Sub
' when debugging the original code I set max 1 for easier debugging purposes
Dim po As New ParallelOptions With {.MaxDegreeOfParallelism = 1}
Parallel.ForEach(things, po, parallelLoopBody)
End Sub
End Module
This should produce the following output, as written above:
55
165
330
550
825
1155
1540
1980
2475
3025
55
165
330
550
825
1155
1540
1980
2475
3025
But when explicitly declaring j = 0 and running the code
55
110
165
220
275
330
385
440
495
550
55
110
165
220
275
330
385
440
495
550
When I stepped through the code I realized that the variable j was "keeping" the value from the last iteration of the loop.
But I would expect j to be 0 each time, because it is a value type and I am declaring it in the loop body.
I was able to get the results I expected by setting j to 0 explicitly.
Can someone explain why this happens?

Related

Using variables instead of values

I'm having a problem with my existing code.
This code works fine,
Public Function jewel_intrate_new(ByVal duration As Integer) As String
Select Case duration
Case 0 : max2 = "0%"
Case 1 To 33 : max2 = "3.5%"
Case 34 To 63 : max2 = "9%"
Case 64 To 93 : max2 = "14.5%"
Case 94 To 123 : max2 = "20%"
Case 124 To 153 : max2 = "25.5%"
Case 154 To 183 : max2 = "31%"
Case 184 To 213 : max2 = "36.5%"
Case 214 To 243 : max2 = "42%"
Case 244 To 273 : max2 = "47.5%"
Case 274 To 303 : max2 = "53%"
Case 304 To 333 : max2 = "58.5%"
Case 334 To 363 : max2 = "64%"
Case 364 To 393 : max2 = "69.5%"
Case 394 To 423 : max2 = "75%"
Case 424 To 453 : max2 = "80.5%"
Case 454 To 483 : max2 = "86%"
Case 484 To 513 : max2 = "91.5%"
Case 514 To 543 : max2 = "97%"
Case 544 To 573 : max2 = "102.5%"
Case 574 To 603 : max2 = "108%"
Case 604 To 633 : max2 = "113.5%"
Case 634 To 663 : max2 = "119%"
Case 664 To 693 : max2 = "124.5%"
End Select
Return max2
End Function
All i want is to make my app as editable the values so i update the code as follows:
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim x As Double = 3.5 * 100, z As Integer, duration As Integer = TextBox1.Text
Dim jj As Double = 3.5
Select Case duration
Case 0
jj = 0
Case 1 To 33
jj = 3.5
Case 34 To 9999
z = (duration / 30)
For i As Integer = 1 To z
jj += 3.5 + 2 'this will be editable in database.
Next
End Select
Label1.Text = jj & "%"
End Sub
But they don't have the same output.
Is there anyway to make my function simpler and shorter?
monthly interest is 3.5%
penalty interest is 2% after 33 days
monthly is 30 days plus 3 days grace period
These results should match your Select Case but you can pass in any interest rate or penalty interest. Import System.Math. Test against your Select Case.
Private Function Calculate(ByVal Duration As Integer, InterestRate As Double, PenaltyRate As Double) As Double
Dim Rate As Double
Dim Multiplier As Integer = CInt(Math.Ceiling((Duration - 3) / 30))
Rate = Multiplier * InterestRate + PenaltyRate * (Multiplier - 1)
Return Rate
End Function

Split function for long text fails with VALUE! error

I am using a function that i saw here on Stackoverflow:
Function EXTRACTELEMENT(Txt, n, Separator) As String
EXTRACTELEMENT = Split(Application.Trim(Txt), Separator)(n - 1)
End Function
It was spliting an array of data, like this:
sRN LMDscandata sRA LMDscandata 1 1 F97BBF 0 0 6D2A 6D2D 71F5A0FA 71F5FD85 0 0 7 0 0 1388 168 0 1 DIST1 3F800000 00000000 D9490 1388 5 6E2 6DC 6E3 6ED 6E1 0 0 0 0 0 0
But when i tried to increase the amount of data:
sRN LMDscandata sRA LMDscandata 1 1 F97BBF 0 0 FCDF FCE2 9DC90606 9DC9637B 0 0 7 0 0 1388 168 0 1 DIST1 3F800000 00000000 C3500 1388 3D 525 50B 518 508 51D 50A 51A 502 514 50F 502 51C 50E 51C 50E 4FF 509 505 50B 4F9 505 51B 513 516 501 50F 509 4FE 505 508 50C 507 50C 50E 51A 511 514 528 511 519 524 52E 526 522 524 535 534 52E 527 52F 52E 53D 52F 550 535 547 548 559 551 557 558 0 0 0 0 0 0
An error is occuring and the VBA returns an error window and no data is split. How can I fix it?
This is the full code, I am coding it to test a sensor output, where I receive some important data in hex & ascii and then transform to dec and make some graphs. This is the function that convert the values.
If someone can also give some tips on the Sub, I would appreciate it.
Sub ler()
Dim ncell
Dim vArr, col
Dim counter, elem_end As Integer
Dim rng1, rng2 As String
Set ascii = ThisWorkbook.Worksheets("ASCII")
Set medidas = ThisWorkbook.Worksheets("Medidas")
'Valor da última linha preenchida da coluna A'
ncell = ascii.Range("A65536").End(xlUp).Row
'Número de elementos'
elem_end = ascii.Range("B" & ncell).Value
For counter = 1 To elem_end
counterplus = counter + 2
vArr = Split(Cells(1, counterplus).Address(True, False), "$")
Col_Letter = vArr(0)
col = Col_Letter
Let rng1 = col & ncell
Let rng2 = "A" & ncell
ascii.Range(rng1).NumberFormat = "#"
ele = EXTRACTELEMENT(ascii.Range(rng2), counter, " ")
ascii.Range(rng1).FormulaR1C1 = ele
Next
With ascii.Range(Cells(ncell, 1), Cells(ncell, counterplus))
Set dist = .Find("DIST1", LookIn:=xlValues)
If Not dist Is Nothing Then
firstAddress = dist.Address
Do
dist1 = firstAddress
Set dist = .FindNext(dist)
Loop While Not dist Is Nothing And dist.Address <> firstAddress
End If
End With
data_col = ascii.Range(dist1).Column + 5
data_num = ascii.Cells(ncell, data_col).Value
dec_num = CLng("&H" & data_num)
medidas.Range("A" & ncell).Value = dec_num
For counter2 = 1 To data_num
asc_value = ascii.Cells(ncell, data_col + counter2).Value
Dec = CLng("&H" & asc_value)
medidas.Cells(ncell, counter2 + 1).Value = Dec
Next
End Sub
In Column B, there is a function that calculates the number of elements of the data in column A
You need to declare the variables, you are getting a Type mismatch, at least the first needs to be declared.
Function EXTRACTELEMENT(Txt As String, n As Long, Separator As String) As String
EXTRACTELEMENT = Split(Application.Trim(Txt), Separator)(n - 1)
End Function

Converting byte[] to object in vb.net

I have a byte array, for example:
Dim byteArray(10) as Byte
byteArray(0) = 1
byteArray(1) = 2
byteArray(2) = 3
...
byteArray(9) = 10
and I am trying to convert it into an object but without success. I have read a lot of posts here about on how to do it so I have below function:
Public Shared Function ByteArrayToObject(ByVal arrBytes As Byte()) As Object
Using ms As New MemoryStream()
Dim binForm As New BinaryFormatter()
ms.Write(arrBytes, 0, arrBytes.Length)
ms.Seek(0, SeekOrigin.Begin)
Dim obj As Object = DirectCast(binForm.Deserialize(ms), Object)
Return obj
End Using
End Function
but when performing the DirectCast I am getting an exception saying, more or less (translated from spanish):
"SerializationException was unhandled: End of sequence reached before terminating analysis".
Any idea why is it happening?
You have an array of bytes:
Dim byteArray(10) as Byte
byteArray(0) = 1
byteArray(1) = 2
byteArray(2) = 3
...
byteArray(9) = 10
Which is this byte stream:
1 2 3 4 5 6 7 8 9 10
But you don't have a serialized object. Which is what your code assumes:
Dim obj As Object = DirectCast(binForm.Deserialize(ms), Object)
That stream can't be de-serialized into an instance of Object because, well, it isn't a serialized instance of Object. But this is (or at least is on my machine in my test):
0 1 0 0 0 255 255 255 255 1 0 0 0 0 0 0 0 4 1 0 0 0 13 83 121 115 116 101 109 46 79 98 106 101 99 116 0 0 0 0 11
Basically, you can't just de-serialize anything into an instance of an object. It has to be an actual serialized version of that object.

Convert big string to decimal in vb.net

Hello i have big string value which is md5 of something now i need to convert it into the decimal value
for example
Dim md5_s As String = "6F05AF42533432A5513610FE839ACC86"
now i need output same like the online converters to this
"54 70 48 53 65 70 52 50 53 51 51 52 51 50 65 53 53 49 51 54 49 48 70
69 56 51 57 65 67 67 56 54 "
is it possible i don't want spaces in the above converted decimal ?
vb.net help please
Okay here i tried and got it n is my approach works fine will this fine n work always right
Dim t As String
Dim a As String = "6F05AF42533432A5513610FE839ACC86"
For Each c As Char In a
t &= Convert.ToInt32(c)
Next
TextBox1.Text = t
will this one is right ?
result is same what i am looking for as
5470485365705250535151525150655353495154494870695651576567675654
so i assume this is right huh ?
I'm not quite sure this is what you are really looking for but this is what you asked for
For count = 0 To md5_s.Length - 1
Dim tempChar As String = md5_s.Substring(count, 1)
Console.Write(Asc(tempChar))
Next
What is more likely what you want is something like this
Private Function HexToByteArray(ByVal hex As [String]) As Byte()
Dim NumberChars As Integer = hex.Length
Dim bytes As Byte() = New Byte(NumberChars / 2 - 1) {}
For i As Integer = 0 To NumberChars - 1 Step 2
bytes(i / 2) = Convert.ToByte(hex.Substring(i, 2), 16)
Next
Return bytes
End Function
either way ... hope this helps

copy sets of numbers into a listbox from a textbox

I have a textbox that the user puts in sets of numbers(e.g. 32 45 98 56 52 1 23) and I need to copy these numbers into a listbox so that each number is its own item. So far I have this
For Each ch As Char In TextBox20.Text
If Char.IsDigit(ch) Then
ListBox1.Items.Add(ch)
End If
Next
but the problem is that it will copy each digit as an item so we will end up with
3
2
4
5
9
8
5
6
I need it to copy them like this
32
45
98
56
here is a sample of how to do that
Sub addToListBox()
Dim sample As String
Dim v As Variant
Dim i As Integer
sample = "32 45 98 56 52 1 23"
v = Split(sample, " ")
For i = 0 To UBound(v)
If IsNumeric(v(i)) Then
ListBox1.Items.Add(v(i))
End If
Next i
End Sub