How can i subtract number from IP address in vb.net - vb.net

I have a small question here , I have two Textboxes in VB.Net.
Textbox1 value will be entered by user. for example Textbox1 = 10.200.1.1
I want to auto subtract 100 from the 2nd octet and put the value in Textbox2
Textbox2 = 10.100.1.1
Is that doable in VB.Net?

You can use the IPAddress class of .NET to solve this:
Dim ip As System.Net.IPAddress = Nothing
'parse the IP address from user input to make sure the input is valid and check for IPv4.
If System.Net.IPAddress.TryParse(TextBox1.Text, ip) AndAlso ip.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then
Dim ipBytes() As Byte = ip.GetAddressBytes
'just subtract 100 on the 2nd octet if higher or equals 100.
If ipBytes(1) >= 100 Then
ipBytes(1) = ipBytes(1) - 100
End If
'create the new IP address from modified octets.
ip = New System.Net.IPAddress(ipBytes)
TextBox2.Text = ip.ToString()
End If

Let's split on period, then convert the second to integer, and reduce it by 100, convert it back to a string, and recombine the parts into a whole:
Dim ip = ip1TextBox.Text;
Dim bits = ip.Split("."c)
Dim octet2 = Convert.ToInt32(bits(1))
octet2 -= 100
bits(1) = octet2.ToString()
Dim newIp = string.Join(".", bits)

Related

increment alphanumeric string where alphabet position in a string is keeps changing

I need to save Multiple(about 20-25) serial number of the specimen in my application. Sometimes serial number will be alphanumeric but will be sequential. I need a way out to increment alphanumeric serial numbers based on the first serial number entered.
My main problem is alphabet position and alphabet count keeps changing. Example : 10MG2015 20562MG0 MGX02526 etc etc
I tried but mine works when Alphabet are in starting position and when there are known number of alphabets. Here is my try
Dim intValue as integer
Dim serialno as string
Dim serialno1 as string
For i =0 to 20
Serialno1 = serialno.Substring(3)
Int32.TryParse(Serialno1, intValue)
intValue = intValue + 1
checkedox1.items.add(serialno.Substring(0,3) + intValue.ToString("D3"))
NEXT
Any help is highly appreciated. Thanks in advance
edit 1
Clarity : I want to increment alphanumeric string. Example : If first entered one is 10MG2015 then I should increment to 10MG2016, 10MG2017, 10MG2018, 10MG2019 and so on... For 20562MG0 it will be 20562MG1, 20562MG2 20562MG3 and so on...
Function FindSequenceNumber(SerialNumber As String) As Integer
'Look for at least four digits in a row, and capture all the digits
Dim sequenceExpr As New Regex("([0-9]{4,11})")
Dim result As Integer = -1
Dim m As Match = sequenceExpr.Match(SerialNumber)
If m.Success AndAlso Integer.TryParse(m.Groups(1).Value, result) Then
Return result
Else
'Throw exception, return -1, etc
End If
End Function
See it here:
https://dotnetfiddle.net/gO2nue
Note: the integer type doesn't preserve leading zeros. You may find it better to return a tuple with either the length of the original string, so you can pad zeros to the left if needed to match the original formatting.
Or maybe this:
Function IncrementSerial(SerialNumber As String) As String
'Look for at least four digits in a row, and capture all the digits
Dim sequenceExpr As New Regex("([0-9]{4,11})")
Dim m As Match = sequenceExpr.Match(SerialNumber)
If Not m.Success Then Throw New Exception("No sequence number found")
Dim c = m.Groups(1).Captures(0)
Dim seq = (Integer.Parse(c.Value) + 1).ToString()
If seq.Length < c.Value.Length Then
seq = seq.PadLeft(c.Value.Length, "0"c)
End If
Dim result As String = ""
If c.Index > 0 Then result & = SerialNumber.Substring(0, c.Index)
result &= seq
If c.Index + seq.Length < SerialNumber.Length Then result &= SerialNumber.SubString(c.Index + seq.Length)
Return result
End Function

How to convert textbox year date value to check if it has only 2 digits?

