Avoiding VSTO, Word Automation Timing RPC_E_CALL_REJECTED Errors - vb.net

I am writing a VSTO VB.NET application that controls a Word document, using standard features such as copying, pasting, inserting text, and pages, for example, and no additional threads. I get the following error at different times: Call was rejected by callee. (Exception from HRESULT: 0x80010001 (RPC_E_CALL_REJECTED)).
This appears to be a timing issue with Word, since it fails almost randomly but only on Word calls. In the debugger, I can then click Continue and the code resumes.
I've seen a lot of comments about this, relevant ones seems to be about the COM IMessageFilter interface. But they all skip one important point: I just want to wait for Word to get free again and then continue. I don't want to prompt the user with options (such as with RetryRejectedCall). An ugly work around right now is intentional delays, like Threading.Thread.Sleep(500), but that's hardly the solution, and with many calls that's also impractical.
What is the proper way of handling this?

Most probably you are using the Word object model from secondary threads. Office application uses the single threaded apartment model. It is not recommended to use any object model from a secondary thread.
Also you may find the similar forum thread helpful.

Related

Labview Program changes behavior after looking at (not changing) the Block Diagram

My Labview Program works like a charm, until I look at the Block Diagram. No changes are made. I do not Save. Just Ctrl+E and then Ctrl+R.
Now it does not work properly. Only a Restart of Labview fixes the problem.
My Program controls two Scanner arrays for Laser Cutting simultaneously. To force parallel working, I use the Error handler and loops that wait for a signal from the Scanner. But suddenly some loops run more often than they should.
What does majorly happen in Labview when I open the Block diagram that messes with my code?
Edit:
Its hard to tell what is happening without violating my non-disclosure agreement.
I'm controlling two independent mirror-Arrays for Laser Cutting. While one is running one Cutting-Job, the other is supposed to run the other Jobs. Just very fast. When the first is finished they meet at the same position and run the same geometry at the same slow speed. The jobs are provided as *.XML and stored as .net Objects. The device only runs the most recent job and overwrites it when getting a new one.
I can check if a job is still running. While this is true I run a while loop for the other jobs. Now this loop runs a few times too often and even ignores WAIT-blocks to a degree. Also it skips the part where it reads the XML job file, changes the speed part back to fast again and saves it. It only runs one time fast.
#Joe: No it does not. It only runs once well. afterwards it does not.
Youtube links
The way it is supposed to move
The wrong way
There is exactly one thing I can think of that changes solely by opening the block diagram.
When the block diagram opens, any commented-out or unreachable-code-compiler-eliminated sections of code will load their subVIs. If one of those commented out sections of code were somehow interfere with your running code, you might have an issue.
There are only two ways I know of for that to interfere... both of them are fairly improbable.
a) You have some sort of "check for all VIs in memory" or "check for all types in memory" that you're using as a plug-in system. When the commented-out sections load, that would change the VIs in memory. Such systems are not uncommon when parsing XML, so maybe.
b) You are using Run VI method for some dynamically invoked VI to execute as a top-level VI, but by loading the diagram, it discovers that it is a subVI of your current program. A VI cannot simultaneously be top-level and a subVI, so the call to Run VI returns an error.
That's it. I can't think of anything else. Both ideas seem unlikely, but given your claim and a lack of a block diagram, I figured I'd post it as a hypothesis.
In the improbable case someone has a similar problem. The problem was a xml file that was read during run time. Sometimes multiple instances tried to access it and this produced the error.
Quick point to check: are Debug and "retain data in wires" disabled? While it may not change the computations, but it may certainly change the timing of very tight loops, and that was one of the unexpected program behaviors, OP was referring to.

Can't eliminate Access corruption

