Sub declaration within lambda expression doesn't work - vb.net

I tried to run the following example from http://www.informit.com/articles/article.aspx?p=2429291&seqNum=8
Private progress As Progress(Of Integer)
Private counter As Integer = 0
Sub Main()
Try
progress = New Progress(Of Integer)
AddHandler progress.ProgressChanged, Sub(sender, e)
Console.
WriteLine _
("Download progress: " & _
CStr(e))
End Sub
DownloadAllFeedsAsync(progress)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
Console.ReadLine()
End Try
End Sub
My problem is, that the following line is not accepted by the compiler:
AddHandler progress.ProgressChanged, Sub(sender, e)
Console.WriteLine("Download progress: " & CStr(e))
End Sub
There seems to be a problem with sender and e.
The error message is the following:
The Lambda-Parameter "sender" hides a variable in an embracing Block".
Does somebody know this problem?

As i mentioned in my comment to the question: i've checked related code on both VS: 2012 and 2017 and it's getting compiled without errors.
As to your error message, please check this: Lambda parameter '' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression
The most important thing is:
To correct this error
Ensure that all variables in your lambda expression have unique
names that do not duplicate existing variable names in the same scope.
Accordingly to your comment:
In the example from the link there is only a Sub Main() whereas in my
example I have Form1_Load(Sender As Object, e as Eventargs).
So, variables: sender and e are existing in the same scope. Now, you know what to do to resolve your issue ;)

Related

vb.net - error handling on main method or every method

I have a program that is interacting with emails. I am upgrading it from vb6 to vb.net. There was extensive error handling in the program before ,using On Error commands, to ensure that it never broke, just ignored and logged the errors. In most functions there is this On Error code, where it handles an error in the function by returning a default value and exiting the function. For Example:
Public Function Init() As Boolean
On Error GoTo Err_Init
Init = True
Exit_Init:
Exit Function
Err_Init:
Init = False
Resume Exit_Init
End Function
I want to change all error handling to Try - Catch blocks. My initial thought when I was upgrading the vb6 code was to replace all error handling with a simple Try - Catch around the Sub Main entry point, as below:
Public Sub Main()
Try
Init()
catch
'do stuff
end try
End Sub
public function Init() As boolean
init = true
end function
as any errors in the program would be caught in this way and I could handle them all in one Try - Catch.
However I then realised that, that would not make the function above return a value of False when an error occurred. If I still want this functionality do I have to wrap everything in Try blocks?
Since your concern is that you do not want the application to crash or break, Yes you can use Try cache block for that concern.
However, If you are talking about error handling in the whole application, then I would suggest that you think of a way to refactor the whole code.
Remove all the "On Error" statements and apply some new logic to handle the errors.
That logic could vary (Only logging, Retrying strategy Design pattern, etc) Think of all the expected errors and handle them accordingly.
If you need to do something special for errors in a particular function, then the function should have its own Try/Catch block to implement that behavior. For example:
Public Function Init() As Boolean
Try
'Presumably some other code goes here
Return True
Catch ex As Exception
Return False
End Try
End Function
Get rid of all the on Error steps and do the error handling globally
In the main_load put the three block below
' Get your application's application domain for error handling.
Dim currentDomain As AppDomain = AppDomain.CurrentDomain
' Define a handler for unhandled exceptions.
AddHandler currentDomain.UnhandledException, AddressOf MYExnHandler
' Define a handler for unhandled exceptions for threads behind forms.
AddHandler Application.ThreadException, AddressOf MYThreadHandler
and then add the two sub routines shown below
Private Sub MYExnHandler(ByVal sender As Object,
ByVal e As UnhandledExceptionEventArgs)
Dim EX As Exception
EX = e.ExceptionObject
If EX.StackTrace.Contains("SOMETHING") Then
My.Computer.FileSystem.WriteAllText(LogToWrite, "Error SOMETHING caught:" & EX.StackTrace & vbCrLf, True, System.Text.Encoding.Default)
MsgBox("error caught. Contact **XXX** for assistance!" & vbCrLf & vbCrLf & "Error: " & vbCrLf & EX.StackTrace,, "Fatal Error")
End If
End Sub
Private Sub MYThreadHandler(ByVal sender As Object,
ByVal e As Threading.ThreadExceptionEventArgs)
If e.Exception.StackTrace.Contains("SOMETHING") Then
My.Computer.FileSystem.WriteAllText(LogToWrite, "Error SOETHING caught:" & e.Exception.StackTrace & vbCrLf, True, System.Text.Encoding.Default)
MsgBox("Error caught. Contact **xxx** for assistance!" & vbCrLf & vbCrLf & "Error: " & vbCrLf & e.Exception.StackTrace,, "Fatal Error")
End If
End Sub
You can just check the content of the errors and respond accordingly to every single error with a Case Array..

