LINQ VB.Net variable not declared error - vb.net

I am trying to run this line of code:
Dim OrderedFiles() As String = Directory.GetFiles(FilePath).OrderBy(x >= x.CreationTime)
I get an error on x saying x is not declared.
I have my project set to Option Strict Off and Option Infer On. If I turn ON Option Strict then I get thousands of errors from the project(it is inherited) and I don't have the time to fix all of them, but x no longer gives me an error. I have googled until I want to throw my computer out the window.
Any help on how to correct this statement would be appreciated.
Edit:
I was hoping for a more elegant solution but here is what I came up with to solve this particular problem.
Dim fileList() As String = Directory.GetFiles(FilePath)
Dim fileDate(fileList.Length - 1) As DateTime
For i As Integer = 0 To fileList.Length - 1
fileDate(i) = New FileInfo(fileList(i)).CreationTime
Next
Array.Sort(fileDate, fileList)
With EmailTemplates_DropDownList
.DataSource = fileList.Reverse.Take(5)
.DataBind()
End With
It is not particularly elegant but it does the job. I was hoping for a one liner LINQ solution and I just don't have the background in LINQ to know how to do the job, time to go buy a book.

I'm not sure where you got this syntax from:
OrderBy(x >= x.CreationTime)
That almost looks like the C# syntax of
OrderBy(x => x.CreationTime)
but I believe in VB you would use
OrderBy(Function(x) x.CreationTime)
That's certainly what the example in Enumerable.OrderBy would suggest.
EDIT: At that point you'll get a different error, as per Steve's post... but he hasn't corrected the syntax. I suspect you want:
Dim OrderedFiles() As FileInfo = new DirectoryInfo(FilePath).GetFiles().
OrderBy(Function(x) x.CreationTime).
ToArray()

Directory.GetFiles() returns the names of files (including their paths) in the specified directory.
It's not possible to use x.CreationTime, x is a string
Probably you should use DirectoryInfo
Dim di as DirectoryInfo = new DirectoryInfo(FilePath)
Dim OrderedFiles = di.GetFiles().OrderBy(Function(x) x.CreationTime).Take(3)
Dim fi as FileInfo
For each fi in OrderedFiles
Console.WriteLine(fi.FullName)
Next

Related

Remove parts of a string in vb.net

