Option Strict On disallows implicit conversions from 'String ' to 'Char' VB.NET - vb.net

I'm using Option Strict On (and sometimes wishing I wasn't!) but have a piece of code that works as I want it to without it but not with it.
It should be quite simple I think but I couldn't find an answer here.
My code that works with Option Strict Off is this:
If returnedString.Contains(".exe ") And returnvalues.Count = 0 Then
Dim x As Integer = 0
For Each entry In returnedString.Split(".exe ")
If (entry.Length > 0) And x = 0 Then
returnvalues.Add(entry & ".exe")
x = x + 1
End If
Next
End If
The returnedString is, for example:
C:\Program Files (x86)\Whatever\Whatever.exe
and
C:\Program Files (x86)\Whatever\Whatever
is returned in entry if Option Strict is off, which is what I want.
However, if I use Visual Studio's suggestion of adding a cast, the following does not work:
For Each entry As String In returnedString.Split(CType(".exe ", Char()))
The first entry returned is C:\Program and this is presumably because it finds the Char ' '; I don't want it to check per character, I want it to check the whole string like it does when Option Strict is off but I can't work it out.
I tried .ToCharArray but that really does the same thing.

Please continue to use Option Strict On. It is annoying but it will save your day a lot.
For your problem:
It is caused by the fact that when you enable Option Strict On, the compiler is no longer allowed to take the first char from your string and use it as separator. Because there is no overload for string.Split that takes just a string, then it complains about an attempt to an do invalid conversion.
If you want to use a string as separator then it is required to pass an array of strings as the first parameter, and a second parameter of type StringSplitOptions is required.
Fixing it is really simple. Just change the line to:
For Each entry In returnedString.Split({".exe"}, StringSplitOptions.None)

Related

System.InvalidCastException: 'Conversion from string "INSERT INTO Listing (ID_Listing," to type 'Double' is not valid.' In Visual Basic

Im having this error pop up when running my app, i cant seem to find what causes the error, as I'm not even using any Double variables
Private Sub btnCrearListing_Click(sender As Object, e As EventArgs) Handles btnCrearListing.Click
conexion.Open()
Dim CrearListing As New OleDbCommand("INSERT INTO Listing (ID_Listing, precio, cantidad_item, ID_Usuario, ID_Item, Tipo_Listing) VALUES (" + ContadorListing + "," + Val(txtPrecio) + "," + Val(txtCantidad) + "," + Login.JugadorLogeado + "," + ItemListado + ",'" + cboTipoListing.Text + "')", conexion)
ContadorListing = ContadorListing + 1
conexion.Close()
End Sub
If you're going to concatenate strings then use the concatenation operator (&), NOT the addition operator (+). If both operands are String objects then addition maps to concatenation. If the operands are different types though, one will need to be implicitly converted to the other type in order for the addition to be perfromed. In this case, the system is trying to implicitly convert the String to a Double in order to add it to the other number but it obviously fails because that String doesn't represent a number. If you use the concatenation operator then the system knows you want to concatenate, so it will convert the number to a String.
You really ought to have Option Strict On, which would catch bad code like this at compile time, rather than letting it slip through to run time. It won;t tell you how to fix it necessarily but it will at least tell you that there's something to fix. ALWAYS turn Option Strict On in your project properties and also in the VS options, so it will be On by default for all future projects. You can then turn it On at the file level on the rare occasions that you actually need it for specific code.
Having said all that, you shouldn't be building SQL code using string concatenation in the first place. ALWAYS use parameters as it avoids a number of issues. I won't go into specifics here, as that's beyond the scope of the question you actually asked, but you should read this and modify your code accordingly.

VB.net build solution by ignore error

Greeting everyone, i'm new member and this's my first time to post question on this.
I need your help to advise me how can i ignore the error and build the solution.
From my code has error 'BC30057' about 'Too many arguments' as you see. But i must use many kinds of argument due to this function depend on .dll file (many version with variant agrument) on each computer.
Please advise me, and if you have better solution plese let me know.
=======================================================================
Select Case Group
Case "A"
tmpStr = FITSCon.fn_InitDB(FITS_OPN, FITSRev)
Case "B"
tmpStr = FITSCon.fn_InitDB(FITS_Model, FITS_OPN, FITSRev, FITSName)
Case "C"
tmpStr = FITSCon.fn_InitDB(FITS_Model, FITS_OPN, FITSName)
End Select
=======================================================================
If that code is in a file for which Option Strict is set to Off then you can assign FITSCon to a variable of type Object and then call your method on that. With Option Strict Off, late-binding is permitted so you can use any signature you want in that case, as long as it's valid at run-time.
If you already have Option Strict Off for the project (which is the default for VS but I would recommend changing that) then all you need to do is this:
Dim FITSConObject As Object = FITSCon
Select Case Group
Case "A"
tmpStr = FITSConObject.fn_InitDB(FITS_OPN, FITSRev)
Case "B"
tmpStr = FITSConObject.fn_InitDB(FITS_Model, FITS_OPN, FITSRev, FITSName)
Case "C"
tmpStr = FITSConObject.fn_InitDB(FITS_Model, FITS_OPN, FITSName)
End Select
If you have Option Strict On for the project then leave a comment to that effect and I'll provide a detailed explanation of the best course of action, which would involve moving that code to a partial class in a separate code file, so you can turn Option Strict Off for the minimum of code.

