vb.net - Problem remaking com object after program has closed - vb.net

Have been searching for a solution to this problem for days with no luck so I decided to post here and hope someone can help me. What makes it even harder is that I can't replicate this problem on my computer very consistently. Sometimes I will get the error but most of the time I won't.
Basically what is happening is I am creating an IE object which my program then controls for a long period of time. What is happening is, if a user exits the program it calls oIE.Quit() then closes the program. This should close internet explorer and all processes associated with it.
But, the iexplorer process doesn't end up closing. Then when the user tries to run the program again we get this error "System.Runtime.InteropServices.COMException (0x80004005): Creating an instance of the COM component with CLSID {0002DF01-0000-0000-C000-000000000046} from the IClassFactory failed due to the following error: 80004005.".
To fix this we simply close the any iexplorer.exe processes that are open and it will let us create our ie object again. This happens also if the program crashes and they try to restart it.
I am not sure what is causing this or if I am missing something that has to do with com objects. But I am simply stuck.
Here is some code although plugging in this code likely won't reproduce any errors:
'create ie object
oIE = New SHDocVw.InternetExplorer
oIE.Navigate("http://www.google.com")
oIE.Visible = False
oIE.Silent = True
'kill ie object
oIE.Quit()

The exception you get is hopeless, that's E_FAIL, "Unspecified error". There isn't any obvious reason why this would fail, starting another instance of IE when your program starts back up shouldn't be a problem. Well, short from those ghost instances of IE that keep running forever. I would guess that you got this exception for the same reason that IE didn't quit when you called Quit() the last time.
Do consider the kind of mishap you'll create when your program aborts and doesn't get around to cleanly shutting down IE. Using Environment.Exit() would be quite unhealthy for example. Or any other kind of nasty kaboom that doesn't let the finalizer thread run at termination. Maybe that has already happened many times before, now IE just refuses to create any more instances? How many instances do you have to kill when you need to get it going again?
The much better mousetrap here is to run IE in-process in your own program rather than out-of-process with SHDocVw. So that when your program terminates, it takes IE with it. It is also much more efficient, there's a lot of overhead involved in making out-of-process COM server calls.
You do this by using WebBrowser in your program.

Related

Why do I get "No process is associated with this object." when calling process.Close() or process.Kill()?

I have a C# program that is launching TShark.exe which is the background equivalent of WireShark. I would like to close all instances that I start. It appears to start just fine, run in the background and log network traffic to a file as it should. However, when I try to close it, I get a "No process is associated with this object." exception.
Here is how I'm starting the processes:
ProcessStartInfo processStartInfo = new ProcessStartInfo
{
Arguments = $"-i {nic} -t ad -w {GenerateLogPath(nic)}",
FileName = "\"C:\\Program Files\\Wireshark\\tshark.exe\"",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false
};
WireSharkProcesses.Add(System.Diagnostics.Process.Start(processStartInfo));
I've tried several methods to close/kill these processes. First, I kept a list of all processes that I had started in my app and called the following on them without success:
process.CloseWindow();
process.Close();
process.Kill();
I kept getting the "No process is associated with this object." exception.
So, I used:
var processes = System.Diagnostics.Process.GetProcesses();
And got a list of all processes on my machine and looped through them and attempted to close those who's process name was "tshark" or "dumpcap". I attempted this with .CloseWindow(), .Close(), and .Kill() all of which failed and threw the above exception.
I even went into TaskManager and attempted to END TASK on them. They appeared to be removed, but upon closing and re-opening TaskManager, they magically reappeared. There are also now several instances of "tshark" and "dumpcap" that show up when I call GetProcesses(), but are not in the list of processes that Task Manager shows.
What am I missing here?? Short of rebooting my machine, how do I get these processes to exit? Is this just a wireshark problem, or a general problem with killing processes?
Are you using WinPcap or Npcap? If you're using WinPcap, you could try switching to Npcap and using that instead. See Gerald Comb's comment #32 on the recently closed Wireshark Bug 14701.
By the way, in case you weren't aware, tshark is capable of capturing on more than one interface at a time, so in theory only a single instance is required. I understand that this can sometimes cause reassembly problems though, so if that's what you're trying to avoid or if you just want to keep packets separated by interface, then yes, you'll have to start multiple instances.

MS Access crashes when trying to close down a connection to Blackbaud's Raiser's Edge API

