Generate Unique Sequence - vb.net

I have 8 different single digit variable with either 0 or 1 value.
I need to create concurrent string by placing together all those 8 digit to create an unique sequence variable and then need to add all those unique sequence variable in a list or array.
for an example;
each of sequence will be like 00000000 or 11111111 or 01010101 or 01101100
trying to find the better way to write a function to genrate all unique sequnces.
What I tried...
Imports System.IO
Imports System.Net
Imports Newtonsoft.Json
Imports AlphaSequence.My
Imports Newtonsoft.Json.Linq
Imports System.Windows.Forms
Imports Microsoft.VisualBasic.CompilerServices
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim str As String = Nothing
Dim obj As JArray = Me.GetSequence(Me.NumericUpDown1.Value)
Debug.Print(obj.ToString)
End Sub
Friend Function GetSequence(ByVal face As Integer) As JArray
Dim Seq As JArray = New JArray
Dim str As String = Nothing
Dim data As String = Nothing
For a = 0 To 1
str = ""
For i = 0 To face
str = str & a
Next
Seq.Add(str)
Next
Return Seq
End Function
End Class
I am missing something, this loop is not right and not generating value as expected, Can any one help me to write a better code to get expected result ?

Related

How do I optimize my code - vb.net

I have a working program, but it's like Frankenstein - parts of other programs put together, that may be redundant. Here's what I'm trying to do:
Find a string inside a binary file & from that location to the EOF dump the contents into a string.
Here is my code:
Imports System.IO
Public Class Form1
Dim b() As Byte = IO.File.ReadAllBytes("C:\data.bin")
Dim encodme As New System.Text.ASCIIEncoding
Dim SearchString As String = "xyzzy"
Dim bSearch As Byte() = encodme.GetBytes(SearchString)
Dim bFound As Boolean = True
Dim oneByte As Byte
Dim fileData As New IO.FileStream("C:\data.bin", FileMode.Open, FileAccess.Read)
Dim strMessage As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For i As Integer = 0 To b.Length - bSearch.Length - 1
If b(i) = bSearch(0) Then
bFound = True
For j As Integer = 0 To bSearch.Length - 1
If b(i + j) <> bSearch(j) Then
bFound = False
Exit For
End If
Next
If bFound Then
fileData.Seek(i + 5, SeekOrigin.Begin)
strMessage = ""
For r As Integer = (i + 5) To fileData.Length() - 1
oneByte = fileData.ReadByte()
strMessage = strMessage + Chr(oneByte)
Next r
MsgBox(strMessage)
Else
MsgBox("File Doesn't have string")
Exit Sub
End If
End If
Next
End Sub
End Class
When looking for performance, it is best to avoid trying to walk through this kind of thing byte by byte. Instead you should use the facilities .NET provides you with. This example uses RegEx to find all matches of a string in any file, returning each match with everything that follows it until the next match or the end of the file in a UTF-8 string:
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim matches = FindStringMatchesInFile("C:\Infinite Air\snowboarding.exe", "data")
For Each m In matches
...
Next
End Sub
Private Function FindStringMatchesInFile(filename As String,
searchString As String) As List(Of String)
Dim output As New List(Of String)
Dim reader = New StreamReader(filename, Encoding.UTF8)
Dim re = New Regex(String.Format("{0}(?:(?!{0}).)*", searchString),
RegexOptions.Singleline Or RegexOptions.IgnoreCase,
Regex.InfiniteMatchTimeout)
Dim matches = re.Matches(reader.ReadToEnd())
For Each m As Match In matches
output.Add(m.ToString())
Next
Return output
End Function
End Class
The RegEx pattern definition is the following:
Matches the characters {searchString} literally (case insensitive)
Non-capturing group (?:(?!{searchString}).)*
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Negative Lookahead (?!{searchString})
Assert that the Regex below does not match
Matches the characters {searchString} literally (case insensitive)
. matches any character
Global pattern flags
g modifier: global. All matches (don't return after first match)
s modifier: single line. Dot matches newline characters
i modifier: case insensitive.

Trying to write IP address to textbox in Visual Basic

I am trying to write a simple program that finds the public IP for the computer it is being used on. However, I am not sure how to set the text of the TextBox to the IP address that is found. Can anyone help me?
Code:
Imports System.Net
Imports System.Text
Imports System.Text.RegularExpressions
Public Class Form1
Private Function GetMyIP() As IPAddress
Using wc As New WebClient
Return IPAddress.Parse(Encoding.ASCII.GetString(wc.DownloadData("http://tools.feron.it/php/ip.php")))
End Using
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = (GetMyIP())
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs)
End Sub
End Class
First, you should use Option Strict On. That would point out to you that you need to use
TextBox1.Text = GetMyIP().ToString()
Next, if you examine the headers from that web page you will see it returns the result in UTF-8 encoding, so you should use Encoding.UTF8 instead of Encoding.ASCII. Unfortunately, that still does not work - I will write more on that later.
However, WebClient has a DownloadString method which works well in this case:
Private Function GetMyIP() As IPAddress
Using wc As New WebClient
Dim url = "http://tools.feron.it/php/ip.php"
Dim x = wc.DownloadString(url)
Return IPAddress.Parse(x.Trim())
End Using
End Function
If you still want to use DownloadData, you should examine the returned bytes: you would find that the data you want is preceded by the bytes 0xEF 0xBB 0xBF. I do not know why. This is messing up the string that you want if you download it as an array of bytes.
You could use LINQ to remove the strange bytes:
Private Function GetMyIP() As IPAddress
Using wc As New WebClient
Dim url = "http://tools.feron.it/php/ip.php"
Dim x = wc.DownloadData(url)
Dim y = Encoding.UTF8.GetString(x.Where(Function(b) b < 128).ToArray())
Return IPAddress.Parse(y)
End Using
End Function
(I could have used Encoding.ASCII in there because the bytes over 127 have been removed.)

