Exception unhandled within Application.Designer.vb - vb.net

I have another issue:
I am able to build my VB.NET application. However, when I go to debug it, I get an unhandled exception:
System.InvalidOperationException occurred HResult=0x80131509
Message=An error occurred creating the form. See
Exception.InnerException for details. The error is: Object reference
not set to an instance of an object. Source=ProovePC StackTrace:
at ProovePC.My.MyProject.MyForms.Create__Instance__[T](T Instance) in
:line 190 at ProovePC.My.MyProject.MyForms.get_Front1() at
ProovePC.My.MyApplication.OnCreateMainForm() in
C:\Users\Phillip\source\Workspaces\Upwork
Projects\ProoveIt\ProovePC\My Project\Application.Designer.vb:line 35
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[]
commandLine) at ProovePC.My.MyApplication.Main(String[] Args) in
:line 81
Inner Exception 1: NullReferenceException: Object reference not set to
an instance of an object.
The odd part is that it occurs in auto-generated code, in the Application.Designer.vb file. I have confirmed that the constructor is public and that the name of the form matches the name within this file:
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = true
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterAllFormsClose
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.ProovePC.Front1 'Error occurs here?
End Sub
End Class
End Namespace
I am a little lost on this since I am new VB.NET, but I would like to think that the fix is a simple one. For those wondering, I am running visual studio 2017. I should note that I come from a C# background and recently got into vb.net. So please, explain as much as possible.
Edit:
Form Constructor:
Public Sub New()
' This call is required by the designer.
'NewMethod()
InitializeComponents()
' Add any initialization after the InitializeComponent() call.
End Sub
Edit:
Ok so here is the interesting part, now I am getting the error on the InitializeComponents function itself within the auto generated constructor of the form. Once I comment this function out, I am able to build and run the application. I only get so far because that application needs hardware to fully run which I have not connected yet.
Now, here is the interesting part, if I were to comment out the constructor, there is a line above it that comes back as undefined reference error:
Public MainStatus As StatusStrip = StatusStrip1 'Error is here now
'Public Sub New()
' This call is required by the designer.
'InitializeComponent()
' Add any initialization after the InitializeComponent() call.
'End Sub
For those wondering, I am now in the front1.vb file

there was a property within the form control that was being set to nothing when it needs to be set to Me.
As for the random line of code, Public MainStatus As StatusStrip = StatusStrip1 I think that it was accidentally copy pasted there as the variable is only used at that line. I commented it out and everything builds good now.

Related

BC30521 error on opening a form VS 2017 vb.net

I have a vb.net winforms project and after opening a form that has code that has the following line
Dim ChildForm As frmItemInstallation = New frmItemInstallation
I am getting the following error message:
Overload resolution failed because no accessible 'New' is most specific for these arguments: 'Public Sub New()': Not most specific. 'Friend Sub New()': Not most specific
I wasn't getting this in the past, just started when I reopened the project to make changes
this is on an existing form in the project, if I create a new form, I don't get the error message
I am using VS 2017 runtime is 4.6.1
Any help would greatly be appreciated
Public Class frmInventory
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub

Events and exceptions in 3-layer architecture