I am the IT department of a Non-Profit organization. I have a question today which might be too specialized for this forum and I hope I do not waste my time writing it up. We are using Blackbaud's 'Raiser's Edge' (RE) Software (written in VB6 and VB.net as far as I know) to keep track of our membership and donations. We have an MS Access application (have been using it since before we got RE) to process donations and for now I want to keep it and only do minor changes to adapt it to the new software.
The MS Access program is now doing a few calls to the RE API which work great. To login and establish a connection I have to create a new 'REAPI' object and use it for other API calls. That REAPI object has a method called: SignOutOnTerminate which needs to be set to TRUE when creating that object. It is supposed to kill all connections to RE once my application closes. There is no regular .close method.
Once I create the object I can do work as many times as I want and there is no problem at all as far as I can see.
However when trying to close the application or set the object to nothing (Set REAPI = Nothing) Access crashes immediately (It fades out and I get the message that Windows is looking for a solution to the problem. Then Access closes and restarts itself.)
It is more annoying and unprofessional then hindering production but I want to fix it.
The App was developed on Windows 7 64-bit with Access 2010 32-bit. It was tested on Windows XP with Office 2003 or 2007 machines (32-bit) and behaves the same way.
I have posted this problem already on 2 Blackbaud forums and tried a suggested a work around which did not work (kill the process with a shell command and then set the object to nothing). Hopefully I will get more answers soon.
I tried to just exclude the SignOutOnTerminate when creating the object. But got the same behavior.
I looked in the Event Manager --> Application Log and found the Crash. It reported that access crashed because of this dll: C:\Windows\System32\MSVBVM60.dll (It is actually located in the SysWos64 folder as it is a 32-bit application).
Looking up this error I found some suggestions to replace it with an earlier version of the dll, the one which ships with XP. I found a file and tried the suggestion but it still crashed. The error log reported the older version number as faulting so I registered it correctly.
I also created a case with Blackbaud but the rep did not know what the problem is and did not have MS Access installed. He is trying to get his support team to install it for him so he can test and investigate this error.
The last suspicion I have is that the API is causing the error and my code is fine.
But before I make this assumption and until I get my answer from Blackbaud I want to do a final check, but I have run out of ideas for further trouble shooting and resorted to pose this problem in this forum.
Any Ideas?
I realise that this is an old thread and if you have solved this by now then that is great. However this is a known issue with The Raiser's Edge API. If you use .NET with RE's API (which is COM based) there is definitely some resource that is not cleaned up properly. At one point I suspected that it was something to with making use of RE's graphical interface i.e. by calling the regular login method to log you into RE. However even if you log in to RE using the "as a server" method supplying the user name and password it still crashes on exiting the application.
We have an installer that sets up credentials in RE. The installer is in .NET and accesses the RE API. We now show a message just before the end of the application telling users to ignore the impending crash... Not a great solution by any means.

NSTask subprocess stuck in _dyld_start

I use NSTask to run my helper application. On 99% one my customer systems this works fine, but two got back to me letting me know it doesn't. One of them was nice enough to let me look into the issue per remote desktop.
I tried a lot of different NSPipe/NSFileHandle combination for StandardOutput/StandardError to make sure the problem is not related filling up these buffers. Example 1 and 2. My guess is that it is not related because it works fine on so many systems and _dyld_start is too early on in the application lifecycle to fill up StandardOutput/StandardError.
Other notes about the problem:
Launching the helper app from the terminal works fine.
Attaching and detaching the gdb on the stuck process and after-worth it works fine and when it finished NSTask picks up work after -waitUntilExit.
Using fork(2) and execv(3) instead of NSTask is able to launch and run the helper fine.
The parent process is sandboxed but I think previous reports where non-sandboxed on Mac OS X 10.6/10.7.
Screenshot of the process Sample from Activity Monitor:
Any clues or debugging tips to figure out why the helper is stuck in _dyld_start are welcome!
Since nobody answered, I am throwing a few ideas. Maybe one of them is the answer – only guessing – but since clues and tips are welcome, you could take a look at:
the list of the loaded libraries in the crash dump (there may be a clue there)
any error that would happen in the child process (after the fork). However, I see why it could be difficult to get back any post-fork error.
If I recall correctly, NSTask calls posix_spawn(2). This may be a clue, since using fork(2) and execv(3) seems working, you could focus on the differences between NSTask and the non-blocking alternative. Clearly, something is happening at the very beginning that prevents the child from executing properly.
Are you sure it is stuck and not crashed? As far as the user could tell, your app your app wouldn't look like it crashed. Only the child process would crash.
As a last resort, you could try to look for any Mach exception occuring (if
any, that would mean an error, which you wouldn't be able to
recover anyway. But it would provide valuable clues nonetheless).
You can tell willing custommers to send you their sysdiagnose. To this goal, ask them to hit Command + Option + Control + . + Shift to wait a few minutes. Soon after, their finder should pop a window to reveal a file named: sysdiagnose_timestamp_.tar.gz. Kindly ask them to mail it to you. Mine is around 5 MB. More details on the sysdiagnose man page.

Application.restart - Puzzling behaviour in VB.Net