The problem that I have is related to only being possible to insert 2 digit's on the field year and I was wondering if it was possible to have a string with a value 2017 and only inserting 17 when I press a button.
I have tried to use the CONTAINS property to check if it only has numbers, but now I'm kind of stuck.
You could use regex.
Private Function returnLastTwo(input As Integer) As Integer
Dim matchYearString As String = "(?:(\d\d)(?:(\d\d))?)"
Dim output As Integer
If CStr(input).Length = 4 Then
output = Text.RegularExpressions.Regex.Match(CStr(input), matchYearString).Groups(2).Value
ElseIf CStr(input).Length = 2 Then
output = Text.RegularExpressions.Regex.Match(CStr(input), matchYearString).Groups(1).Value
Else
Throw New Exception("Check input")
End If
Return output
End Function
You can use a string/substring concept;
Module DateSplit
Sub Main()
Dim literal As String = "2017"
Dim substring As String = literal.Substring(2)
Console.WriteLine("Substring: {0}", substring)
End Sub
End Module
I did not test this code but should output 17
Another approach would be casting your date as a string and create a char array, then you can have access to the element and convert them back to numbers if you like
Dim dateToSplit As Integer = 2017
Dim strDate As String = dateToSplit.ToString()
Dim charArr() AS Char = strDate.ToCharArray()
Assuming your user enters a date like this: 01/01/2017, into the textbox:
dim dateFromTextbox = yourTextbox.Text ' ==> 01/01/2017
dim lastTwoDigits = Right(dateFromTextbox, 2) ' ==> 17

Add TextBox strings as numbers

I'm making a counter that updates when the calculate button is pressed, but when I press it it add it like:
11111
where the answer should be 5.
Const tax = 1.05
Dim capPrice = 4.0
Dim espPrice = 2.5
Dim latPrice = 3.5
Dim icedPrice = 3.0
'keeping here teporarily
Dim takeAway = True
If (takeAway = True) Then
capCounter.text = capCounter.text + capAmount.text
espCounter.Text = espCounter.Text + espAmount.Text
latCounter.Text = latCounter.Text + latAmount.Text
icedCounter.Text = icedCounter.Text + icedAmount.Text
What you observe is string concatenation because a TextBox stores strings. You have to convert it to a number, for example with Int32.Parse, then you can sum the values:
Dim capCount As Int32
Dim capAmount as Int32
Dim validCapCount = Int32.TryParse(capCounter.Text, capCount)
Dim validCapAmount = Int32.TryParse(capAmount.Text, capAmount)
If validCapCount AndAlso validCapAmount Then
capCounter.Text = (capCount + capAmount).ToString()
End If
' do the same with the other values ...
This is because the Property Text of a control is a String.
If you want to perform your addition, you must convert those texts to a Integer first :
capCounter.text = (CType(capCounter.text, Integer) + CType(capAmount.text, Integer)).ToString()
(This if you are sure it will only be integers contained in the texts)
If you will use it for numbers only and allow user imput I will recommend you to use a numericUpDown and not a textboxt.
Then you can use the Value property of the numericupdown and it will return a numeric value, not a String.
However, if you need it to be a textbox, use CType as SuperPeanut sugested or TryParse as Tim sugested
Most of the other comments explain most of it, but have you tried using a different type of control to display the information, perhaps a NumericUpDownControl?

VB.NET add a decimal Point to Series