Format number with leading zeroes in .NET 2.0

I have problem to format numbers and convert it to string with leading zeroes when application uses NET framework 2.0 with Visual Basic.
I try:
Dim myNum = 12
Dim myStr as String
Dim myStr = myNum.ToString("0000")
or
Dim myStr = myNum.ToString("D4")
... in order to get wanted string: 0012
Please help to solve this.
You have an old version of Visual Studio, one that doesn't have Option Infer yet. Or it isn't turned on. That makes the myNum identifier a variable of type Object.
So your code tries to call the Object.ToString() method. Which does not have an overload that takes an argument. The compiler now tries to make hay of your code and can only do so by treating ("0000") or ("D4") as an array index expression. Indexing the string that's returned by Object.ToString(). That has pretty funny side effects, to put it mildly. A string like "0000" is not a valid index expression, the compiler generates code to automatically convert it to an Integer. That works for "0000", converted to 0 and the result is a character, just "1"c. Converting "D4" to an integer does not work so well of course, that's a loud Kaboom!
The solution is a very simple one, just name the type of the variable explicitly:
Dim myNum As Integer = 12
Dim myStr = myNum.ToString("D4") '' Fine
VB.NET's support for dynamic typing is pretty in/famous. Meant to help new programmers getting started, it in fact is an advanced technique given the myriad ways it can behave in very unexpected ways.
The universal advice is always the same. Let the compiler help you catch mistakes like this. Put this at the top of your source code file:
Option Strict On

Easy way to remove warning messages after converting vb6 project to VB.NET

