Picked up a legacy VB.NET project originally written for version 1.1 of the .NET framework. I'm running Vista with .NET 3.5. I have cleared out all the original error and the project will build; it just wont run.
As far as I can tell, it is trying to run 'LoginForm' but putting breakpoints in doesn't work because the error is thrown before the breakpoints are reached, regardless of where in the file they are placed.
Really can't work out what to do! Any help appreciated.
StackTrace:
System.IndexOutOfRangeException was unhandled
Message="Index was outside the bounds of the array."
Source="FirstLine"
StackTrace:
at FirstLine.LoginForm.main()
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
EDIT: Terribly sorry, didn't appreciate the code would be of much use because the issue is more that I can't get to it. However, here's the main function:
Shared Sub main()
Dim p As Process() = Process.GetProcessesByName("FirstLine")
If p.Length = 1 Then
'START COPYMINDER
'Dim expirydate As Date = CDate("01/01/1970")
'Dim expiry As Integer
'Try
' GetCopyMinderExpiryDate(expiry)
' If Not expiry = 0 And Not expiry = 1 Then
' expirydate = expirydate.AddSeconds(expiry)
' Dim diff As Integer = DateDiff(DateInterval.Day, Date.Now, expirydate)
' If diff >= 0 And diff 0 Then
' DisplayError((ret_code))
' End
'End If
'Dim did As String
'GetCopyMinderDeveloperID(did)
'If did "IT" Then
' MessageBox.Show("Invalid Developer ID " & did & ". Firstline will now shutdown", "Firstline", MessageBoxButtons.OK, MessageBoxIcon.Error)
' End
'End If
'END COPYMINDER
Dim lf As New LoginForm
If LoginSettings.setting("loginShowErrorOnLine") = "TRUE" Then
lf.ShowDialog()
Else
Try
lf.ShowDialog()
Catch ex As Exception
MsgBox(ex.Message)
Config.UnlockByUser(Config.currentUser.username)
Config.currentUser.UserLoggedOff()
End Try
End If
Else
Dim prc As Process = p(0)
SwitchToThisWindow(prc.MainWindowHandle, True)
End If
End Sub
Thanks for your responses so far. It's encouraging to see such a helpful community!
Dim prc As Process = p(0) is your problem as it is in the else statements where the the array length can be anything but 1 (0 for instance).
when the length is 0 it will give you the IndexOutOfRange when you try to access the first element.
Try turning on debug build; this will give you the possibility to add breakpoints and will also give you some row numbers at the stack trace.
Your problem is that you are not handling the case where p.Length = 0. This occurs if there is no process with the name "FirstLine".
Have you also renamed your process / application ?
Related
Some people -- perhaps gullibly -- believe that there are multiple ways of being a catskinner.
When my attempt to search all the Controls on a Page for Checkboxes continued to fail ignominiously (for proof of that, see this), I thought maybe I could just look at the ID of the Control, rather than care what type of control it was at heart.
So, I commented out this line:
If TypeOf cntrl Is System.Web.UI.WebControls.CheckBox Then
...and tried this instead:
If cntrl.ID.ToString().Contains("ckbx")
But I fared no better, and received this coldwater slap:
Server Error in '/EMS/customerreportingnet' Application.
--------------------------------------------------------------------------------
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 69: LabelDebug.Text = LabelDebug.Text+" "+cntrl.GetType().ToString+" "
Line 70: 'If TypeOf cntrl Is System.Web.UI.WebControls.CheckBox Then
Line 71: If cntrl.ID.ToString().Contains("ckbx")
Line 72: 'Dim objAsConvertible As IConvertible = TryCast(cntrl, IConvertible)
Line 73: 'If objAsConvertible Is Nothing Then
Source File: C:\EnhancedMonthlySalesReporting\customerreportingnet\customerreportingnet\pages\custmaint_categoryadmin.aspx.vb Line: 71
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
pages_custmaint_categoryadmin.Button1_Click(Object sender, EventArgs e) in C:\EnhancedMonthlySalesReporting\customerreportingnet\customerreportingnet\pages\custmaint_categoryadmin.aspx.vb:71
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +114
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +139
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +28
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2980
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.5485; ASP.NET Version:2.0.50727.5491
Why is it that the control, which obviously exists, throws an exception as if there is no reference to it?
The entire block of code is:
Dim coName As String
Dim argVals(2) As String
Dim _Unit As String
Dim _MemberNo As String
Dim _CustNo As String
Dim curCheckboxIDVal As String
For Each cntrl As Control In Me.Controls
'If TypeOf cntrl Is System.Web.UI.WebControls.CheckBox Then
If cntrl.ID.ToString().Contains("ckbx")
If DirectCast(cntrl, CheckBox).Checked = True Then
Label2.Text = "label 2 text from checked"
curCheckboxIDVal = CStr(DirectCast(cntrl, CheckBox).ID)
coName = GetLabelTextForID(curCheckboxIDVal)
argVals = GetArgValsForCompanyName(coName)
_Unit = argVals(0)
_MemberNo = argVals(1)
_CustNo = argVals(2)
Label2.Text = _Unit
LabelDebug.Text = _MemberNo
Using conn As New SqlConnection(connStr), _
cmd As New SqlCommand(upd8DML, conn)
cmd.Parameters.Add("#Unit", SqlDbType.VarChar, 50).Value = _Unit
cmd.Parameters.Add("#MemberNo", SqlDbType.VarChar, 50).Value = _MemberNo
cmd.Parameters.Add("#CustNo", SqlDbType.VarChar, 50).Value = _CustNo
conn.Open()
cmd.ExecuteScalar()
End Using
End If
End If
Next
To get to the line that's throwing the error, cntrl has to be a valid Control in the Me.Controls collection; I reckon all Controls have an ID property. So why that err is being thrown on that line makes little, if any, sense to me.
the problem is in here:
If cntrl.ID.ToString().Contains("ckbx")
cntrl.ID seems to be null.
Try to debug to see what value you have in your cntrl.ID.ToString()
Checking if value is Null:
If String.IsNullOrEmpty(cntrl.ID) then exit For
or
If cntrl.ID Is Nothing Then exit For
The fix ended up being simple, and even logical, in hindsight.
The controls are dynamically added to the form, like so:
formCustCatMaint.Controls.Add(coName)
And so, replacing this line, in the loop:
For Each cntrl As Control In Me.Controls
...with this:
For Each cntrl As Control In formCustCatMaint.Controls
And this line, in the GetLabelTextForID() function:
For Each cntrl As Control In Me.Controls
...with this:
For Each cntrl As Control In formCustCatMaint.Controls
...did the trick. The controls are being found, and the code is working as designed/originally expected.
Nebenbei bemerkt, this also works fine now:
If TypeOf cntrl Is CheckBox Then
Enviroment: vb.net visual studio 10 - win forms
The Error:
{"Cannot access a disposed object. Object name:'frmInfo'."}
StackTrace:
at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
at HorizonRealTime.UI.frmInfo.UpdateGUI(cHorizonColoredString strdata) in R:\csavb2010dlls\Test\TestSoloutions\StoreAutoStuff\HorizonRealTimeVB10\CommanderRealTime.UI\frmInfo.vb:line 93
at HorizonRealTime.UI.frmInfo.DoWork() in R:\csavb2010dlls\Test\TestSoloutions\StoreAutoStuff\HorizonRealTimeVB10\CommanderRealTime.UI\frmInfo.vb:line 75
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Simple Explanation:
I have 1 main form with many child mdi forms.
One form(frminfo) manages all the status/error messages that server processes generate.
These messages get placed on a
Imports System.Collections.Concurrent
Public oStatusMsgs As BlockingCollection(Of String) = New BlockingCollection(Of String) 'thread safe collection
The problem occurs very rarely(usually just on application startup) when it enters the if me.invokerequired { me.Invoke(delegate)} I get a object disposed error when it tries to invoke itself.
even in debug the object is not flagged as disposed after the error occurs.
if I wrap the me.invoke in a try/catch... it procedes to process the following messages just fine.
Output in textbox ends up looking like this:
---Refreshing Data---
#Items Data Refreshed#
#Deps Data Refreshed#
Real-Time Info - Error Displaying GUI Info - #Units Data Refreshed# - Cannot access a disposed object. Object name: 'frmInfo'.
#Retail Data Refreshed#
#Tax Data Refreshed#
---Exiting Data Refresh---
Whats funny is that this textbox is on frminfo that im copying the text out of.
Whats even stranger is. It is actually processing messages prior to getting this error. So the disposed error exception seems to be a false reading, and something else is actually occurring.
On frminfo is a low-priority thread that loops infinitely basically like this
Private sub DoStuff() 'this is kicked off from the frminfo.onload event as a new thread that is referenced by frminfo
dim strdata as string = nothing
do while active
If Me.frmparent.oStatusMsgs.Count > 0 Then
Me.frmparent.oStatusMsgs.TryTake(strdata, 300)
If Not strdata Is Nothing Then
Call me.UpdateGUI(strdata)
End If
strdata = Nothing
End If
thread.sleep(50)
loop
End sub
Private Sub UpdateGUI(ByVal strdata As string)
If Me.InvokeRequired Then
Try
Me.Invoke(New UpdateGUIDelegate(AddressOf UpdateGUI), New Object() {strdata})
Catch ex As Exception
Me.frmparent.oErrorMsgs.Add(Me.Text & " - Error Displaying GUI Info - " & strdata & " - " & ex.Message)
End Try
Else
'this is where it would append the strdata to some kind of textbox or other form level control
end if
end sub
On the main UI thread I do create addition references to this mdi child form.
The first is a collection I add every mdi child form to. I let the GC handle this entirely other then the add.(I do this to ensure my forms are not disposed of)
There is also a collection of forms that I use to sort the mdi childs. The
in some cases i do like
dim otmpinfofrm as form = frmcollection(i)
frmcollection(i) = nothing 'where this is where frminfo currently resides in the collection
frmcollection(i) = frmcollection(i+1)
I loop through the collection and at the end i put back in the reference to
frmcollection(lastindex) = otmpinfofrm
I dont think this sorting could impact the thread calling me.invoke to update a local control. Since Im just sorting references?
Any help would be appreciated regarding better use of the me.invoke to avoid this error from happening at all.
Please take a look at this code. For some reason that I can't figure out, the File.Delete() line isn't getting fired and I'm not getting an error.
' hard-coded for testing
Dim path As String = "C:\Program Files (x86)\Test\Program\Program.exe"
Dim appDir As String = My.Application.Info.DirectoryPath
Dim iniPath As String = appDir & "\config.ini"
Dim outputPath As String = appDir & "\output.ini"
Dim textLine As String = ""
Dim reader = File.OpenText(iniPath)
Dim writer = New StreamWriter(outputPath)
' Read the lines in the ini file until the pathToExecutable line is found and write the path to that line
While (InlineAssignHelper(textLine, reader.ReadLine())) IsNot Nothing
If textLine.StartsWith("pathToExecutable=") Then
writer.WriteLine("pathToExecutable=" & path)
Else
writer.WriteLine(textLine)
End If
End While
reader.Dispose()
reader.Close()
writer.Dispose()
writer.Close()
File.Copy(outputPath, iniPath, True)
File.Delete(outputPath) ' THIS ISN'T GETTING FIRED
Return path
You stated that you are not getting an error, but if you don't implement exception handling, you're most probably getting errors and throwing them away (pun intended).
Use a try/catch around any of your System.IO.File operations, and even more, you can implement specific handles and catch specific exceptions.
Try
File.Copy(outputPath, iniPath, True)
File.Delete(outputPath) ' THIS ISN'T GETTING FIRED
Catch ioException As IOException
'The specified file is in use.
MessageBox.Show(ioException.Message)
Catch ex As Exception
'Some other error apart for file in use.
MessageBox.Show(ex.Message)
End Try
Ericosg's suggestion about using a try/catch lead me to the issue: I had the file open in a streamreader earlier in my code, but never closed it there.
I really can not understand why the exception is triggered.
I created this code that performs some checks for the correctness of the license.
The function isittrial occurs if the trial software is creating a hidden file, this file is then checked with File.exist.
The problem is the following:
the file is created by isittrial but for some strange reason you enable the exception of file.exist, what can I do to fix it?
I really can not understand why it does not work.
isittrial() 'this function make the file to check
Dim percorsoCompleto As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
Try
If My.Computer.FileSystem.FileExists(directory) Then
Dim fileReader As String
Dim dire As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
fileReader = My.Computer.FileSystem.ReadAllText(directory,
System.Text.Encoding.UTF32)
Dim check = DeCryptIt(fileReader, "aspanet")
Dim datadecripted As String = DeCryptIt(Registry.GetValue("HKEY_CURRENT_USER\Software\cc", "end", ""), "aspanet")
If Date.Now < check And check <> datadecripted Then
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
Else
End If
Else
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
End If
Catch ex As Exception
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
'DeActivate()
'ForceActivation()
End Try
This line
If My.Computer.FileSystem.FileExists(directory) Then
seems to test for the existence of a file passing the name of a directory (or an empty string or whatever, we can see how this variable is initialized). In every case the result will be false.
Then your code jumps to an else block with the same error message of the exception fooling your perception of the error.
Try instead
Dim percorsoCompleto As String = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
percorsoCompleto = Path.Combine(percorsoCompleto, "Software", "cc.txt")
Try
If My.Computer.FileSystem.FileExists(percorsoCompleto) Then
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(percorsoCompleto,
System.Text.Encoding.UTF32)
.....
Notice that I have removed the path concatenation with a more fail safe call to Path.Combine
I'm working on a project for school in which a dll is loaded.
The dll that is loaded is a bridge between my program and the Twincat System Manager which forms the bridge between the computer and a PLC via the local network.
I need to read Variables trough this whole chain from the plc to my program.
This is the way I do this:
Public Function adsReadReal(ByVal Variabelenaam As String) As Single
Dim ds = New TwinCAT.Ads.AdsStream(4 * 8) ' new data stream
Dim br = New System.IO.BinaryReader(ds) 'new binary
Dim hVar = New Integer
Try
ConState(1)
tcclient = New TcAdsClient
ConState(2)
tcclient.Connect(Form1.amsAdress, 801) 'connects the tcclient to the PLC
hVar = tcclient.CreateVariableHandle(Variabelenaam) 'creats a handle for the variable
tcclient.Read(hVar, ds) 'read it
ConState(5)
Return br.ReadSingle() 'convert it from binary to readable for vb
Catch ex As Exception
ConState(0)
PrintEx(ex) 'print out the exception
finally
tcclient.Dispose() 'make the object stop being used to prevent a lingering connection
End Try
Return False
End Function
Now the program loads a dll called TwinCAT.ADS.dll at the start of the connection module. If the Twincat system manager is running the program ends normally, but when it is not it crashes and gives me this error:
System.DllNotFoundException was unhandled
Message="Kan DLL tcadsdll.dll niet laden: Kan opgegeven module niet vinden. (Uitzondering van HRESULT: 0x8007007E)"
Source="TwinCAT.Ads"
TypeName=""
StackTrace:
bij TwinCAT.Ads.Internal.TcAdsDllWrapper.TcAdsDll.AdsAmsUnRegisterRouterNotification()
bij TwinCAT.Ads.Internal.TcAdsDllWrapper.AmsUnRegisterRouterNotification(Boolean
throwAdsException)
bij TwinCAT.Ads.Internal.TcLocalSystem.Dispose(Boolean disposing)
bij TwinCAT.Ads.Internal.TcLocalSystem.Finalize()
which is roughly translated to:
Cannot load DLL tcadsdll.dll: Cannot find given module. (Exception at
HRESULT: 0x8007007E)
This is not a dll that I have imported, so it must be from the TwinCAT.ADS.dll
How can I prevent the program from throwing this error at me and instead close the program peacefully? I have tried to catch all the exceptions of every dll related operation possible.
Also the source is on Bitbucket. I will make it public on request.
Some links on the official but quite unhandy Beckhoff site:
http://infosys.beckhoff.com/espanol.php?content=../content/1034/tcquickstart/html/tcquickstart_samplevisualbasicnet.htm&id=10449
Edit:
Apparently using tcclient.dispose() causes the error since the finnaly statement was use instead of just after the try block
Edit: This currently catches the exception but it does not handle it.
Dim currentDomain As AppDomain = AppDomain.CurrentDomain
AddHandler currentDomain.UnhandledException, AddressOf MyHandler
Dim tick As Byte = 0
Sub MyHandler(sender As Object, args As UnhandledExceptionEventArgs)
Dim ex As Exception = DirectCast(args.ExceptionObject, Exception)
MsgBox("exception tick" & Str(tick))
tick = tick + 1
PrintEx(ex)
End Sub
Edit:
The exception isn't caught properly because in vs2008 a couple of errors occurs but the tick appears after I press F5 (continue)
When the program is run directly, I only see 1 Tick. Then windows gives an error.
Did you try an unhandled exception handler?
Dim currentDomain As AppDomain = AppDomain.CurrentDomain
AddHandler currentDomain.UnhandledException, AddressOf MyHandler
Sub MyHandler(sender As Object, args As UnhandledExceptionEventArgs)
Dim e As Exception = DirectCast(args.ExceptionObject, Exception)
Console.WriteLine("MyHandler caught : " + e.Message)
End Sub