Error inside of Application.Designer.vb inside of OnCreateMainForm() Sub - vb.net-2010

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!

Related

Exception unhandled within Application.Designer.vb

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.

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.

Update control on main form via Background Worker with method in another class VB.Net

I have been banging my head against the wall all day trying to figure this one out.
I am finishing up a program to simply delete files in specific temp folders. I have read that it is sometimes good practice to create separate classes for methods and variables. So I have created a separate class for a couple methods to delete files and folders in a specified directory. I am using a Background Worker in my Form1 class and am calling my deleteFiles() method from my WebFixProcesses class in the DoWork event in the Form1 class. I am using a Background Worker so that I can easily report progress back to a progress bar on my main form.
The files get deleted without an issue but I just can't get the label on my main form to reflect the current file being deleted. the label doesn't change in any way.
I know the formula is correct as I can get this working if the method is in the Form1 class. and I simply use:
Invoke(Sub()
lblStatus.Text = File.ToString
lblStatus.Refresh()
End Sub)
here is my method that I am calling from the WebFixProcesses class:
Public Shared Sub deleteFiles(ByVal fileLocation As String)
For Each file As String In Directory.GetFiles(fileLocation)
Try
fileDisplay.Add(file)
For i = 1 To fileDisplay.Count
file = fileDisplay(i)
Form1.BackgroundWorker1.ReportProgress(CInt(i / fileDisplay.Count) * 100)
Next
IO.File.Delete(file)
Form1.labelText(file)
Form1.labelRefresh()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Next
End Sub
labelText() and labelRefresh() are methods from my main form which are using delegates to try to pass information to the control:
Public Sub labelText(ByVal file As String)
If lblStatus.InvokeRequired Then
Dim del As New txtBoxDelegate(AddressOf labelText)
Me.Invoke(del, file)
Else
lblStatus.Text = file.ToString()
End If
End Sub
Public Sub labelRefresh()
If lblStatus.InvokeRequired Then
Dim del As New txtBoxRefDelegate(AddressOf labelRefresh)
Me.Invoke(del)
Else
lblStatus.Refresh()
End If
End Sub
If anyone can help me out to inform me what I may be doing wrong it would be immensely appreciated as my head is in a lot of pain from this. And maybe I am going at it all wrong, and just being stubborn keeping my methods in their own class. But any help would be awesome. Thanks guys!
What Hans wrote on the question comment is true: Form1 is a type, not an instance, but to make things easier to newbye programmes (coming from VB6), M$ did a "mix", allowing you to use the form name as the instance of the form in the main thread.
This however works only if you are on that thread.
If you reference Form1 from another thread, a new instance of Form1 is created.
To solve the issue, add this code to the form:
Private Shared _instance As Form1
Public ReadOnly Property Instance As Form1
Get
Return _instance
End Get
End Property
We will use this property to store the current instance of the form. To do so, add this line to the Load event:
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
_instance = Me
'other code here
End Sub
Now, from every class, in any thread, if you use
Form1.Instance
...you get the actual form. Now you can Invoke, even from the same form:
Me.instance.Invoke(Sub()
Me.lblStatus.Text = "Hello World"
End Sub)

CA2000: Dispose objects before losing scope and Form.Show()

I'm trying to fix all my project warning according to Microsoft code analysis (CA:XXXXX)
One of the warning is "CA2000: Dispose objects before losing scope"
My Code is:
Private sub Foo()
Dim O As New Form1()
O.Show()
End Sub
Visual studio says that the object O is not disposable, in such situation I can't use the keyword USING because I will lost the object O after End Using:
Private sub Foo()
Using O As New Form1()
O.Show() 'The form will open then close !!!
End Using
End Sub
The form then will open and close
How to get ride with CA2000 in such situation, I don't need to ignore, I want to solve and fix.
Thanks.
I don't need to ignore, I want to solve and fix.
This is, effectively, a false warning, in this specific instance. You don't want to "solve and fix" this message in this specific case, because you want the object to "live" beyond the end of the local scope.
If you call Dispose on the object in that scope, you will (always) close the form, in this case.
How about ShowDialog?
Private sub Foo()
Using O As New Form1()
O.ShowDialog()
End Using
End Sub
It will dispose all resources of Form1 after i has been closed.

"make single instance application" what does this do?

in vb 2008 express this option is available under application properties. does anyone know what is its function? does it make it so that it's impossible to open two instances at the same time?
does it make it so that it's impossible to open two instances at the same time?
Yes.
Why not just use a Mutex? This is what MS suggests and I have used it for many-a-years with no issues.
Public Class Form1
Private objMutex As System.Threading.Mutex
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Check to prevent running twice
objMutex = New System.Threading.Mutex(False, "MyApplicationName")
If objMutex.WaitOne(0, False) = False Then
objMutex.Close()
objMutex = Nothing
MessageBox.Show("Another instance is already running!")
End
End If
'If you get to this point it's frist instance
End Sub
End Class
When the form, in this case, closes, the mutex is released and you can open another. This works even if you app crashes.
Yes, it makes it impossible to open two instances at the same time.
However it's very important to be aware of the bugs. With some firewalls, it's impossible to open even one instance - your application crashes at startup! See this excellent article by Bill McCarthy for more details, and a technique for restricting your application to one instance. His technique for communicating the command-line argument from a second instance back to the first instance uses pipes in .NET 3.5.
Dim _process() As Process
_process = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName)
If _process.Length > 1 Then
MsgBox("El programa ya está ejecutandose.", vbInformation)
End
End If
I found a great article for this topic: Single Instance Application in VB.NET.
Example usage:
Module ModMain
Private m_Handler As New SingleInstanceHandler()
' You should download codes for SingleInstaceHandler() class from:
' http://www.codeproject.com/Articles/3865/Single-Instance-Application-in-VB-NET
Private m_MainForm As Form
Public Sub Main(ByVal args() As String)
AddHandler m_Handler.StartUpEvent, AddressOf StartUp ' Add the StartUp callback
m_Handler.Run(args)
End Sub
Public Sub StartUp(ByVal sender As Object, ByVal event_args As StartUpEventArgs)
If event_args.NewInstance Then ' This is the first instance, create the main form and addd the child forms
m_MainForm = New Form()
Application.Run(m_MainForm)
Else ' This is coming from another instance
' Your codes and actions for next instances...
End If
End Sub
End Module
Yes you're correct in that it will only allow one instance of your application to be open at a time.
There is even a easier method:
Use the following code...
Imports System.IO
On the main form load event do the following:
If File.Exist(Application.StartupPath & "\abc.txt") Then
'You can change the extension of the file to what ever you desire ex: dll, xyz etc.
MsgBox("Only one Instance of the application is allowed!!!")
Environment.Exit(0)
Else
File.Create(Application.StartupPath & "\abc.txt", 10, Fileoptions.DeleteonClose)
Endif
This will take care of single instances as well as thin clients, and the file cannot be deleted while the application is running. and on closing the application or if the application crashes the file will delete itself.