VB.NET: short cuts in code - vb.net

Why is the following VB.NET code setting str to Nothing in my VS2005 IDE:
If Trim(str = New StreamReader(OpenFile).ReadToEnd) <> "" Then
Button2.Enabled = True
TextBox1.Text = fname
End If
OpenFile is a Function that returns a FileStream
EDIT: If the above line containing Trim is not correct, is there a way to achieve the intended result in only one line?

The code is never setting str at all:
If Trim(str = New StreamReader(OpenFile).ReadToEnd) <> "" Then
This line doesn’t set str, it compares it to the result of reading the file.
In VB, the = operator has two meanings, depending on context. If used in a statement, it assigns the right-hand expression to the left-hand expression. If used in any other context (i.e. in an expression), it performs an equality comparison, not an assignment.
Thus, in VB you must write the following:
str = New StreamReader(OpenFile()).ReadToEnd()
If str.Trim() <> "" Then …
Notice that I’ve replaced the free function Trim by a method call to make the code more consistent with common .NET coding practices.

The first thing to do when starting any VB.Net project is to make sure that Option Explicit and Option Strict are both set to true in the project settings. Only ever disable either of them if you have a specific reason (you need late binding or are taking over some old horrible code).
This would have stopped that code from even compiling and would have shown you the error right away.