My firm's Access database has been having some serious problems recently. The errors we're getting seem like they indicate corruption -- here are the most common:
Error accessing file. Network connection may have been lost.
There was an error compiling this function.
No error, Access just crashes completely.
I've noticed that these errors only happen with a compiled database. If I decompile it, it works fine. If I take an uncompiled database and compile it, it works fine -- until the next time I try to open it. It appears that compiling the database into a .ACCDE file solves the problem, which is what I've been doing, but one person has reported that the issue returned for her, which has me very nervous.
I've tried exporting all of the objects in the database to text, starting with a brand new database, and importing them all again, but that doesn't solve the problem. Once I import all of the objects into the clean database, the problem comes back.
One last point that seems be related, but I don't understand how. The problem started right around the time that I added some class modules to the database. These class modules use the VBA Implements keyword, in an effort to clean up my code by introducing some polymorphism. I don't know why this would cause the problem, but the timing seems to indicate a relationship.
I've been searching for an explanation, but haven't found one yet. Does anyone have any suggestions?
EDIT: The database includes a few references in addition to the standard ones:
Microsoft ActiveX Data Objects 2.8
Microsoft Office 12.0
Microsoft Scripting Runtime
Microsoft VBScript Regular Expressions 5.5
Some of the things I do and use when debugging Access:
Test my app in a number of VM. You can use HyperV on Win8, VMWare or VirtualBox to set up various controlled test environments, like testing on WinXP, Win7, Win8, 32bit or 64 bits, just anything that matches the range of OS and bitness of your users.
I use vbWatchDog, a clever utility that only adds a few classes to your application (no external dependency) and allows you to trap errors at high level, and show you exactly where they happen. This is invaluable to catch and record strange errors, especially in the field.
If the issue appears isolated to one or a few users only, I would try to find out what is special about their config. If nothing seems out of place, I would completely unsintall all Office component and re-install it after scrubbing the registry for dangling keys and removing all traces of folders from the old install.
If your users do not need a complete version of Access, just use the free Access Runtime on their machine.
Make sure that you are using consistent versions of Access throughout: if you are using Access 2007, make sure your dev machine is also using that version and that all other users are also only using that version and that no components from Access 2010/2013 are present.
Try to ascertain if the crash is always happening around the same user-actions. I use a simple log file that I write to when a debugging flag is set. The log file is a simple text file that I open/write to/close everytime I log something (I don't keep it open to make sure the data is flushed to the file, otherwise when Access crashes, you may only have old data in the log file as the new one may still be in the buffer). Things I log are, for instance, sensitive function entry/exit, SQL queries that I execute from code, form open/close, etc.
As a generality, make sure your app compiles without issue (I mean when doing Debug > Compile from the IDE). Any issue at this stage must be solved.
Make absolutely sure you close all open recordsets, preferrably followed by setting their variables to Nothing. VBA is not as sensitive as it used to be about dangling references, but I found it good practice, especially when you cannot be absolutely sure that these references will be freed (especially when doing stuff at Module-level or Class-level for instance, where the scope may be longer-lived than expected).
Similarly, make sure you properly destroy any COM object you create in your classes (and subs/functions. The Class_Terminate destructor must explicitly clean up all. This is also valid when closing forms if you created COM objects (you mentioned using ADOX, scripting objects and regex). In general keeping track of created objects is paramount: make sure you explicitly free all your objects by resetting them (for instance using RemoveAll on a dictionary, then assigning their reference to Nothing.
Do not over-use On Error Resume or On Error Goto. I almost never use these except when absolutely necessary to recover from otherwise undetectable errors. Using these error trapping constructs can hide a lot of errors that would otherwise show you that something is wrong with your code. I prefer to program defensively than having to handle exceptions.
For testing, disable your error trapping to see if it isn't hiding the cause of your crashes.
Make sure that the front-end is local to the user machine, You mention they get their individual front-end from the network but I'm not sure if they run it from there or if it it copied on their local machine. At any rate, it should be local not on a remote folder.
You mention using SQL Server as a backend. Try to trace all the queries being executed. It's possible that the issue comes from communication with SQL Server, a corrupt driver, a security issue that prevents some queries from being run, a query returning unexpected data, etc. Watch the log files and event log on the server closely for strange errors, especially if they involve security.
Speaking of event log, look for the trace of the crash in the event log of your users. There may be information there, however cryptic.
If you use custom ribbon actions, make sure thy are not causing issues. I had strange problems over time with the ribbon. Log all all function calls made by the ribbon.

MS Access closing on command button click

I have been writing VBA code for a split database, and as of late, some of the command buttons will close the instance of access on the end users machine. No warnings, no ability to stop it from happening. If I add a breakpoint, the code doesnt even hit the click event, it just closes out entirely. This however, is briefly solved by adding a NEW command button and then transferring the code over. What gives?
Repairing and compacting a database rarely seems to solve database corruption problems, and neither does decompiling it (although these can work).
I'd follow these steps (as per Dan's suggestion):
create a new database
import all objects (tables, queries, forms, reports, macros and modules) from old database
At this point it may hang on one particular form or report. If this happens, just omit this form/report from the import (although you may well be unable ever to get at it again!).
Finally, compile any VBA code, repair any references to other VBA object libraries, redraw your relationships window so it looks as pretty as it did before (the relationships themselves aren't lost; just the way they're arranged) - and curse Access!

Why does my Excel VBA code still run after closing my form?

I'm creating a fairly extensive Excel user form making use of several custom classes I've written. Things currently seem to work as expected, but sometimes when I close the form a process appears to still be running in the background.
I know this because after closing said form, sometimes a CPU core keeps running at full capacity, and when I click on a cell in my spreadsheet the value shown in the formula bar blinks rapidly, as if the spreadsheet were being repeatedly refreshed.
I've tried inserting breaks and debug statements in the Class_Terminate functions of each class (or at least all the big ones), and they all seem to deconstruct neatly. Furthermore, when I rest at a code break, everything halts as expected.
So, what gives? Is there a better way to isolate the problem? How can I find out what's still running after I close my userform?
Well, after some aggressive commenting and uncommenting, it seems like my error has to do with VBA's destructor functions, Class_Terminate().
I have a "WellReader" class within a "WellCollection" class, so when I terminate my WellCollection class, it destructs WellReader along with it. However, if I have Class_Terminate() defined for both classes, it throws my program into a loop (literally). Simply defining the functions causes the error, even if there's no code within them.
(Here's a related StackOverflow post that sheds some amount of light on this issue.)
So, while I'm not sure why both destructor functions won't work, for now I'll do without one. Thanks for everyone's help!

Avoiding cross process calls when doing Word automation via VB.net

The short version
I've got a Word Addin in VB.net and VSTO that exposes a COM compatible object via Word.COMAddins.Object, so that the addin functionality can be called External to Word, without accesses to Word itself being cross-process.
The technique worked in VB6, but with VB.net, it still works, but it's much slower than the same code running directly from the addin via a task pane, as if the calls are all cross process when they shouldn't be.
x
The Long version
This addin essentially does tons of processing on Word Documents.
The addin can be run in two ways.
from within Word, using a taskpane
externally, via a set of classes
exposed to COM (because I have to
provide access to the functionality
to VB6 client apps.
BUT, here's the rub. Anyone who's ever done Word automation knows that code that runs perfectly acceptably INPROC with Word (in this case the instance of the ADDIN that Word itself loads), will generally run unacceptably slowly out of process (or cross process).
This app is no different.
Ages ago, I made use of a handy trick to circumvent this issue.
Create a Word Addin as usual
Expose an object via the
Word.COMAddin.Object property that
will let external code access your
addin.
In your external project, instead of
manipulating Word directly, Use the
Application.COMAddins collection,
find your addin, retrieve the
exposed COMAddin.Object property
from it and then call a method on
that object that does the work.
Of course, the call to your COMAddin.Object object will still be cross process, BUT, once execution is in the addin that is IN PROCESS with Word, your addin can now perform all the Word object manipulations it wants and it's fast because they're all in-process calls at that point.
That worked in the VB6 COM days.
But, I put together this VB.net vsto addin, and expose my addin object via the RequestComAddInAutomationService function of VSTO's Connect object
I can make calls into my addin externally and they all work exactly as I would expect them to, except they're all +slow+, very much like the calls into Word are still being performed cross process even though the code making those calls to Word is part of the addin dll that was loaded in-process by Word!
And slow as in a factor of about 10 to 1; what takes 3 seconds to run when run directly from the ADDIN via the task pane, takes ~30seconds to run when called from external code through the COMADDIN.object object.
I'm guessing that I'm running into some sort of issue with .net APPDOMAINS or something and what +really+ constitutes cross proc calls in .net, but I've found nothing so far that would even hint about this sort of thing.
My next step, barring some mystical insight, will be to code up a repro, which could get tricky because of the shear number of elements in play.
Any thoughts?
I've made the same observations with my VSTO Word add in. What I'd like to add here: When you add your procedure as a click handler to a button:
`this.testButton.Click += new Office._CommandBarButtonEvents_ClickEventHandler(YourProcedure);ยด
and implement your expensive procedure in "YourProcedure", you can call into Word's UI thread using
this.testButton.Execute();
This is not an elegant solution either, but maybe useful if you happen to have buttons ready in a CommandBar.
Unfortunately, the Event hook technique Thorben mentions wouldn't work for my particular situation.
So I'm closing this question out with the workaround that I mentioned in comments and I'll repeat here...
Well, not a perfect solution, but I have found +a+ solution. It involved a timer, so it's definitely suboptimal Essentially, when the addin is loaded by Word, (ie during the STARTUP event), initialize a timer (a WINFORMS timer, not a threading timer), and set it's interval to 500. When External code connects to the addin via the COMADDIN.OBject property, and makes a call into the addin, set a variable flag, which is being polled by the timer. When the timer sees it set, it resets the flag and performs the action.
It's not the clean solution I'd have preferred, but it's fairly easy to implement, moderately easy to understand after the fact, and it definitely avoids the slowdown of xprocess COM calls into Word.