Check if a dll is installed and available - c#

I am trying to make an application that may rely on a Wacom tablet. It is not necessary for the program to work, but it is a nice addition. Although, it should also work on computers without the Wintab32.dll installed and I would like to make a check to see if the DLL is available.
This piece of code generates an error and I would like to catch the error before it is generated. I am using WintabDN to support .net Wacom applications.
if (WintabDN.CWintabInfo.IsWintabAvailable())
{
// Initialize Wintab
WintabLib.Initialize(true);
WintabLib.OnWintabPacketReceived += WintabLib_OnWintabPacketReceived;
}
FAILED IsWintabAvailable: System.DllNotFoundException: Unable to load
DLL 'Wintab32.dll': The specified module could not be found.
(Exception from HRESULT: 0x8007007E)
at WintabDN.CWintabFuncs.WTInfoA(UInt32 wCategory_I, UInt32 nIndex_I, IntPtr IpOutput_O)
at WintabDN.CWintabInfo.IsWintabAvailable()
The problem with this error is that it is a messagebox and not an exception thrown by the package. How can I prevent this messagebox from showing up?

It's a bit tricky, because the underlying exception is already being handled.
Trying to block the messagebox from showing is going to be difficult, if not impossible. You can do something really hacky like a watcher thread to catch the foreground window changing, then manually sending a mouse click message to the application's underlying message queue to try and trigger the OK button on the message box.
So I have two suggestions: this is the official topic on DLL search order; you can use it to emulate the search and find the file in advance.
If you don't want to do that you could import the LoadLibrary method from kernel32.dll and then call that to try and load the DLL that the WintabDN library is trying to use; if you get an exception then you know that the WintabDN library will also. Here's an almost related topic that'll help bind LoadLibrary: http://blogs.msdn.com/b/jonathanswift/archive/2006/10/03/dynamically-calling-an-unmanaged-dll-from-.net-_2800_c_23002900_.aspx