I have another question considering events and exceptions
A small introduction to my project: I'm working in a 3 layer architecture, so I have a GUI(form), BLL(Business logic layer) and a DAL(data acces layer).
So my GUI is linked to a BLL which is connected to several DAL classes. For example my BLL has a class clsCSV (which reads and writes CSV files)
I now want to raise events and/or catch exceptions from this class to inform the user and log exceptions. There are 3 events: "ErrorLoad", "ErrorWrite", "Ready"
Public Class clsCSV
Public Sub New()
End Sub
Public Function Load(sFilePath As String)
Dim oFileHelper As New DelimitedFileEngine(Of clsItem)
Dim oList As New List(Of clsItem)
' Load a CSV file
Try
oList = oFileHelper.ReadFileAsList(sFilePath)
Catch ex As Exception
'RaiseEvent ErrorLoad("")
clsErrorLog.Log(ex)
Finally
End Try
' If the list is empty return nothing
If Not IsNothing(oList) Then
Return oList
Else
Return Nothing
End If
End Function
Public Sub Write(sFilePath As String, oList As List(Of clsTranslatedItem))
Dim oFileHelper As New DelimitedFileEngine(Of clsTranslatedItem)
oFileHelper.WriteFile(sFilePath, oList)
RaiseEvent Ready()
End Sub
Public Event ErrorLoad(ByVal sender As Object, ByVal e As EventArgs)
Public Event ErrorWrite(sMessage As String)
Public Event Ready()
End Class
There is a try-catch in my public sub load which catches any exception and logs it to a text file by calling clsErrorLog.log(ex) which then calls this class and logs the error:
Public Shared Sub Log(ex As Exception)
Try
Dim oBestand As New System.IO.StreamWriter(My.Computer.FileSystem.SpecialDirectories.Desktop & "\ErrorLog.txt", True)
If Not IsNothing(oBestand) Then
oBestand.WriteLine("")
oBestand.WriteLine(My.Computer.Clock.LocalTime.ToString)
oBestand.WriteLine(ex.Message)
oBestand.WriteLine(ex.StackTrace)
oBestand.WriteLine("_________________________________________")
oBestand.Close()
End If
Catch exc As Exception
End Try
End Sub
This works fine, but now I want to inform the user that an error occured, so I was thinking to raise an event called "ErrorLoad" (in clsCSV) and catch this in my BLL. But what can I do then? Add a sub that handles this event, which then raises an event in the BLL, caught by the GUI? or is this a long way to this?
I also want to do this for the other events offcourse. But the whole event system in the layered architecture is a bit confusing.
Anyone who can enlighten me?
Thanks in advance!
Without knowing the implementation details of your UI, I can only give you some general advice.
You need some kind of two directional communication between your GUI and your BLL. For example in WPF this is usually done using INotifyPropertyChanged interface and the event it defines.
So the BLL raises a event and the GUI is listening. The basically only has the task of informing the GUI that it has to check a specific property or function or anything like this from the BLL. The rest is up to the GUI to do so and inform the user.
I wouldn't do that using exceptions. These are there to handle the error path of specific functions. This path is done once your BLL noticed the error and prepared it for the UI handling.

how to pass commandlinearguments from to a Running Application [duplicate]