The following Function creates multiple series for a graph.
Function createSeries(ByVal fileNames() As String, ByVal intValXAxis As Integer, ByVal intValYAxis As Integer) As Series()
Dim ChartSeries(fileNames.Count) As Series
Dim i As Integer = 0
For Each filename In fileNames
ChartSeries(i) = New Series
ChartSeries(i).ChartType = SeriesChartType.FastLine
ChartSeries(i).ChartArea = "ChartArea1"
If filename.Contains("NOK") = True Then
ChartSeries(i).Color = Color.Red
ChartSeries(i).BorderWidth = 3
Else
ChartSeries(i).Color = Color.Green
End If
Dim fileReader = My.Computer.FileSystem.OpenTextFileReader(filename)
Do
Dim strCache() As String = Split(fileReader.ReadLine(), ";")
ChartSeries(i).Points.AddXY(strCache(intValXAxis - 1), strCache(intValYAxis - 1))
ChartSeries(i).ToolTip = filename
Loop Until fileReader.EndOfStream = True
i += 1
Next
Return ChartSeries
End Function
The problem I have is, that the Y-Values of the Series I create are mostly something like that: 0,09440104 or 0,1757813. I need these Values shown on the graph as they are, but the zero's got removed and the Y-Point-Values are : 9440104 or 1757813
I tried to format them with "Globalization" before adding them to the Series, but it doesn't solved the problem.
Just to be clear: I want the numbers as shown above(0,09440104 and 0,1757813) to be the Y-values of the points.
How can i solve the problem?
Thanks in advance.
By default, En-US culture will read your comma "," as thousand separator and thus taking your data as > 0 rather than < 0.
You have two options: change the culture or change the string format. If all your numbers are less than 1000 (or, to be more precise, not having . as thousand separator), I recommend simply to replace , with .
Dim strCache() As String = Split(fileReader.ReadLine(), ";")
Dim repStrX = strCache(intValXAxis - 1).Replace(",",".")
Dim repStrY = strCache(intValYAxis - 1).Replace(",",".")
ChartSeries(i).Points.AddXY(repStrX , repStrY)
Or, if they are having value more than 1000 (or, again, to be more precise, not having . as thousand separator), without specifying the culture, you could also use Replace with some tricks: making use of non-existing character as intermediate value to flip between . and , in the original string.
Dim strCache() As String = Split(fileReader.ReadLine(), ";")
Dim repStrX = strCache(intValXAxis - 1).Replace(",","G").Replace(".",",").Replace("G",".")
Dim repStrY = strCache(intValYAxis - 1).Replace(",","G").Replace(".",",").Replace("G",".")
ChartSeries(i).Points.AddXY(repStrX , repStrY)

generate numbers between set values vb.net

I am creating a program to generate numbers between a list of values.
Problem I am having is if the first number stats with a smaller value than the second value it will create an error, such as 1000 and 32 will say it doesnt work, or 532 and 64
I do not understand why or how to fix it
Private Sub Generate_Click(sender As System.Object,
e As System.EventArgs) Handles Generate.Click
'Displays to enter correct information if lower is <=
If Upper.Text <= Lower.Text Or Lower.Text >= Upper.Text Then
List.Items.Clear()
List.Items.Add("Please enter correct info Upper # higher value than Lower #")
Else
'If Upper range is higher than lower range then display numbers until total value is displayed
List.Items.Clear()
Number.Text = ""
Dim i As Integer = Lower.Text
Do While i <= Upper.Text 'Loop generates the numbers between values specified
List.Items.Add(i)
i += 1
Loop
'Select a random value from the list generated
Dim myRandom As New Random
Dim b As Integer = List.Items.Count
Dim chosenItem As System.Object = List.Items.Item(myRandom.Next(b))
Number.Text = chosenItem.ToString
End If
End Sub
Basically you have to compare numeric value you are comparing string so it is happening.
And 'or' condition is not required in if statement so omit it.
please replace you code as follows.
if System.Convert.ToInt32(Upper.Text) <= System.Convert.ToInt32(Lower.Text) Then
List.Items.Clear()
List.Items.Add("Please enter correct info Upper # higher value than Lower #")
Else
List.Items.Clear()
Number.Text = ""
Dim i As Integer = Lower.Text
Do While i <= System.Convert.ToInt32(Upper.Text) 'Loop generates the numbers between values specified
List.Items.Add(i)
i += 1
Loop
'Select a random value from the list generated
Dim myRandom As New Random
Dim b As Integer = List.Items.Count
Dim chosenItem As System.Object = List.Items.Item(myRandom.Next(b))
Number.Text = chosenItem.ToString
End If
With the If clause, you are doing a string comparison on numerical values. You need to cast them to integer values. And you are doing the same comparison twice which is unnecessary. Also there is a simpler way of generating random numbers between two integers.
I would encourage you to code with the "Option Strict On" declaration at the top of the page. The compiler will alert you when you attempt to make implicit conversions of which there are several in your code.
Dim iMinimum As Integer = Integer.Parse(Lower.Text)
Dim iMaximum As Integer = Integer.Parse(Upper.Text)
If iMaximum <= iMinimum Then
Number.Text = "Please enter correct info Upper # higher value than Lower #"
Else
Dim randomObject As Random = New Random
Number.Text = randomObject.Next(iMinimum, iMaximum).ToString
End If