VB.net program hangs when asked to read .txt

I am attempting to read a .txt file that I successfully wrote with a separate program, but I keep getting the program stalling (aka no input/output at all, like it had an infinite loop or something). I get the message "A", but no others.
I've seen a lot of threads on sites like this one that list all sorts of creative ways to read from a file, but every guide I have found wants me to change the code between Msgbox A and Msgbox D. None of them change the result, so I'm beginning to think that the issue is actually with how I'm pointing out the file's location. There was one code (had something to do with Dim objReader As New System.IO.TextReader(FileLoc)), but when I asked for a read of the file I got the file's address instead. That's why I suspect I'm pointing to the .txt wrong. There is one issue...
I have absolutely no idea how to do this, if what I've done is wrong.
I've attached at the end the snippet of code (with every single line of extraneous data ripped out of it).
If it matters, the location of the actual program is in the "G01-Cartography" folder.
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadMap("Map_Cygnus.txt")
End Sub
Private Sub LoadMap(FileLoc As String)
FileLoc = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\" + FileLoc
MsgBox("A")
Using File As New StreamReader(FileLoc)
MsgBox("B")
Dim WholeMap = File.ReadLine()
MsgBox("C")
End Using
MsgBox("D")
End Sub
What does running this show you in the debugger? Can you open the Map_Cygnus.txt file in Notepad? Set a breakpoint on the first line and run the program to see what is going on.
Private BaseDirectory As String = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\"
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim WholeMap = File.ReadAllText(Path.Combine(BaseDirectory, "Map_Cygnus.txt"))
Debug.Print("Size Of Map: {0}", WholeMap.Length)
End Sub
It looks like you're using the correct methods/objects according to MSDN.
Your code runs for me in an new VB console app(.net 4.5)
A different approach then MSGBOXs would be to use Debug.WriteLine or Console.WriteLine.
If MSGBOX A shows but not B, then the problem is in constructing the stream reader.
Probably you are watching the application for output but the debugger(visual studio) has stopped the application on that line, with an exception. eg File not found, No Permission, using a http uri...
If MSGBOX C doesn't show then problem is probably that the file has problems being read.
Permissions?
Does it have a Line of Text?
Is the folder 'online'
If MSGBOX D shows, but nothing happens then you are doing nothing with WholeMap
See what is displayed if you rewite MsgBox("C") to Debug.WriteLine("Read " + WholeMap)
I have a few suggestions. Firstly, use Option Strict On, it will help you to avoid headaches down the road.
The code to open the file is correct. In addition to avoiding using MsgBox() to debug and instead setting breakpoints or using Debug.WriteLine(), wrap the subroutine in a Try...Catch exception.
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadMap("Map_Cygnus.txt")
End Sub
Private Sub LoadMap(FileLoc As String)
Try
FileLoc = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\" + FileLoc
MsgBox("A")
Using File As New StreamReader(FileLoc)
MsgBox("B")
Dim WholeMap = File.ReadLine() 'dimming a variable inside a block like this means the variable only has scope while inside the block
MsgBox("C")
End Using
MsgBox("D")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Note that you normally should only catch whatever exceptions you expect, but I generally catch everything while debugging things like this.
I would also like to point out that you are only reading one line out of the file into the variable WholeMap. That variable loses scope as soon as the End Using line is hit, thereby losing the line you just read from the file. I'm assuming that you have the code in this way because it seems to be giving you trouble reading from it, but thought I would point it out anyway.
Public Class GameMain
Private WholeMap As String = ""
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadMap("Map_Cygnus.txt")
End Sub
Private Sub LoadMap(FileLoc As String)
Try
FileLoc = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\" + FileLoc
Using File As New StreamReader(FileLoc)
WholeMap = File.ReadLine() 'dimming the variable above will give all of your subs inside class Form1 access to the contents of it (note that I've removed the Dim command here)
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