Im using the FolderBrowserDialog to pick a path.
It will return for ex. this= C:\Mypath1\Mypath2\DOCS
I would like to remove everything but DOCS.
If i use VBA i would use a InStrRev combined with a left. But now in in VB.net and im not sure how to achieve this, im pretty sure there is something better than my old VBA way?
Anyone there that could help, google failed me.
Try this:
IO.Path.GetFileName("C:\Mypath1\Mypath2\DOCS")
Which returns DOCS.
I am not sure what you want to do. But maybe this can help you get the last part of a string
Dim fullPath As String = " C:\Mypath1\Mypath2\DOCS"
Dim Parts As String() = fullPath.Split("\")
Dim lastPart As String = Parts(Parts.Length - 1)

LINQ Count problems while trying to access to subList from a List of Objects (VB.NET)

I'm having a pretty tough time figuring it out why it doesn't work properly but I'm asking for it.
Dim goodCount As Integer = (From item In equipmentTagList
Where item.Importance = "Critique"
Where item.Status <> TargetRange.OutOfRange
Select item).Count()
Dim badCount As Integer = (From item In equipmentTagList
Where item.Importance = "Critique"
Where item.Status.Contains(TargetRange.OutOfRange)
Select item).Count()
EquipmentTagList is a List(Of MachineTag) (custom object) so I want to get how many MachineTag from the EquipmentTagList matches the criteria. I'm still confused about why the first one works but not the other one. I know by debugging that the first one returns at least one result while the other returns nothing... I've searched a lot to get help for this error but unfortunately found nothing...
Thanks for helping me out.
EDIT:
The error I get is :
System.InvalidOperationException with Object reference not set to an instance of an object
Assuming for the moment that item.Status is an Integer data type (inferred from your use of TargetRange.OutOfRange as though it's an Enum), the syntax in your second snippet would be expected to fault.
The .Contains() method is reserved for use with IEnumerable objects, not Integer values.
If you modify your code slightly, to this:
Dim badCount = (From item In equipmentTagList
Where item.Importance = "Critique"
Where item.Status.Contains(TargetRange.OutOfRange)
Select item)
...and then set a breakpoint at some point after this call, you'll note that badCount is Nothing. Since Nothing can't have a .Count, the call fails.
Your first snippet is correct—as you've already pointed out.
EDIT
Something's not right here. Your code shouldn't even compile.
Here's what I'm getting:
So item.Status certainly can't be an Integer.
Maybe this will make it a bit easier. You can group by Status after filtering by Importance:
Dim items = From i In equipmentTagList Where i.Importance = "Critique"
Dim counts = items.ToLookup(Function(i) i.Status <> TargetRange.OutOfRange)
Dim goodCount = counts(True).Count()
Dim badCount = counts(False).Count()

Convert String input to working VB code

Is it possible to convert, say, a textbox input to working code?
For example, user types 'if x<10 then y=2 else y=5' into textbox1, it gets used directly as code something like ...
dim x as integer = 5
dim y as integer = 0
include processed textbox1.text
resultbox.text = (y*20).tostring
It's not important why this would be needed - just whether there is any straight-forward method that parses a string to code.
Many thanks.
Maybe this is what you are looking for:
http://www.codeproject.com/Articles/12852/Compile-and-Run-VB-NET-Code-using-the-CodeDom
yes you can do this using the VBCodeProvider class. Although the amount of code required is quite significant:
http://www.codeproject.com/Articles/5472/Compiling-NET-code-on-the-fly

Visual Basic.NET - Add two numbers (I/O from file)

Following code should sum two numbers from file "input.txt" and write the sum to "output.txt". Compilation is succesfull, but "output.txt" is still empty after running program. What am I doing wrong?
Imports System.IO
Public Class test
Public Shared Sub Main()
Dim scan as StreamReader = new StreamReader("input.txt")
Dim writer as StreamWriter = new StreamWriter("output.txt", True)
Dim input as String
input = scan.ReadLine()
Dim ab() as String = Split(input)
Dim res as Integer = Val(ab(0))+Val(ab(1))
writer.writeLine(res)
writer.close()
End sub
End class
Your code works properly for me, so as long as your input file is formatted properly (i.e. a single line with two numbers separated by spaces, like "1 2") and you have the necessary OS permissions to read and write to those files, then it should work for you too. However, it's worth mentioning that there are several issues with your code that would be good to correct, since the fly in the face of typical best-practices.
First, you should, as much as possible, turn Option Strict On. I know that you have it Off because your code won't compile with it On. The following line is technically misleading, and therefore fails with Option Strict On:
Dim res As Integer = Val(ab(0)) + Val(ab(1))
The reason if fails is because the Val function returns a Double, not an integer, so, technically, depending on the contents of the file, the result could be fractional or could be too large to fit in an Integer. With Option Strict Off, the compiler is essentially automatically fixing your code for you, like this:
Dim res As Integer = CInt(Val(ab(0)) + Val(ab(1)))
In order to set the res variable equal to the result of the calculation, the more capable Double value must be converted down to an Integer. When you are forced to put the CInt in the code yourself, you are fully aware that the conversion is taking place and what the consequences of it might be. When you have Option Strict Off and it inserts the conversion behind-the-scenes, then you may very well miss a potential bug.
Secondly, the Val function is old-school VB6 syntax. While it technically works fine, it's provided mainly for backwards compatibility. The new .NET equivalent would be to use Integer.Parse, Integer.TryParse or Convert.ToInt32.
Thirdly, you never close the scan stream reader. You could just add scan.Close() to the end of your method, but is better, when possible, to create Using blocks for any disposable object, like this:
Using scan As StreamReader = New StreamReader("test.txt")
Using writer As StreamWriter = New StreamWriter("output.txt", True)
Dim input As String
input = scan.ReadLine()
Dim ab() As String = Split(input)
Dim res As Integer = Integer.Parse(ab(0)) + Integer.Parse(ab(1))
writer.WriteLine(res)
End Using
End Using
Lastly, as Hans pointed out, it's not good to rely on the current directory. It's always best to specify full paths for your files. There are different methods in the framework for getting various folder paths, such as the user's desktop folder, or the download folder, or the temp folder, or the application folder, or the current application's folder, or the folder of the current running assembly. You can use any such method to get your desired folder path, and then use Path.Combine to add the file name to get the full file path. For instance:
Dim desktopFolderPath As String = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
Dim inputFilePath As String = Path.Combine(desktopFolderPath, "input.txt")
Dim outputFilePath As String = Path.Combine(desktopFolderPath, "output.txt")

How do I pass ItemSpec into GetBranchHistory()?

I'm trying to get information about specific branches in TFS, so to start, I'm trying to create a variable to assign as a BranchHistoryTreeItem. However, when I pass in the ItemSpec, I'm getting an error on Spec (not the definition, but where it's passed into GetBranchHistory):
Value of type 'Microsoft.TeamFoundation.VersionControl.Client.ItemSpec' cannot be converted to '1-dimensional array of Microsoft.TeamFoundation.VersionControl.Client.ItemSpec'
I understand the error, but I'm not entirely sure why it throwing it. Isn't this data type exactly what it's looking for? I believe I have the ItemSpec declared correctly, but I'm a bit lost here. Can anyone offer some advice on why I'm getting this? Code:
Sub GetBranchInfo()
Dim tfs As New TfsTeamProjectCollection(Common.BuildServerURI)
Dim Version = tfs.GetService(Of VersionControlServer)()
Dim Spec As New ItemSpec("$/Project1", RecursionType.None)
Dim BranchHistory As New BranchHistoryTreeItem(Version.GetBranchHistory(Spec, VersionSpec.Latest))
End Sub
GetBranchHistory takes an array of ItemSpecs.
My VB is a little rusty, but I think you want something like:
Dim Spec As New ItemSpec("$/Project1", RecursionType.None)
Dim Specs(1) = new ItemSpec() {Spec}
Dim BranchHistory As New BranchHistoryTreeItem(Version.GetBranchHistory(Specs, VersionSpec.Latest))