Very odd issue. When trying to register a new user on the server, the server will post back messages such as "OK" and "usernameTaken". Upon comparing this returned string with another string (to perform an action based on the returned value), the compare isn't working.
Dim backupX As New CBackup
backupX.startSocket("127.0.0.1", 8888)
Dim str1 As String = backupX.registerUser("user1", "testpass")
Dim str2 As String = "usernameTaken"
If String.Equals(str1, str2) Then
MsgBox("Strings are Equal() ")
Else
MsgBox("Strings are not Equal() - " & str1 & " vs " & str2)
End If
This results in:
So what this shows is that even though the strings are equal, it sais they aren't. And the MsgBox should be saying Strings are not Equal() - usernameTaken vs usernameTaken, it left the vs usernameTaken part out completely.
What's going on here?
Extra info on CBackup class:
backupX.registerUser function:
Public Function registerUser(ByVal name As String, ByVal password As String) As String
Dim md5 As New CMD5
If name.Contains(",") Then
Return "0-commaInName"
Else
Return SocketSendAndReceiveMSG("registerUser," & name & "," & md5.GenerateStringHash(password))
End If
End Function
SocketSendAndReceiveMSG function:
Private Function SocketSendAndReceiveMSG(ByVal msg As String) As String
Return socket.sendAndReceiveMSG(msg)
End Function
socket.sendAndReceiveMSG function:
Public Function sendAndReceiveMSG(ByVal msg As String) As String
Dim serverStream As NetworkStream = clientSocket.GetStream()
sendMSG(msg & "$", serverStream)
Return receiveMSG(serverStream)
End Function
receiveMSG function
Public Function receiveMSG(ByVal serverStream As NetworkStream) As String
Dim inStream(10024) As Byte
Dim buffSize As Integer = clientSocket.ReceiveBufferSize
serverStream.Read(inStream, 0, buffSize)
Dim returndata As String = System.Text.Encoding.ASCII.GetString(inStream)
Form1.msg("Data from Server : " & returndata)
Return returndata
End Function
Looks to be like the socket code is working just fine.. each Function returns the corresponding Functions' Return value (registerUser -> SocketSendAndReceiveMSG -> sendAndReceiveMSG -> receiveMSG). I don't see how this could be messing the str1 string variable up like this..
Set a breakpoint on the line If String.Equals(str1, str2) Then and inspect both strings. Are they of the same length? Is the program stopping at your breakpoint or is another code part running?
Related
I want to make a Message, using formatting, multiple lines and adding 3 arguments. But I'm having some trouble
Public Class vbList
'Declare
Dim users As IList(Of User) = New List(Of User)()
Public Sub New()
InitializeComponent()
users.Add(New User With {
.Id = 1,
.Name = "Suresh Dasari",
.Location = "Hyderabad"
})
MsgBox("Id: {0}", users.Item(0).Id.ToString() & vbCrLf & "Name: {0}", users.Item(0).Name) & vbCrLf & "Location: {0}", users.Item(0).Location)
End Sub
I don't get this message below. Don't I need to convert the Id to a string to put it in a message?
System.InvalidCastException: 'Conversion from string "1
Name: {0}" to type 'Integer' is not valid.'
And whats up with this one, I can't have more than 2 arguments?
Too many arguments to 'Public Function MsgBox(Prompt As Object, [Buttons As MsgBoxStyle = ApplicationModal], [Title As Object = Nothing]) As MsgBoxResult'. VSBasics C:\Users\ljhha\Documents\it\vb\VSBasics\VSBasics\vbList.vb 33 Active
Use String.Format or string interpolation to insert the variables. You can insert line breaks that way too or use a multiline literal in the first place.
Dim str1 = String.Format("Date: {0}{1}Time: {2}", Date.Now.ToShortDateString(), Environment.NewLine, Date.Now.ToShortTimeString())
Dim str2 = $"Date: {Date.Now.ToShortDateString()}{Environment.NewLine}Time: {Date.Now.ToShortTimeString()}"
Dim str3 = $"Date: {Date.Now.ToShortDateString()}
Time: {Date.Now.ToShortTimeString()}"
MessageBox.Show(str1)
MessageBox.Show(str2)
MessageBox.Show(str3)
I got code for getting the first match. But the code does not get all matches. Can someone explain me how to do that? :)
Dim Start As Integer = 0, [End] As Integer = 0
If content.Contains(startString) AndAlso content.Contains(endString) Then
Start = content.IndexOf(startString, 0) + startString.Length
[End] = content.IndexOf(endString, Start)
Return content.Substring(Start, [End] - Start)
Else
Return String.Empty
End If
This works beautifuly for the first string and is easy to use. Just need to make it get a string array that i will use later (there are aprox. 5-10 strings that are always present between startString and endString).
Update:
Dim Searchstring As String
Searchstring = RichTextBox1.Text
Dim SearchStringPlus = Regex.Replace(Searchstring, "\s+", "+")
Dim SearchHTML As String
Dim WebClient1 As New Net.WebClient
SearchHTML = WebClient1.DownloadString("https://www.imdb.com/find?ref_=nv_sr_fn&q=" & SearchStringPlus & "&s=tt")
Dim SearchIndex As String = "<td class=""primary_photo""> <a href=""/title/tt"
Dim iSearch As System.IO.StreamWriter
iSearch = My.Computer.FileSystem.OpenTextFileWriter("iSearch.txt", False)
iSearch.WriteLine(SearchHTML)
iSearch.Close()
Dim SearchHTMLR As String
SearchHTMLR = IO.File.ReadAllLines("iSearch.txt").FirstOrDefault(Function(x) x.Contains(SearchIndex))
Dim titles As String
titles = GetStringBetween(SearchHTMLR, "<a href=""/title/", "/?ref_=fn_tt_tt_1")
MessageBox.Show(titles)
You can achieve this by using the Substring method.
Vb.Net
Private Function GetStringBetween(ByVal str As String, ByVal startStr As String, ByVal endStr As String) As String
Return str.Substring(startStr.Length, str.Length - (startStr.Length + endStr.Length))
End Function
C#
private string GetStringBetween(string str, string start, string end)
{
return str.Substring(start.Length, str.Length - (start.Length + end.Length));
}
Domain\X_User|X_User,Domain\Y_User|Y_User,
I'm using a SSRS report and I'm receiving the above value, I want to write visual basic function in the report ( Custom code) to split the above string and return the following value:
X_User,Y_User
I tried to write this code inside a custom code of the report body:
Public Function SubString_Owner(X As String) As String
Dim OwnerArray() As String = Split(X, ",")
Dim Names As String
Dim i As Integer = 0
While i <= OwnerArray.Length - 1
Dim NamesArr As String() = Split(OwnerArray(0), "|")
Names = NamesArr(1) + ","
i += 1
End While
Return Names
End Function
The problem is when trying to split OwnerArray(i), it gives an error but when using a fixed value, like zero, it builds fine. Can anyone figure out why this is?
Here is a more generic solution that will work with any number of items:
Dim sourceString As String = "Domain\X_User|X_User,Domain\Y_User|Y_User,"
Dim domainsAndUsers As IEnumerable(Of String) = sourceString.Split(","c).Where(Function(s) Not String.IsNullOrEmpty(s))
Dim usersWithoutDomains As IEnumerable(Of String) = domainsAndUsers.Select(Function(s) s.Remove(0, s.IndexOf("\") + 1))
Dim users As IEnumerable(Of String) = usersWithoutDomains.Select(Function(s) s.Remove(s.IndexOf("|")))
Dim result As String = users.Aggregate(Function(s, d) s & "," & d)
Or if you want it as a single-line function, here:
Function Foo(sourceString As String) As String
Return sourceString.Split(","c).Where(Function(s) Not String.IsNullOrEmpty(s)).Select(Function(s) s.Remove(0, s.IndexOf("\") + 1)).Select(Function(s) s.Remove(s.IndexOf("|"))).Aggregate(Function(s, d) s & "," & d)
End Function
EDIT:
You may have to add Imports System.Linq to the top. Not sure if SSRS can use LINQ or not. If not, then here is a similar solution without LINQ:
Dim sourceString As String = "Domain\X_User|X_User,Domain\Y_User|Y_User,"
Dim domainsAndUsers As IEnumerable(Of String) = sourceString.Split(","c)
Dim usersWithoutDomains As String = String.Empty
For Each domainUser As String In domainsAndUsers
usersWithoutDomains &= domainUser.Remove(0, domainUser.IndexOf("\") + 1) & ","
Next
Dim strTest As String = "Domain\X_User|X_User,Domain\Y_User|Y_User"
MsgBox(strTest.Split("|")(0).Split("\")(1) & " " & strTest.Split("|")(1).Split("\")(1))
Here's a simple way that will work with variable data as long as the pattern you've shown is strongly followed:
Imports System.Linq
Dim strtest As String = "Domain\X_User|X_User,Domain\Y_User|Y_User,"
'This splits the string according to "|" and ",". Now any string without _
a "\" is the user and Join adds them together with `,` as a delimiter
Dim result As String = Join((From s In strtest.Split("|,".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Where Not s.Contains("\")
Select s).ToArray, ",")
Just in case LINQ is unavailable to you here's a different way to the same results without LINQ:
Dim result As String = ""
For Each s As String In strtest.Split("|,".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
If Not s.Contains("\") Then
result += s & ","
End If
Next
result = result.TrimEnd(",".ToCharArray)
I need to pass in parameters to my sub/function.
When the parameter is passed, the value in the string, I would like to get the value evaluated and sent as:
Dim strParams As String = drRow(0)
' drRow is a row from DB Table. the value in drRow(0) =
' "#FromDate=""" & Now.AddDays(-10).ToShortDateString & """&#ToDate=""" & Now.AddDays(-4).ToShortDateString "
I would like to see this converted to:
Dim strFinal as string
strFinal = ProcessString(strParams)
End Result should be:
strFinal = "#FromDate=10/09/2011&#ToDate=10/15/2011"
Any ideas how I can do this. I am getting the initial string from DB, I need to convert to the final string, I am not able to figure out how to write the "ProcessString" function.
Thanks for looking.
"IF" you can change your parameter statement to something simple like:
#FromDate=;-10;#ToDate=;-4
Then you can do something like this:
Dim strParams As String = "#FromDate=;-10;#ToDate=;-4"
Dim value As String = String.Empty
Dim parts() As String = strParams.Split(";"c)
If parts.Length = 4 Then
Dim fromDays As Integer
Dim toDays As Integer
If Integer.TryParse(parts(1), fromDays) AndAlso Integer.TryParse(parts(3), toDays) Then
value = parts(0) + Now.AddDays(fromDays).ToShortDateString + parts(2) + Now.AddDays(toDays).ToShortDateString
End If
End If
MessageBox.Show("Value = " & value)
If it's anything more complicated than that then you will have to start parsing every part of your string with lots of If and Select statements-- you should probably heed Jim Mischel's advice and try a different approach.
This is the end result of what i used based on suggestions.. Thanks Guys.
Public Function ProcessParameters(ByVal strParams As String) As String
Dim arrParams() As String
'strParams = "#FromDate=-10;&#ToDate=-4;&#CompanyID=1"
arrParams = strParams.Split(";")
Dim arrP() As String
Dim strFinalParams As String = ""
For Each strP As String In arrParams
arrP = strP.Split("=")
If arrP(0).ToString.EndsWith("Date") Then
strFinalParams &= arrP(0) & "=" & Now.AddDays(arrP(1)).ToShortDateString
Else
strFinalParams &= arrP(0) & "=" & arrP(1)
End If
Next
Return strFinalParams
End Function
}
Lets say i have this in a shell
"chdir * && whoami.exe >> $$$"
I have this replacecommand
Dim ReplaceCommand as String = sCommand.Replace("*", UserDirect)
I also would like the $$$ to be replaced with a user chosen filepath.
I can get the file path chosen but it never puts it into the shell.
I have tried
Dim ReplaceCommand1, ReplaceCommand2 as String = sCommand.Replace("*" & "$$$", UserDirect & filepath)
Shell("cmd.exe" & ReplaceCommand1 & ReplaceCommand2)
Dim ReplaceCommand as String = sCommand.Replace("*", UserDirect) & ("$$$", filepath)
Shell("cmd.exe" & ReplaceCommand)
also
Dim ReplaceCommand1 as String = sCommand.Replace("*", UserDirect)
Dim ReplaceCommand2 as String = sCommand.Replace("$$$", filepath)
Shell("cmd.exe" & ReplaceCommand1 & ReplaceCommand2)
EDIT:
get a path to short error when I use commas in shell instead of &
Dim ReplaceCommand1 as String = sCommand.Replace("*", UserDirect)
Dim ReplaceCommand2 as String = sCommand.Replace("$$$", filepath)
Shell("cmd.exe", ReplaceCommand1 , ReplaceCommand2)
You can chain the Replace's together:
Dim ReplaceCommand1 as String = sCommand.Replace("*", UserDirect).Replace("$$$", filepath)
Shell("cmd.exe" & ReplaceCommand1)
Part of your examples don't compile cause of the syntax errors.
You're not using Shell() like you're supposed to.
Public Function Shell(
PathName As String,
Optional Style As Microsoft.VisualBasic.AppWinStyle = MinimizedFocus,
Optional Wait As Boolean = False,
Optional Timeout As Integer = -1
) As Integer
From the examples you gave, it looks like you're just throwing stuff together. Stop and think for a minute :)