I have converted a VB6 project to VB.NET and am left with a large number of inline 'warning messages' such as "UPGRADE_WARNING: Couldn't resolve default property of object varJonSkeet" that I would like to get rid of. Is there a way to do this within Visual Studio 2008? Will it be easier to remove the warning messages with regex? I would prefer to do the removals one file at a time, but it isn't a dealbreaker.
Quick and simple fix if using VS 2008, use Find and Replace :
Open up the find options
Click 'use' and then select 'Wildcards'
In the 'Find what' put "'Upgrade Warning*" and leave the 'Replace with' blank
Click 'Replace All'
The best way to get rid of warnings is to address the suspicious code that the warnings complain about. That is, change the code such that it is no longer warning-worthy. Don't just seek to disable the generation of warnings altogether.
You'll need to provide more details about the specific warnings you're concerned about, and the accompanying code. But remember to search previous answers here first.
I see the warnings are actually text literally in your code, not messages issued in the compiler output. The way to get rid of those is to search for the keyword (UPGRADE_WARNING, I guess), consider whether the issue that it warns about has been addressed or is still a valid concern, fix the problem if there is one, and the delete that warning line. For example, does varJonSkeet have a default property, and if not, does it need one? Should you use to a non-default property instead? (You're not really asking how to delete a line of text, are you?)
If you've already gone through the whole file and determined that none of the warnings are valid, there's a quick way of removing all the warning lines.
grep -v UPGRADE_WARNING input_file.vb > output_file.vb
ren output_file.vb input_file.vb
If you don't already have grep on your system, then you don't have a complete development environment yet. Go get a copy. The -v option tells it to invert the search results, thus printing all lines that don't contain the search pattern. Those get written into the new file. Then replace the old file with the new one.
I believe he is saying that he wants to remove the inline comments from his code.
Fastest way is to perform a find in files for UPGRADE_WARNING: and remove them by hand.
Or,
You could create a new .Net program to iterate through each .vb file in your source directory and read them in using a StreamReader and then write them out 1 line at a time to the same file and as you go omit any lines containing UPGRADE_WARNING:.
If you do the second way you will be that much better for having done some more vb.net coding.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim FileName As String = "c:\form1.vb"
Dim SourceFile As System.IO.FileInfo = New FileInfo(FileName)
Dim SourceTextStream As System.IO.TextReader = SourceFile.OpenText()
Dim SourceFileContent() As String = Split(SourceTextStream.ReadToEnd(), vbCrLf)
SourceTextStream.Close()
Dim CurrentSourceLine As String
Dim CurrentSourceLineNumber As Long
Dim DestStream As StreamWriter = New StreamWriter(FileName)
Dim LogStream As StreamWriter = New StreamWriter(FileName + ".log")
For Each CurrentSourceLine In SourceFileContent
CurrentSourceLineNumber += 1
If InStr(CurrentSourceLine, "UPGRADE_WARNING") = 0 Then
DestStream.WriteLine(CurrentSourceLine)
Else
' Write to Log File
LogStream.WriteLine("Line Skipped at number: " + CurrentSourceLineNumber.ToString())
End If
Next
DestStream.Close()
LogStream.Close()
End Sub
Rewrite the project in VB.NET. Getting rid of the warnings might is only a means to get to the goal which (i presume) is a working program.
The VS 2008 method mentioned above does not work with VS 2010 and later.
for VS 2010 and later follow these steps to remove upgrade warnings...
CTRL + F
Expand the "Find..." drop-down and select "Find In Files...".
Select the "Replace in Files" tab.
Find what: [^\S\r\n]'UPGRADE_WARNING:.*\r?\n
Replace with: BLANK
Expand "Find Options".
Check "Use Regular Expressions".
Begin your search/replace/replace all.
Explained: Using regex, the [^\S\r\n] tells regex to ignore the white-space at the beginning of the line, then obviously the 'UPGRADE_WARNING: is the start of the warning comment were looking for, then the .* tells regex to ignore everything else up to the *\r?\n, then the *\r?\n tells regex to also match the line-break at the end (without this part would leave a blank line where each warning would have been).

VB6 Editor changing case of variable names

I'm not much of a Visual Basic person, but I am tasked with maintaining an old VB6 app. Whenever I check out a file, the editor will replace a bunch of the uppercase variable names with lowercase automatically. How can I make this stop!? I don't want to have to change them all back, and it's a pain to have these changes show up in SourceSafe "Differences" when I'm trying to locate the REAL differences.
It is changing it automatically in the definition, too:
Dim C as Control becomes Dim c as Control. Dim X& becomes Dim x&. But it doesn't do it all the time; for example, three lines down from Dim x&, there's a Dim Y&, uppercase, which it did not change. Why's it do this to me?
Since I always find this thread first looking for a solution to messed-up casing, here is one Simon D proposed in a related question:
If you just need to fix one variable's casing (e.g. you accidentally made a cOrrectCAse variable and now they are all over the place), you can correct this for good by adding
#If False Then
Dim CorrectCase
#End If
to the beginning of your module. If you save the project and remove the statement later, the casing remains correct.
Using Excel VBA I often accidentally change all Range.Row to Range.row by carelessly dimming a row variable inside some function - with the help of Simon D's solution I can fix this now.
Continuing from DJ's answer...
And it won't only change the case of variables in the same scope either.
It will change the case of all variables with the same name in your entire project. So even if they're declared in uppercase in one place, another module might have different variables using the same variable names in lowercase, causing all variables in your project to change to lowercase, depending on which of the declarations was loaded (?) or edited last.
So the reason your C and X variables are changing case, while the Y isn't, is probably because C and X are declared somewhere else in your project too, but in lowercase, while Y isn't.
There's another mention of it here, where they mostly seem concerned with such variable names conflicting when case is being used to differentiate local from global variables. They end up going for prefixes instead.
The only alternative I can think of is to use some other editor with VB6-highlighting capabilities to do your editing...
Enums are even worse. Getting the case wrong anywhere the enum is used changes the case of the definition.
To get past the painful file diff experience, set the VSS option in the diff dialog to do case-insensitive comparisons. That way you'll only see the "real" changes.
It must be defined/declared in lower-case. Locate the declaration and fix it there. The IDE will always change the case to match the declaration.
Close all the VB projects, open the form file with a text editor, change the case of all the names then re-open the Project with VB IDE.
Prevent VB6 auto correct For enum values
As my general rule I declare constants in UPPERCASE. Since enums are essentially constants I like to declare values for enums in UPPERCASE as well. I noticed the VB6 IDE also auto corrects these.
I found the IDE does not correct these values when using numbers and underscores '_' in the value names.
Example:
Public Enum myEnum
VALUE 'Will be corrected to: Value
VALUE1 'Will not be corrected
VALUE_ 'Will not be corrected
End Enum
I do not know if this works in general and if this extends to naming/auto correction of variable names.
I have had a similar enumeration problem where for no apparent reason UPPERCASE was changed to MixedCase.
Enum eRowDepths
BD = 1
CF = 1
Separator = 1
Header = 3
subTotal = 2
End Enum
When I changed to the following (tailing the last character of the non-conforming variables), I had no problem
Enum eRowDepths
BD = 1
CF = 1
SEPARATO = 1
HEADE = 3
SUBTOTA = 2
End Enum
It turns out that this is a case of the tail wagging the dog. I have the following code, not the most elegant I admit but working nonetheless (please excuse formatting issues):-
'insert 3 rows
iSubTotalPlaceHolder = i
rows(ActiveSheet.Range(rangeDMirrorSubTotals).Cells.Count + _
Header _
& ":" _
& ActiveSheet.Range(rangeDMirrorSubTotals).Cells.Count + _
Header + _
subTotal + _
Separator).Insert
So it seems that the compiler won't accept explicit UpperCase constants as part of this statement.
This was acceptable
Dim fred as Integer
fred = SEPARATO + HEADE + SUBTOTA
So my work-around is to use a variable instead of the constants as part of the complex insert statement if I want to stick to the rule of keeping enumerated constants uppercase.
I hope this is of use
DJ is spot on... VB always changes the case of variables to match the original declaration. It's a 'feature'.
Continuing from Mercator's excellent answer...
I'd recommend:
Check out all files (I assume you're using VSS for a VB6 app)
Do a rebuild of the entire project group
Recheck back into VSS
Now base you're the real differences rather than the 'auto' changes that VB6 has tried to apply.