OK guys, what's going on here?
In this VB code:
Module Module1
Sub Main()
If MsgBox("Restart?", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
Application.Restart()
MsgBox("restarting")
Else
MsgBox("Cancel")
End If
End Sub
End Module
If this code is contained within a module, Application.Restart does not end the running application till the End Sub is hit. Any code that appears before then is executed - eg the 'Restarting' messagebox appears.
However, if the equivalent code is run within a form then Application.Restart terminates the running application immediately.
(Both cases correctly start a new instance). This behaviour does not appear to be documented anywhere - the implication in the docs is that it's synonymous with 'End' as far as the termination of the running instance is concerned. Am I missing something?
The best way to answer these questions it to look at the code itself using Reflector (or Microsoft's free for debugging code, when it is available).
With Reflector, you can see (in .NET Framework 4.0) System.Windows.Forms.Application.Restart looks for four different types of applications:
the initial check that Assembly.GetEntryAssembly is Nothing, throwing a NotSupportedException if it is;
the Process.GetCurrentProcess.MainModule.FileName is ieexec.exe in the same folder as the current .NET Framework (specifically the folder where the module defining Object is);
ApplicationDeployment.IsNetworkDeployed is True; and
the general case.
All three supported cases determine the method to start the process again, calls Application.ExitInternal and starts the process again.
Application.ExitInternal closes open forms, including the check for a form attempting to abort the close by setting FormClosingEventArgs.Cancel to True. If no form attempts to cancel, the forms are closed and, using ThreadContext.ExitApplication, all ThreadConnexts are cleaned up (Disposed or their ApplicationContext.ExitThread is called).
NB No Thread.Abort is called, so threads are NOT explicitly ended in any way. Also the Windows.Forms ModalApplicationContext, does not even call the ThreadExit "event" that a normal ApplicationContext does.
(Note that all three supported cases in Application.Restart ignore the result of Application.ExitInternal, so if a form does attempt to abort all that happens is any other forms don't get a chance to close, and the ThreadContexts are not cleaned up!)
Importantly for your question, it does NOT attempt to actually exit the current threads or the entire application (other than closing open forms and thread contexts).
However, by the time your MsgBox("restarting") executes the new application has been started.
You need to manually exit the application after calling Application.Restart. In the case of "run[ing] within a form" (you don't show the code where you tested this) either the form is closed and that is what you considered as the current application ending, or extra stuff that Windows.Forms (or VB) sets up means the application is exited by one of the "events" that throw when the clean up that does occur runs.
In other words, before testing it I expected the MsgBox to appear even when this code is in say the Click event of a form, with the form disappearing first, and the application restarting at the same time.
Having tested it, the MsgBox tries to appear, as I hear the beep that corresponds to it, and if I comment it out the beep does not occur. So something causes the application to exit even though it should have a message box open, and even putting a MsgBox in a Finally outside of the Application.Run does not appear on a Restart. (Note a similar effect is seen if you call MsgBox after Application.Exit.)
So something set up by Windows.Forms (or VB) does actually call something like Environment.Exit which calls the Win32Api ExitProcess and does not regard Finally or call Dispose or Finalize.
Note the Application.Restart documentation implies it is not for Console Applications though it currently works fine (except for the not quitting straight away, which is not implied by Application.Exit).
I am able to restart the application by closing and disposing all open forms, except the one that is calling.
For j As Integer = Application.OpenForms.Count - 1 To 0 Step -1
Dim frm = Application.OpenForms(j)
If frm.Text <> callingForm.Text Then
frm.Close()
frm.Dispose()
End If
Next
Application.Restart()
This is going to be, admittedly, a bit of a guess based on some fairly top-level reading I've done about Application.Restart(), but I think this is occurring due to the way Restart operates internally.
I think Restart() tries to do as much "intelligent" cleanup as it can for a process that is being terminated, and in what may be considered a fairly simplistic implementation, tracks certain of the things to be "cleaned up," possibly calling Dispose() on them (if applicable), which normally is a reasonable step to take. In your case, I'm going to make the guess that a background thread, or form, holds a reference to something - can't say what - that prevents the code from shutting down. It may become aware that it is executing inside a method, and wants to give that method a chance to complete before killing it - waiting on the completion of that sub/method.
I've seen other instances of Restart actually causing a really strange "Collection was Modified" error when no collection was involved. That's suggesting to me, probably naively, that the internal cleanup Restart is trying to achieve is reposed in a simple list, but in certain circumstances, the cleanup modifies the element in an unexpected way, a way that modifies the collection, causes the exception to be thrown, and aborts the exit/restart.

Com Object Exception

I wrote an application that loops through a set of records and prints two things.
One is a report from SSRS wich works correctly.
The other is a drawing that uses a COM object to print. The COM object randomly fails and causes the program to quit.
Is there a way to stop it from killing the entire program when the COM Object fails? I have tried catch every exception at every level and it still does not work.
Do you have the code of COM object that you are calling. If you have code then check whether there any exit command on failure.
Are you using the COM object from multiple threads? You should only access the COM object from a single thread with a message pump. In my experience this can cause weird instability which cannot be trapped via a try-catch.
It sounds like the issue maybe with the com object itself and not your code. If this is the case then if the com object does not throw an error then you will not be able to catch one.
Kind Regards
Tony Smith-Brewster