vb.net timer and exception (try... catch) and memory leak

Scenario:
I've hundreds of applications instances running on client machines doing a certain job. Something like a cloud app.
Objective: When an error occur in any of them i want to report the error to an error-log database an quit silently the app to avoid user annoyance.
The problem:
I've migrate to VB.NET recently and don't know yet wich is the best aproach to error handle the code. Those instances are runing a routine under a timer.
Private Sub timerLifeSignal_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerLifeSignal.Tick
MAINSUB()
End Sub
Friend Sub MAINSUB()
frmSAN.timerLifeSignal.Enabled = False
...
'do the job
...
frmSAN.timerLifeSignal.Enabled = True
end sub
At first glance i've put try/catch into every single function but it leads to a memory leak since, AFIK, the exception object created was not disposed correctly.
So is there a way to make try/catch do not memory leak under these circumstances?
Thx,
UPDATE:
Basically what i was doing is something like:
Private Sub timerLifeSignal_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerLifeSignal.Tick
MAINSUB()
End Sub
Friend Sub MAINSUB()
Try
frmSAN.timerLifeSignal.Enabled = False
...
'do the job
...
frmSAN.timerLifeSignal.Enabled = True
Catch ex as Exception : gERRFUNC(" | MAIN | " & ex.Message) : End Try
end sub
friend sub dothejob
try
...
' really do the job
...
Catch ex as Exception : gERRFUNC(" | MAIN | " & ex.Message) : End Try
end sub
and so on... and finally (may here it's my mistake) another try/catch nested into here:
Public Sub gERRFUNC(Optional ByVal errorMSG As String = "")
Try
' log message on database
SQL = "INSERT INTO sanerrorlog VALUES (NULL, '" & currentMySQLTime() & "', '" & errorMSG & "');"
' function that open conn and execute the sql... working fine
' NOTE THAT INSIDE THE DORS FUNCTION THERE'S ALSO A TRY/CATCH USING THE SAME EX OBJECT.
DORS(SQL)
' clean up things
SQL = "DELETE FROM sannie WHERE sid=" & gMyID
DORS(SQL)
For i = 0 To UBound(gCONN)
If gCONN(i).State = ConnectionState.Open Then gCONN(i).Close()
Next
frmSAN.nfi.Visible = False
gWWB = Nothing
End
Catch E As Exception: End: End Try
End Sub
So... if i do this:
Private Sub timerLifeSignal_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerLifeSignal.Tick
Try
MAINSUB()
Catch ex as Exception : gERRFUNC(" | MAIN | " & ex.Message) : End Try
End Sub
Means all exceptions inside mainsub should be catched?
You have another way..
You can attach events to the app domain and main thread, in case it fails, to catch the errors.
Something like:
AppDomain.CurrentDomain.UnhandledException +=
CurrentDomain_UnhandledException;
Application.ThreadException +=
Application_ThreadException;
Application.ApplicationExit += Application_ApplicationExit;
with this in mind, every time an exception occurs, anywhere that it hasn't a catch by itself, will fall trough any of this ones...
Try/Catches by themselves don't cause memory leaks. Not finalizing something after a failure, which triggers a catch can however. By removing your try/catches, you've apparently exposed something else that does finalize, even though informally, the object which was causing a memory leak.
Ask yourself this, how could a directive in your code cause a memory leak? Try, nor Catch are references to an object, and thus could not cause memory consumption issue by themselves -- only by the logical path of the code they control.
Just for reference the memory leak problem occurs because of nested try/catch loops wich (by my mistake) uses the same variable as exception object.
To be more clear take the following example:
Public Sub gERRFUNC(Optional ByVal errorMSG As String = "")
Try
// do something wrong here
Catch E As Exception: gERRFUNC(ex.Message): End Try
End Sub
friend Sub gERRFUNC(msg as string)
Try
// call another external sub (wich eventually may also throw an execption)
// take note that the var 'E' is also referenced here and everywhere
// so as 'E' is set it enters on a Exception loop causing the 'memory leak' problem.
Catch E as Exception: End: End Try
End Sub
By removing the nested try/catch or by using a well structured error 'flow' may avoid these type of problem.
Best Regards,
Paulo Bueno.

VB.NET Cross-thread operation not valid

I have a loop (BackgroundWorker) that is changing a PictureBox's Location very frequently, but I'm getting an error -
Cross-thread operation not valid: Control 'box1' accessed from a thread other than the
thread it was created on.
I don't understand it at all, so I am hoping someone can help me with this situation.
Code:
box1.Location = New Point(posx, posy)
This exception is thrown when you try to access control from thread other than the thread it was created on.
To get past this, you need to use the InvokeRequired property for the control to see if it needs to be updated and to update the control you will need to use a delegate. i think you will need to do this in your backgroundWorker_DoWork method
Private Delegate Sub UpdatePictureBoxDelegate(Point p)
Dim del As New UpdatePictureBoxDelegate(AddressOf UpdatePictureBox)
Private Sub UpdatePictureBox(Point p)
If pictureBoxVariable.InvokeRequired Then
Dim del As New UpdatePictureBoxDelegate(AddressOf UpdatePictureBox)
pictureBoxVariable.Invoke(del, New Object() {p})
Else
' this is UI thread
End If
End Sub
For other people which coming across this error:
Try the dispatcher object: MSDN
My code:
Private _dispatcher As Dispatcher
Private Sub ThisAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
_dispatcher = Dispatcher.CurrentDispatcher
End Sub
Private Sub otherFunction()
' Place where you want to make the cross thread call
_dispatcher.BeginInvoke(Sub() ThreadSafe())
End Sub
Private Sub ThreadSafe()
' here you can make the required calls
End Sub

Variable is not declared; it may be inaccessible due to its protection level

Today I decided to come up with a program that would be useful for me in VB.net (I have never coded in VB.net before). All is going fine up till this point but I have hit a snag with the error mentioned above. The problem is with the windowssevenexistsonsource boolean under the get get of profiles comment. I will also take any code criticism well as I would like to get out of bad practices before I start! (the sub does end but I have not included that code)
Code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'Check that the entries required are not empty
If String.IsNullOrEmpty(sourceipaddress.Text) Or String.IsNullOrEmpty(destinationipaddress.Text) Then
MsgBox("Source or destination IP address is empty")
Exit Sub
End If
'First we need to establish the operating system of the source and destination
Try
Dim windowssevenexistsonsource As Boolean = IO.Directory.Exists("\\" & sourceipaddress.Text & "\c$\users")
Dim windowssevenexistsondestination As Boolean = IO.Directory.Exists("\\" & sourceipaddress.Text & "\c$\users")
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
'Now we need to get a list of profiles in the relevant directory and put them into an array
'Declare variables and empty the array
Dim Sourcedirectorylistarray, destinationdirectorylistarray As String()
Dim sourcedirectoryentry, destinationdirectoryentry As String
Dim Sourcerootpath, destinationrootpath As String
'Get List of Profiles
Try
If windowssevenexistsonsource = True Then
Sourcedirectorylistarray = System.IO.Directory.GetDirectories("\\" & sourceipaddress.Text & "\c$\users\")
destinationdirectorylistarray = System.IO.Directory.GetDirectories("\\" & destinationipaddress.Text & "\c$\users\")
Else
MsgBox("test")
End If
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
In declaring your variables windowssevenexitsonsource and windowssevenexistsondestination in your try block you are limiting their scope to the try block. Try declaring them at the beginning of your subroutine.