End of statement expected. - VB Code to WebService Error

I'm getting this error when trying to debug my VB code in Visual Studio to interact with a specific WebService .
Im not very familiar with Visual Basic.
The error is on the line Dim ticket_handle As String = " CR 1001 " ws.closeTicket ( Sid , " closed ticket " ticket_handle )
The complete code:
Imports System.IO Imports System.Xml
Imports System.Xml.Serialization
Imports WebReference
Partial Class _Default
Inherits System.Web.UI.Page
Dim ws As New USD_WebService
Dim sid As String
Dim userhandle, username, password As String
Dim attrVal(5), attr(0), prop(0) As String
Dim requestHandle, requestNumber As String
Dim persistent_id As String
Dim catAttrib(5) As String
Sub Main()
Dim ws As New USD_WebService
ws.Url = "http://hummer:8080/axis/services/USD_R11_WebService?wsdl"
Dim username, password
Dim sid
username = "servicedesk"
password = "password"
sid = ws.login(username, password)
Dim userhandle
userhandle = ws.getHandleForUserid(sid, username)
Dim USD As New WebReference.USD_WebService
sid = USD.login(username, password)
Dim ticket_handle As String = “cr:1001” ws.closeTicket(Sid,“ticket fechado”, ticket_handle)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ws.Url = "http://hummer:8080/axis/services/USD_R11_WebService?wsdl"
End Sub
End Class
Can anyone help me plis?!?!
In VB.NET, only one statement may be executed per line. Other languages, like Java or C# use a ';' to denote the end of a statement, however in VB.NET it is the end of a line. The compiler is trying to tell you that you have two statements on a single line and it expects there to only be one.
Dim ticket_handle As String = “cr:1001” ws.closeTicket(Sid,“ticket fechado”, ticket_handle)
Should be
Dim ticket_handle As String = “cr:1001”
ws.closeTicket(Sid,“ticket fechado”, ticket_handle)

Selecting variable by name