Because you're not setting str, you're comparing it, then trimming the result of the comparison (basically trimming either "True" or "False"
If Trim(str = New StreamReader(OpenFile).ReadToEnd) <> "" Then
This doesn't actually set str, this breaks down to the following code
Dim str as string ' Defaults to nothing/""
Dim boolValue as bool = (str = New StreamReader(OpenFile).ReadToEnd)
If Trim(boolValue) <> "" Then
' This is always true, as "True" and "False" will never = ""'
...
End If

Related

VB.NET variable initialization problem on Publish

Is there any way to stop Visual Studio from removing variable initializations prior to publish?
I have a variable:
Dim myString as String: myString = Nothing
When I click publish, Visual Studio removes ": myString = Nothing"
and then during build it complains "myString is used before it is initialized". If I do a build (instead of publish) this doesn't happen.
This appears to be more a warning. It's perfectly legal to initialize a string using the colon separator, but likely it's being optimized out.
Your code:
Dim myString as String: myString = Nothing
is the equivalent of:
Dim myString as String = Nothing
which is the equivalent of:
Dim myString as String
as Strings default to Nothing by default, at least in the all the more recent versions of VB/ASP I can find
And as such will trigger that warning. whether or not it affects your output? that's on you :)

How do I get only one result for each app instead of double?

Copy this into Visual Studio, add a textbox and it'll run.
Const NET_FW_ACTION_ALLOW = 1
Dim fwPolicy2 = CreateObject("HNetCfg.FwPolicy2")
Dim RulesObject = fwPolicy2.Rules
For Each rule In RulesObject
If rule.action = NET_FW_ACTION_ALLOW Then
TextBox1.Text += rule.name & vbnewline
End If
Next
This is an example of what I get but I only need each app to be listed once, not two times. What am I doing wrong or why does it behave like this?
qBittorrent
qBittorrent
Chrome
Chrome
Visual Studio
Visual Studio
and so on...
It behaves like this because rule.Name is not a unique identifier for a firewall rule. The same rule name may be used for different protocols (TCP, UDP), profiles (domain, private, public), direction (in, out), etc. If you are only interested in rule.Name, add them to a set, then print that set, as follows.
Const NET_FW_ACTION_ALLOW = 1
Dim fwPolicy2 = CreateObject("HNetCfg.FwPolicy2")
Dim RulesObject = fwPolicy2.Rules
Dim names As New HashSet(Of String)
' Create set of unique names.
For Each rule In fwPolicy2.Rules
If rule.action = NET_FW_ACTION_ALLOW Then
names.Add(rule.name)
End If
Next
' Add names to TextBox.
For Each name As String In names
TextBox1.Text += name & vbNewLine
Next
For Each rule In RulesObject
If rule.action = NET_FW_ACTION_ALLOW AndAlso TextBox1.Text.Contains(rule.name.ToString) = False Then
TextBox1.Text += rule.name & vbnewline
End If
Next
The above is one way to do it. It simply checks whether it's already added to the textbox. Btw, I don't know offhand whether or not rule.name is already a string so I added .ToString; if it's already a string, you don't need to add that.
Also, most of us would recommend using Option Strict, and declaring your variables as a type. i.e. Dim myVar as String = "some string"

Conversion From String to Boolean Vb.net

I want to evaluate a String with Boolean Values and Binary Logical Operators (And/Or).
When i write Dim Expression = ((True And False) Or True) then the value of "Expression" Will be true.
However, when i write Dim Expression = "((True And False) Or True)" and try to convert the string to Boolean using Convert.ToBoolean() like MsgBox(Convert.ToBoolean(Expression)) then i got an error stating: String was not recognized as a valid Boolean. as in the picture.
All previous posts deals with strings containing only "True" or "False". but rarely i found a post dealing with an Expression containing brackets and more than one operator as "((True Or False) And True)" or much more complicated expressions. is this supported in the convert.ToBoolean function and if yes why i am getting this error?
There is a round-about way of evaluating an expression using Microsoft script control ..
Right click on your project and choose Add
In the sub menu, choose Reference
In the window that appears, on the left click on COM
Scroll down until you see MicrosoftScriptControl 1.0 and double click it.
Then click Ok on the lower right of the window
This function takes a string and using VBScript, evaluates the string expression. You can of course tweak it to your needs.
Private Function EvaluateBoolean(formula As String) As Boolean
Dim sc As New MSScriptControl.ScriptControl
'SET LANGUAGE TO VBSCRIPT
sc.Language = "VBSCRIPT"
'ATTEMPT MATH
Try
Return Convert.ToBoolean(sc.Eval(formula))
Catch ex As Exception
'SHOW THAT IT WAS INVALID
MessageBox.Show("Invalid Boolean expression")
End Try
End Function

VB : Parentheses automatically added in error

My colleagues frown upon me because according to our sourcesafe, I added parentheses to the method-property thus resulting in a stackoverflow.
Since I'm sure I did no such thing on purpose, I wonder if somehow I used a obscure shortcut which performed these changes.
This kind of stuff :
Public Function Opslaan() As Boolean
If something_wrong() Then
opslaan = False
End If
If opslaan = False Then
Do_Something_Else()
End If
Return opslaan
End Function
and this got changed into :
Public Function Opslaan() As Boolean
If something_wrong() Then
opslaan = False
End If
If opslaan() = False Then '' See the parentheses here added automatically
Do_Something_Else()
end If
Return opslaan
End Function
Any help is appreciated.
This looks like bad old VB6 code converted to VB.NET.
The problem is VB6 allowed you to treat the current function name as a variable and update its value all throughout the method. Then, when you exited the method whatever value this variable had would be returned to the caller. This syntax is confusing and should never be used, even in VB6 since there is a better way.
Update all code you find like this to something like:
Public Function Opslaan() As Boolean
Dim result As Boolean = True
If something_wrong() Then
result = False
end if
If result = False Then
Do_Something_Else()
End If
Return result
End Function
This is much clearer code and will never mistakenly call the same routine.
Also, this is totally personal preference, but I prefer to not check booleans with equals statements. So If result = False Then becomes If Not result Then and If result = true Then becomes If result Then. That almost always feels cleaner to me for Booleans.

Why Does Replace Return Nothing on Empty String

Replace("",vbLf, "")
Go figure.
It should return ""
No. It returns nothing.
Just put the code in vb.net
I think it should return "". Replace all occurance of vbLF with "". Because the original string is "" then it simply replace nothing and we got back ""
\No. We got back nothing.
You are using Visual Basic string functions, not .Net. The Visual Basic runtime usually evaluates Nothing as an empty string ("").
I second the original post, VB.net should not return NOTHING with its REPLACE function. However, it does if your replace happens to return Nothing if the expression is an empty string.
To elaborate on this for anyone winding up here, when you just call "Replace" you're getting Microsoft.VisualBasic.Replace, not the String.Replace you're expecting.
Microsoft.VisualBasic.Replace: https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic?view=netframework-4.7.2
String.Replace: https://learn.microsoft.com/en-us/dotnet/api/system.string.replace?view=netframework-4.7.2
If you want to return an empty string you need to call the .Replace method of a String:
dim myString as String = ""
myString.Replace("a", "b")
This of course finds no match, but the behavior is instead to return and empty string now instead of Nothing when the input expression is an empty String.