I have already implemented context menu to appear when a user right-clicks a file in windows explorer using Registry. The file address will be passed to the application as command lines. Parsing it is no problem.
How can I implement that is similar to "Add To Windows Media Player Playlist"? It does not open another instance of the app but works on the same open window and adds it to a list?
There are 2 ways to do this depending on how your app starts.
Method 1: Using VB App Framework and a MainForm
This is the easiest because you mainly just need to add some code for an Application event. First, add a method to your main form to receive new arguments from subsequent instances of your app:
Public Class MyMainForm ' note the class name of the form
...
Public Sub NewArgumentsReceived(args As String())
' e.g. add them to a list box
If args.Length > 0 Then
lbArgs.Items.AddRange(args)
End If
End Sub
Next:
Open Project Properties
Check the "Make Single Instance" option
At the bottom, click View Application Events
This will open a new code window like any other; Select MyApplication Events in the left drop down; and StartupNextInstance in the right one.
Here, we find the main form and send the command line arguments to the method we created:
Private Sub MyApplication_StartupNextInstance(sender As Object,
e As ApplicationServices.StartupNextInstanceEventArgs) _
Handles Me.StartupNextInstance
Dim f = Application.MainForm
' use YOUR actual form class name:
If f.GetType Is GetType(MyMainForm) Then
CType(f, MyMainForm).NewArgumentsReceived(e.CommandLine.ToArray)
End If
End Sub
Note: Do not try to fish the main form out of Application.OpenForms. A few times I've had it fail to find an open form in the collection, so I have quit relying on it. Application.MainForm is also simpler.
That's it - when a new instance runs, its command line args should be passed to the form and displayed in the listbox (or processed however your method sees fit).
Method 2: Starting From Sub Main
This is more complicated because starting your app from a Sub Main means that the VB Application Framework is not used, which provides the StartupNextInstance event. The solution is to subclass WindowsFormsApplicationBase to provide the functionality needed.
First, give your main form a meaningful name and add something like the NewArgumentsReceived(args As String()) as above.
For those not aware, here is how to start your app from Sub Main():
Add a module named 'Program' to your app
Add a Public Sub Main() to it.
Go to Project -> Properties -> Application
Uncheck Enable Application Framework
Select your new "Sub Main" as the Startup Object
The module can actually be named anything, Program is the convention VS uses for C# apps. The code for Sub Main will be later after we create the class. Much of the following originated from an old MSDN article or blog or something.
Imports Microsoft.VisualBasic.ApplicationServices
Imports System.Collections.ObjectModel
Public Class SingleInstanceApp
' this is My.Application
Inherits WindowsFormsApplicationBase
Public Sub New(mode As AuthenticationMode)
MyBase.New(mode)
InitializeApp()
End Sub
Public Sub New()
InitializeApp()
End Sub
' standard startup procedures we want to implement
Protected Overridable Sub InitializeApp()
Me.IsSingleInstance = True
Me.EnableVisualStyles = True
End Sub
' ie Application.Run(frm):
Public Overloads Sub Run(frm As Form)
' set mainform to be used as message pump
Me.MainForm = frm
' pass the commandline
Me.Run(Me.CommandLineArgs)
End Sub
Private Overloads Sub Run(args As ReadOnlyCollection(Of String))
' convert RO collection to simple array
' these will be handled by Sub Main for the First instance
' and in the StartupNextInstance handler for the others
Me.Run(myArgs.ToArray)
End Sub
' optional: save settings on exit
Protected Overrides Sub OnShutdown()
If My.Settings.Properties.Count > 0 Then
My.Settings.Save()
End If
MyBase.OnShutdown()
End Sub
End Class
Note that the three main things the App Framework can do for us ("Enable XP Styles", "Make Single Instance" and "Save Settings on Exit") are all accounted for. Now, some modifications to Sub Main:
Imports Microsoft.VisualBasic.ApplicationServices
Imports System.Collections.ObjectModel
Module Program
' this app's main form
Friend myForm As MyMainForm
Public Sub Main(args As String())
' create app object hardwired to SingleInstance
Dim app As New SingleInstanceApp()
' add a handler for when a second instance tries to start
' (magic happens there)
AddHandler app.StartupNextInstance, AddressOf StartupNextInstance
myForm = New MyMainForm
' process command line args here for the first instance
' calling the method you added to the form:
myForm.NewArgumentsReceived(args)
' start app
app.Run(myForm)
End Sub
' This is invoked when subsequent instances try to start.
' grab and process their command line
Private Sub StartupNextInstance(sender As Object,
e As StartupNextInstanceEventArgs)
' ToDo: Process the command line provided in e.CommandLine.
myForm.NewArgumentsReceived(e.CommandLine.ToArray)
End Sub
End Module
The SingleInstanceApp class can be reused with any Sub Main style app, and the code in that method is mainly a copy-paste boilerplate affair except for perhaps the form reference and actual name of the NewArgumentsReceived method.
Testing
Compile the app, then using a command window, send some commandline arguments to the app. I used:
C:\Temp>singleinstance "First Inst" apple bats cats
This starts the app as normal, with the arguments shown. Then:
C:\Temp>singleinstance "Next Inst" ziggy zoey zacky
C:\Temp>singleinstance "Last Inst" 111 222 3333
It doesnt matter which approach you use - they both work the same. The Result:
Note that depending on security settings, your firewall may request permission for apps using either method to connect to other computers. This is a result of how an instance sends or listens for the arguments from others. At least with mine, I can deny permission to connect and everything still works fine.
#Plutonix solution is quite efficient and elegant.
However if you program goes through multiple Forms i.e. if the Main Form can change during program execution, for example if you have a login form and then a main form, or a sequence of non-modal forms, Application.MainForm won't always be the same form and may not be known beforehand (hard coded).
Plutonix code assumes it is known and hard codes it.
In this case, you may want to be able to receive the NewArguments at all times, in whichever form is active at the time in your application.
There are 2 solutions to extend Plutonix solution:
1) Repeatedly force Application.MainForm to a specific form in code (I haven't tested this but Application.MainForm is Read/Write so it could work).
2) The most elegant is to implement an Interface on all forms that can possibly become the MainForm:
Create the Basic interface:
Public Interface INewArgumentsReceived
Sub NewArgumentsReceived(args As String())
End Interface
Modify #Plutonix code for MyApplication_StartupNextInstance to:
Private Sub MyApplication_StartupNextInstance(sender As Object, e As ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
Dim f = Application.MainForm
If f.GetType.GetInterfaces.Contains(GetType(INewArgumentsReceived)) Then
CType(f, INewArgumentsReceived).NewArgumentsReceived(e.CommandLine.ToArray)
Else
MsgBox("The current program state can't receive new requests.",, vbExclamation)
End If
Now on all possible forms that can become the Main Form, implement the INewArgumentsReceived Interface:
Public Class FormA: Implements INewArgumentsReceived
Public Sub NewArgumentsReceived(args As String()) Implements INewArgumentsReceived.NewArgumentsReceived
MsgBox("Got new arguments")
End Sub
The other advantage of using the Interfaces is that we can check if the current Application.MainForm implements it and is able to receive it.
If the current Application.MainForm does not implement the Interface it fails gracefully with an informational message.

Error inside of Application.Designer.vb inside of OnCreateMainForm() Sub

I can't figure out what the issue is here. I started project from scratch, went to debug, and received error:
System.InvalidOperationException was unhandled Message=An error
occurred creating the form. See Exception.InnerException for details.
The error is: Object reference not set to an instance of an object.
I am not understand why this error is occurring in an auto-generated file. Here is the code in it's entirety:
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.269
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.AccountAndClientFull.frmMain 'HERE IS WHERE THE ERROR OCCURS
End Sub
End Class
End Namespace
Error occurs at:
Me.MainForm = Global.AccountAndClientFull.frmMain
Any suggestions? I can't figure out what changes need to be made in the application tab of the project properties.
I got the same error and realized it was because I had declared a private default constructor in the form code. If you created a constructor and didn't make it public, try making it public.
Make sure you have a Form Class called frmMain, attention not the file name but the Class Name.
Maybe you have renamed the Form file name to frmMain.vb but in the code of the file the signature of the class remains different.
Another possible cause of this error is if an exception occours in the event handlers of the controls of the forms during initialization.
The creation of the form fails and so an exception is raised.
Another possible cause of this symptom, and a particularly obscure one:
I added two LineShape controls to a child form in Designer and it caused the Me.MainForm error.
(Toolbox/Visual Basic PowerPacks/LineShape).
This point in the documentation may provide a clue:
"When you create a LineShape control at run time, you must also create a ShapeContainer and set the Parent property of the LineShape to the ShapeContainer."
I added the LineShapes using designer so it should have created the ShapeContainers automatically but that may have failed, perhaps because I added them inside a container several layers deep already. I removed the LineShapes to resolve the issue.
If you have any criteria directly under the class that causes an error, it will also break on this error.
For example:
Public Class Form1
Dim FILE_NAME As String = "C:\Folder\File.txt" '//if this file does not exist
Dim objReader As New System.IO.StreamReader(FILE_NAME)
This last line will cause an error in Protected Overrides
I didn't like VB.NET feature when carriage return from string, so added this code under Public Class Form1 in hope to remove that annoying one:
Dim origString As String
Dim newString As String = origString.Replace(vbCr, "").Replace(vbLf, "")
This code caused a same problem. So possible solution is to comment or remove it:
'Dim origString As String 'From Multiline Textbox'
'Dim newString As String = origString.Replace(vbCr, "").Replace(vbLf, "")
I had the same problem... i deleted all the tools in my form and then it ran without any issue... then i found out that it was the webbrowser control that caused me the problem... i deleted it and added it again and the program ran without any trouble... try removing controls one by one and check which one causing the problem... then delete the particular control and re-add it to make it work... this happens when you copy your solution from one pc to another...
Public Sub New()
InitializeComponent()
End Sub
JUST ADD THIS CODE TO YOUR FORM
frmMain
I actually had this error when I ADDED the following to my Form.
Private Sub New()
InitializeComponent()
End Sub
Very strange!

Unstructured Exception Handling in VB.NET 2005/2008

I have a few VB.NET programs to maintain, that have been ported from VB6 and use the old style Unstructured Exception Handling:
On Error GoTo yyy
My question is, can I still get a stack trace while using Unstructured Exception Handling, or do I have to convert them all to Structured Exception Handling (Try/Catch) in order to catch an exception with its full stack trace.
Here's a way to get the stack trace to the line that caused the exception, unlike the other answer which just traces to the routine where your error handler is. The error might have occurred in a different routine.
In the unstructured error handlers, just use the GetException property of the Err object to access the underlying exception - then use the StackTrace property. Like this:
Public Class Form1
Public Sub New()
' This call is required by the Windows Form Designer.'
InitializeComponent()
' Add any initialization after the InitializeComponent() call.'
On Error GoTo ErrHandle
Call test()
Exit Sub
ErrHandle:
MsgBox("Stack trace " & Err.GetException.StackTrace)
Exit Sub
End Sub
Private Sub test()
Call test2()
End Sub
Private Sub test2()
Dim d(2) As Double
MsgBox(d(-1))
End Sub
End Class
As you know yourself, all things being equal, one should always use structured exception handling. However, if you can't, you can get your own stack trace by using the StackTrace class.
NB: Calls to stack trace are expensive, and should only be used in - ahem - 'exceptional' circumstances.
e.g
MethodName = (New StackFrame(0)).GetMethod.Name ' Get the current method
MethodName = (New StackFrame(1)).GetMethod.Name ' Get the Previous method
MethodName = (New StackFrame(2)).GetMethod.Name ' Get the method before that