Try following which answers:
(The Wintab SDK examples won't run without Wintab installed on the system. How can I make my program work if there is no tablet (no Wintab) on the system?)
http://www.wacomeng.com/windows/docs/WacomWindevFAQ.html

How can I prevent this messagebox from showing up?
You can't:
public static bool IsWintabAvailable()
{
IntPtr buf = IntPtr.Zero;
bool status = false;
try
{
status = (CWintabFuncs.WTInfoA(0, 0, buf) > 0);
}
catch (Exception ex)
{
MessageBox.Show("FAILED IsWintabAvailable: " + ex.ToString());
}
return status;
}
:D
I hate library developers, writing such kind of code. They shouldn't decide, what error-handling mechanism you will choose.
But it is open-source, you can fix this issue.
Or you can post a bug at their tracker and wait, when they will fix it.

Related

CefSharp/Cef libcef.dll stack overflow (0xC00000FD)

CefSharp Winforms Version 43.0.0.0, libcef.dll 3.2357.1287.
When selecting text in a text box, and then hitting a key on the on screen keyboard (does not happen on the normal keyboard), I sometimes get a stack overflow in libcef.dll.
I am ripping my hair out trying to isolate the cause. One thing that is slowing me down is the inability to connect a proper pdb file to the dll. Despite downloading all variations of it from CefBuilds.
I have various crash dumps, and was wondering if anybody else has had experience troubleshooting this kind of thing. WinDBG may as well be chinese, with DebugDiag being much easier to follow, but without the valid pdb file neither are any use at all.
I cannot recreate the issue in the winform example application, so its definitely local to us, so I am currently ripping code out left right and center to isolate the cause, but would really appreciate some guidance on how to load the pdb file into debugdiag to stop this:
Despite this:
libcef.dll version:
For anyone interested, this is the current crashing thread's stack trace:
... and on and on and on...
I guess the main question is does anybody know what could be causing the stack overflow? (This problem existed in 41.0.0 in the winform example application, now it only exists within our own application in 43.0.0).
With a secondary question of why aren't the pdb files loading in debugdiag.
Edit. I am compiling in 32bit, and it appears there is no pdb file for the 32 bit edition of libcef.dll v3.2357.1287. In fact, according to cefbuilds.com this file does not exist.
It appeared that although I couldn't re-create the issue using the winform example's main form, I could whilst using its SimpleBrowserForm.cs.
This allowed me to compare the different implementations.
In the main form, once the browser control is initialised, a hacky message loop interceptor is created, to pass internal WM_MOUSEACTIVATE events up to the parent container. This appears to be an effort to ensure that if a context menu is open at the time the click is received, it will be closed by the click event (chromium suppresses internal mouse clicks it seems).
private void OnIsBrowserInitializedChanged(object sender, IsBrowserInitializedChangedEventArgs args)
{
if (args.IsBrowserInitialized)
{
ChromeWidgetMessageInterceptor.SetupLoop((ChromiumWebBrowser)Browser, (message) =>
{
const int WM_MOUSEACTIVATE = 0x0021;
const int WM_NCLBUTTONDOWN = 0x00A1;
if (message.Msg == WM_MOUSEACTIVATE) {
// The default processing of WM_MOUSEACTIVATE results in MA_NOACTIVATE,
// and the subsequent mouse click is eaten by Chrome.
// This means any .NET ToolStrip or ContextMenuStrip does not get closed.
// By posting a WM_NCLBUTTONDOWN message to a harmless co-ordinate of the
// top-level window, we rely on the ToolStripManager's message handling
// to close any open dropdowns:
// http://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/ToolStripManager.cs,1249
var topLevelWindowHandle = message.WParam;
PostMessage(topLevelWindowHandle, WM_NCLBUTTONDOWN, IntPtr.Zero, IntPtr.Zero);
}
});
}
}
Anyway, with this weird little hack in place, my stack overflow crash goes away.
I have raised a github ticket to try get the underlying issue resolved, but for now this is preventing the issue.

Messagebox in Catch block not always showing [duplicate]

When I create a new project, I get a strange behavior for unhandled exceptions. This is how I can reproduce the problem:
1) create a new Windows Forms Application (C#, .NET Framework 4, VS2010)
2) add the following code to the Form1_Load handler:
int vara = 5, varb = 0;
int varc = vara / varb;
int vard = 7;
I would expect that VS breaks and shows an unhandled exception message at the second line. However, what happens is that the third line is just skipped without any message and the application keeps running.
I don't have this problem with my existing C# projects. So I guess that my new projects are created with some strange default settings.
Does anyone have an idea what's wrong with my project???
I tried checking the boxes in Debug->Exceptions. But then executions breaks even if I handle the exception in a try-catch block; which is also not what I want. If I remember correctly, there was a column called "unhandled exceptions" or something like this in this dialog box, which would do excatly what I want. But in my projects there is only one column ("Thrown").
This is a nasty problem induced by the wow64 emulation layer that allows 32-bit code to run on the 64-bit version of Windows 7. It swallows exceptions in the code that runs in response to a notification generated by the 64-bit window manager, like the Load event. Preventing the debugger from seeing it and stepping in. This problem is hard to fix, the Windows and DevDiv groups at Microsoft are pointing fingers back and forth. DevDiv can't do anything about it, Windows thinks it is the correct and documented behavior, mysterious as that sounds.
It is certainly documented but just about nobody understands the consequences or thinks it is reasonable behavior. Especially not when the window procedure is hidden from view of course, like it is in any project that uses wrapper classes to hide the window plumbing. Like any Winforms, WPF or MFC app. Underlying issue is Microsoft could not figure out how to flow exceptions from 32-bit code back to the 64-bit code that triggered the notification back to 32-bit code that tries to handle or debug the exception.
It is only a problem with a debugger attached, your code will bomb as usual without one.
Project > Properties > Build tab > Platform target = AnyCPU and untick Prefer 32-bit. Your app will now run as a 64-bit process, eliminating the wow64 failure mode. Some consequences, it disables Edit + Continue for VS versions prior to VS2013 and might not always be possible when you have a dependency on 32-bit code.
Other possible workarounds:
Debug > Exceptions > tick the Thrown box for CLR exceptions to force the debugger to stop at the line of code that throws the exception.
Write try/catch in the Load event handler and failfast in the catch block.
Use Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException) in the Main() method so that the exception trap in the message loop isn't disabled in debug mode. This however makes all unhandled exceptions hard to debug, the ThreadException event is pretty useless.
Consider if your code really belongs in the Load event handler. It is very rare to need it, it is however very popular in VB.NET and a swan song because it is the default event and a double-click trivially adds the event handler. You only ever really need Load when you are interested in the actual window size after user preferences and autoscaling is applied. Everything else belongs in the constructor.
Update to Windows 8 or later, they have this wow64 problem solved.
In my experience, I only see this issue when I'm running with a debugger attached. The application behaves the same when run standalone: the exception is not swallowed.
With the introduction of KB976038, you can make this work as you'd expect again. I never installed the hotfix, so I'm assuming it came as part of Win7 SP1.
This was mentioned in this post:
The case of the disappearing OnLoad exception – user-mode callback exceptions in x64
Here's some code that will enable the hotfix:
public static class Kernel32
{
public const uint PROCESS_CALLBACK_FILTER_ENABLED = 0x1;
[DllImport("Kernel32.dll")]
public static extern bool SetProcessUserModeExceptionPolicy(UInt32 dwFlags);
[DllImport("Kernel32.dll")]
public static extern bool GetProcessUserModeExceptionPolicy(out UInt32 lpFlags);
public static void DisableUMCallbackFilter() {
uint flags;
GetProcessUserModeExceptionPolicy(out flags);
flags &= ~PROCESS_CALLBACK_FILTER_ENABLED;
SetProcessUserModeExceptionPolicy(flags);
}
}
Call it at the beginning of your application:
[STAThread]
static void Main()
{
Kernel32.DisableUMCallbackFilter();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
I've confirmed (with the the simple example shown below) that this works, just as you'd expect.
protected override void OnLoad(EventArgs e) {
throw new Exception("BOOM"); // This will now get caught.
}
So, what I don't understand, is why it was previously impossible for the debugger to handle crossing kernel-mode stack frames, but with this hotfix, they somehow figured it out.
As Hans mentions, compile the application and run the exe without a debugger attached.
For me the problem was changing a Class property name that a BindingSource control was bound to. Running without the IDE I was able to see the error:
Cannot bind to the property or column SendWithoutProofReading on the
DataSource. Parameter name: dataMember
Fixing the BindingSource control to bind to the updated property name resolved the problem:
I'm using WPF and ran into this same problem. I had tried Hans 1-3 suggestions already, but didn't like them because studio wouldn't stop at where the error was (so I couldn't view my variables and see what was the problem).
So I tried Hans' 4th suggestion. I was suprised at how much of my code could be moved to the MainWindow constructor without any issue. Not sure why I got in the habit of putting so much logic in the Load event, but apparently much of it can be done in the ctor.
However, this had the same problem as 1-3. Errors that occur during the ctor for WPF get wrapped into a generic Xaml exception. (an inner exception has the real error, but again I wanted studio to just break at the actual trouble spot).
What ended up working for me was to create a thread, sleep 50ms, dispatch back to main thread and do what I need...
void Window_Loaded(object sender, RoutedEventArgs e)
{
new Thread(() =>
{
Thread.Sleep(50);
CrossThread(() => { OnWindowLoaded(); });
}).Start();
}
void CrossThread(Action a)
{
this.Dispatcher.BeginInvoke(a);
}
void OnWindowLoaded()
{
...do my thing...
This way studio would break right where an uncaught exception occurs.
A simple work-around could be if you can move your init code to another event like as Form_Shown which called later than Form_Load, and use a flag to run startup code at first form shown:
bool firstLoad = true; //flag to detect first form_shown
private void Form1_Load(object sender, EventArgs e)
{
//firstLoad = true;
//dowork(); //not execute initialization code here (postpone it to form_shown)
}
private void Form1_Shown(object sender, EventArgs e)
{
if (firstLoad) //simulate Form-Load
{
firstLoad = false;
dowork();
}
}
void dowork()
{
var f = File.OpenRead(#"D:\NoSuchFile756.123"); //this cause an exception!
}

C# .NET Error Attaching to Running Instance of Office Application

I am working on an Excel Addin using C#, Visual Studio 2012. I am trying to get the instance of Excel's Application object so as to keep track of the currently active workbook and worksheet (ActiveWorkbook, ActiveWorksheet).
I see that most other related questions on SO have replies suggesting to use the following:
(Excel.Application)Marshal.GetActiveObject("Excel.Application");
I have also tried using this:
(Excel.Application)Globals.ThisAddIn.Application;
In both of the cases I get NullReferenceException. After looking at the workaround suggested here: http://support.microsoft.com/kb/316125/en-us, I tried the following to test both methods.
public CurrentSpreadSheet()
{
try
{
this.CurrentApplication = (Excel.Application)Globals.ThisAddIn.Application;
}
catch (NullReferenceException)
{
MessageBox.Show("Excel application object not registered. Trying plan B..");
//Getting Excel's application object instance
int iSection = 0, iTries = 0;
tryAgain:
try
{
iSection = 1; //Attempting GetActiveObject
this.CurrentApplication = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
iSection = 0; //GetActiveObject succeeded so resume or go for normal error handling if needed
this.CurrentApplication.Visible = true;
}
catch (Exception err)
{
System.Console.WriteLine("Visual C# .NET Error Attaching to Running Instance of Office Application .. yet.");
if (iSection == 1)
{
//GetObject may have failed because the
//Shell function is asynchronous; enough time has not elapsed
//for GetObject to find the running Office application. Wait
//1/2 seconds and retry the GetObject. If we try 20 times
//and GetObject still fails, we assume some other reason
//for GetObject failing and exit the procedure.
iTries++;
if (iTries < 20)
{
System.Threading.Thread.Sleep(500); // Wait 1/2 seconds.
goto tryAgain; //resume code at the GetObject line
}
else
{
MessageBox.Show("GetObject still failing. Process ended.");
}
}
else
{
//iSection == 0 so normal error handling
MessageBox.Show(err.Message);
}
}
}
}
The output is:
Excel application object not registered. Trying plan B..
GetObject still failing. Process ended.
In some rare cases "plan B" does work; I don't see the second message box.
CurrentSpreadSheet is a singleton and I intend to update it during startup from the provided class ThisAddIn.
In ThisAddIn I have something like:
private CurrentSpreadSheet css = CurrentSpreadSheet.Instance;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
///...Some code
css.updateCurrentSpreadSheet();
}
Is there a better way of getting the Application object? If this is not possible right during the startup, is there a better way by which I can keep track of currently active worksheet/workbook right from the startup of excel/my add-in? Currently I am depending on the Application object (e.g. (Excel.Workbook)this.CurrentApplication.ActiveWorkbook;) and some event handlers to keep track of the current workbook and worksheet.
I tried using ExcelDNA:
this.CurrentApplication = (Excel.Application)ExcelDna.Integration.ExcelDnaUtil.Application;
This works some of the times but mostly gives this error:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> ExcelDna.Integration.XlCallException: Exception of type 'ExcelDna.Integration.XlCallException' was thrown.
Keep in mind that an Office add-in runs inside the Office process. So you never want to find an external process. The boilerplate ThisAddIn class that you get when you use a Office project template hands you the Application object you are looking for on a silver platter, use its Application property. The first time you can get to it is in the Startup event, make sure you don't try it earlier. So don't do anything drastic in your constructor and don't initialize class members with initialization expressions, wait until Startup fires.
The relevant MSDN page is here, "Accessing the Object Model of the Host Application" section.
You might take a closer look at http://netoffice.codeplex.com/ There you can find more stuff about Add-In's for Word/Excel/Powerpoint.
Also keep in mind the GuidAttribute when you load your Add-In, because depending on your Office version it won't work anymore and also, check to kept your project whether 32/64-bit, best is Any CPU. Also, keep in mind to register your Add-In into the registry for further usage. If you want further information, don't hesitate to write me a mail.
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.guidattribute.aspx

File.WriteAllText() runs OK, or does it?

I've been starting at this code for the best part of 2 hours (literally) but I can not seem to grasp why this would fail. This method below does not report any exceptions, yet it seems to return false:
public bool SaveFile(string filename, object source)
{
bool result = true;
StringBuilder exportText = new StringBuilder(source.ToString());
try {
File.WriteAllText(filename, exportText.ToString());
}
catch (Exception e)
{
OnPluginError(new ErrorEventArgs(e));
result = false;
}
return result;
}
The problem is: the file is properly written at the requested path, is complete, and readable. No exceptions are thrown, because the OnPluginError() handler invocation method isn't called - any message would be logged in that case, but there is nothing logged. It can't be a permission problem because the file does exist after the call.
And still, the method result is false.
The problem only appears in a Release build. In Debug builds, all seems to work OK. Hence, I can't use the debugger to step through.
This is called from a web application. Any ideas appreciated.
As a temporary troubleshooting step, add another try catch to block any exceptions and then see if the function is still returning false.
public bool SaveFile(string filename, object source)
{
bool result = true;
StringBuilder exportText = new StringBuilder(source.ToString());
try {
try {
File.WriteAllText(filename, exportText.ToString());
} catch(Exception e) { }
}
catch (Exception e)
{
OnPluginError(new ErrorEventArgs(e));
result = false;
}
return result;
}
If it is returning true, then you have isolated the problem and determined that an exception is being thrown, causing the block with result = false to be run.
If it is still returning false, then you can be certain the problem is outside of this function, as the rules of control flow would dictate that the result variable would never be changed.
One possibility is you have an issue with either the code you think is being run is not really being run. For example some issue with the build process not picking up your most recent code changes or redirection. Checking the versions of the website project DLLs, doing clean/rebuild, adding additoinal code to write out trace messages, are all things you should try to cross check to verify your most recent code is being run.
Another possibility is a problem in the code that is checking the return value.
Well...I do feel a bit silly here. I finally found the problem, and it is (as some posters questioned) not related to the WriteAllText() method at all.
FYI: this code ran deep inside an extensive plugin library. Not all that code was designed and written by me, and has been around for almost 2 years without running into problems.
As I mentioned, the WriteAllText() ran fine. It did. Problem was that the location of the file saved, was stored in a Dictionary, which in turn was requested from the plugin currently running. That Dictionary (containing plugin settings) turned out to be created from scratch with each call to that property! So I could add to it as much as I wanted....at the next call to that property, the newly added items would 'disappear' magically since the Dictionary was created anew.
Since it never surfaced before, and that code ran in a lot of other plugins with no problems, I didn't check that property. My bad.
Apologies to everyone that responded for wasting their time. Rest assured it won't happen any time soon! Lesson learned...

What's a good way for a c# dll to return error to the calling application?

i'm writing a dll which is a wrapper to a access database. and i'm pretty new to c# in general as my background is in web development LAMP with perl, i'm not sure what's a good way to return error to a calling app in case they pass the wrong parameters to my functions or what not.
I have no idea as of now except to probably do some msgbox or throw some exceptions but i don't know where to start looking. Any help or resources would be more than useful :)
thanks~
You probably don't want to display message dialogs from within your dll, that's the job of the client application, as part of the presentation layer.
.Net library assemblies typically bubble up exceptions to the host application, so that's the approach I'd look at.
public static class LibraryClass
{
public static void DoSomething(int positiveInteger)
{
if (positiveInteger < 0)
{
throw new ArgumentException("Expected a positive number", "positiveInteger");
}
}
}
Then it's up to your host application to handle those exceptions, logging and displaying them as appropriate.
try
{
LibraryClass.DoSomething(-3);
}
catch(ArgumentException argExc)
{
MessageBox.Show("An Error occurred: " + argExc.ToString());
}
Wrong parameters are usually handled by throwing a ArgumentException or one of its subclasses.
You want to throw an exception.
See
http://msdn.microsoft.com/en-us/library/ms229007.aspx
for the most common framework exceptions, such as ArgumentException and InvalidOperationException. See also
http://msdn.microsoft.com/en-us/library/ms229030.aspx
Check out Design Guidelines for Class Library Developers: Error Raising and Handling Guidelines
Dlls generally should not create any kind of UI element to report an error. You can Throw (same meaning as raise) many different kinds of exceptions, or create your own and the calling code (client) can catch and report to the user.
public void MyDLLFunction()
{
try
{
//some interesting code that may
//cause an error here
}
catch (Exception ex)
{
// do some logging, handle the error etc.
// if you can't handle the error then throw to
// the calling code
throw;
//not throw ex; - that resets the call stack
}
}
throw new exception?

Categories