I'm not sure of the appropriate search term so please close and point me to a duplicate if that's the case.
I have a structure with has multiple variables. I've created an array of the type of the structure. I've added data to a few indexes of the array. I now want to select the a specific variable based on the name of the variable.
He's an example of the structure:
structure struc
dim name as string
dim lvl as integer
dim capacity as integer
end structure
And the deceleration of the array:
dim vills(3) as struc
You should be using public fields, not variables Actually you have the terminology correct according to MSDN, the only thing you are missing is the access modifier i.e.
Public Structure Struc
Public Name As String
Public Lvl As Integer
Public Capacity As Integer
End Structure
At the moment your variables are private which means they aren't accessible from outside your Structure.
Looking at your comments it looks like you are trying to access the property by name dynamically rather than knowing it at compile time. There are a few ways of doing this, most of which involve some Reflection.
You should perhaps have a look at ExpandObject - it's effectively a key/value dictionary with the characteristics of a normal class-type object so you get the best of both worlds e.g.
Dim struct As Object = New ExpandoObject()
struct.name = "SomeValue"
struct.lvl = 3
struct.capacity = 100
Console.WriteLine(struct["name"])
Console.WriteLine(struct["lvl"])
As Tony Hopkinson mentioned, it is possible via Reflection:
Public Class Form1
Structure struc
Dim name As String
Dim lvl As Integer
Dim capacity As Integer
End Structure
Dim vills(3) As struc
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i As Integer = 0 To vills.Length - 1
vills(i).lvl = i * 10
Next
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim fi As Reflection.FieldInfo
Dim fieldName As String = "lvl"
For i As Integer = 0 To vills.Length - 1
fi = vills(i).GetType.GetField(fieldName, Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Public)
If Not IsNothing(fi) Then
Dim value As Object = fi.GetValue(vills(i))
Debug.Print(i & ": " & value.ToString)
End If
Next
End Sub
End Class
Up to you to decide if it's worth it...
I really think that if this is an important and frequent requirement (find an element by key) then you should think twice and change your array to a Dictionary(Of string, struc) and use something like this
Dim vills = new Dictionary(of String, struc)
Dim s = new struc()
s.name="k1"
s.lvl=1
s.capacity=1
z.Add(s.name, s)
....
struc c = vills("k1")
if(c IsNot Nothing) Then
Console.WriteLine(c.lvl.ToString())
End If
but if you still want to use an array you could search your struc array by name using Linq
Structure struc
Public Dim name as string
Public Dim lvl as integer
Public Dim capacity as integer
End Structure
Sub Main
Dim vills(3) as struc
....
Dim c as struc = wills.Where(Function(x) (x.name="keyName")).Single()
if(c.name IsNot Nothing) then
Console.WriteLine("Found")
End If
End Sub

Using .Net XmlSerialize for strings with embedded <cr><lf> loses <cr> when deserializing

The following (abysmal) code demonstrates how standard serialize/de-serialize in VB loses the CR when on de-serialize. This can be overcome by applying 'XmlAttribute(DataType:="string")' to Description. Why does it do this? I would like to fix this without applying a 'LF' -> 'CR''LF' in every affected class. This is fixing a bug in existing XML files generated without the XmlAttribute!
Imports System.Xml.Serialization
Imports System.Xml
Imports System.IO
Public Class Form1
Public Class MyObject
Public Description As String
End Class
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim x As New MyObject
x.Description = "Hello" + vbCrLf + "World"
Dim serializer As New XmlSerializer(GetType(MyObject))
Dim writer As StreamWriter = New StreamWriter("c:\temp\test.xml")
serializer.Serialize(writer, x)
writer.Close()
For i As Integer = 0 To x.Description.ToCharArray.Length - 1
Debug.Print(Asc(x.Description.ToCharArray(i, 1)))
Next
Debug.Print("**********************")
Dim reader As New StreamReader("c:\temp\test.xml")
Dim newObj As MyObject = CType(serializer.Deserialize(reader), MyObject)
For i As Integer = 0 To newObj.Description.ToCharArray.Length - 1
Debug.Print(Asc(newObj.Description.ToCharArray(i, 1)))
Next
End Sub
End Class
Take a look at XML deserialization 'standardising' line endings, how to stop it? (.NET). Does that soluton match what you're trying to do?