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
Related
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!
}
Got an issue where I am a COM type in c# using
this.rtwbType = Type.GetTypeFromProgID(progId, true);
this.rtwb = Activator.CreateInstance(this.rtwbType);
I am then doing some stuff, and when I am done I call exit on the rtwb - so it can close down, and then calling:
Marshal.ReleaseComObject(this.rtwb);
In 2008 R2 this is fine and dandy - but the instance we take to 2012 an exception is thrown here.
System.Runtime.InteropServices.COMException (0x800706BA): The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
like I say works fine elsewhere.
Any pointers?
The following code reproduces this error (at least under Windows 8.1):
var type = Type.GetTypeFromProgID("InternetExplorer.Application", true);
dynamic ie = Activator.CreateInstance(type);
ie.Quit(); // this disconnects the COM proxy from the out-of-proc IE object
Marshal.ReleaseComObject(ie); // throws
Apparently, the implementation of ReleaseComObject is doing something more than calling IUnknown::Release, when it deals with a COM proxy object. My guess is, it may be calling IRemUnknown::RemRelease, which returns HRESULT with an error, so ReleaseComObject throws, because the out-of-proc object has been already disconnected and destroyed with ie.Quit().
Presumably, this behavior was introduced in Windows Server 2012.
The best thing you could probably do is to ignore this specific error:
try
{
Marshal.ReleaseComObject(ie);
}
catch (COMException ex)
{
// I'm getting 0x80010108, rather than 0x800706BA
// The object invoked has disconnected from its clients. (Exception from HRESULT: 0x80010108 (RPC_E_DISCONNECTED)
if ((uint)ex.ErrorCode != 0x80010108)
throw;
}
Updated: this is the expected behavior for an API like Quit, it doesn't violate any COM rules. The goal of Quit is to provide an API for explicit shutdown. I believe it uses CoDisconnectObject internally, as a part of the shutdown process. This disconnects all external proxy references, so the server knows it can shut down safely.
The fact that ReleaseComObject is still trying to do some stuff after that (like, most likely, calling IUnknown::QueryInterface on the disconnected proxy) is not a fault of the COM server.
I'm assuming that rtwb is an InternetExplorer.Application, as Noseratio's test seems to replicate the issue rather well.
It seems Internet Explorer's Quit() method is not really safe to call outside the application's context, e.g. through out-of-process automation. It violates the rules of COM server applications.
For instance, Office applications keep running while there are external references, even after Quit(), so this is really a bit unexpected.
For safety, you can let the reference go when quitting, using the OnQuit event:
using System;
using System.Threading;
using System.Runtime.InteropServices;
public class TestIE
{
public static void Main()
{
Console.WriteLine("Creating application");
dynamic app = Activator.CreateInstance(Type.GetTypeFromProgID("InternetExplorer.Application"));
Console.WriteLine("Created application");
app.Visible = true;
app.OnQuit += new Action(() => {
Console.WriteLine("Entered OnQuit");
Marshal.ReleaseComObject(app);
app = null;
Console.WriteLine("Leaving OnQuit");
});
Console.WriteLine("Sleeping");
Thread.Sleep(5000); // enough time to see if iexplore.exe is running
Console.WriteLine("Slept");
Console.WriteLine("Quitting");
app.Quit();
Console.WriteLine("Quit");
Console.WriteLine("Sleeping");
Thread.Sleep(5000); // enough time to see if iexplore.exe is running
Console.WriteLine("Slept");
Console.WriteLine(app == null);
}
}
If you really need to use ReleaseComObject, discard any exceptions it might throw. I'm not sure if you should discard only COMException, try it out during development.
I'm getting an intermittent error when using Outlook interop within my program. I get users reporting this error every now and then, but it's impossible to reproduce on my end. What's even stranger is that if they restart the program and try again, the error is gone.
Here's the code I'm using to get a reference to Outlook.
public class CommonStuff
{
public static void Initialize()
{
olk = new Microsoft.Office.Interop.Outlook.Application();
olk.ItemSend += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_ItemSendEventHandler(OutlookInterop_ItemSend);
}
public static Microsoft.Office.Interop.Outlook.Application GetOutlook()
{
if (Process.GetProcessesByName("OUTLOOK").Count() == 0) //previous attempt at fixing this issue, and i'm not sure if i even need this
{
olk = new Microsoft.Office.Interop.Outlook.Application();
}
return olk;
}
}
And the code that's used when sending the actual email.
public void SendEmail()
{
Microsoft.Office.Interop.Outlook.MailItem eMail = (Microsoft.Office.Interop.Outlook.MailItem)CommonStuff.GetOutlookApp().CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
eMail.Subject = String.Format("Subject");
eMail.To = "email#things.com";
eMail.Companies = "Company";
eMail.Body = "blah blah blah";
eMail.Attachments.Add(GetCrystalReportPDF());
((Microsoft.Office.Interop.Outlook._MailItem)eMail).Display();
}
Unfortunately I don't know where exactly the error is happening because I can't reproduce the bug. Does anyone have any clues as to what's going on?
This is the classic kind of problem with process interop, you get to troubleshoot all of the bugs and crashes of that other process as well. "RPC server is not available" is a very generic error and doesn't mean anything more than "the process doesn't work anymore". A few simple reasons for that, it could simply have crashed or the user terminated it. Outlook is in general a troublemaker, it isn't exactly the most stable program in Office.
Your work-around with Process.GetProcessesByName() is a fair attempt but it is unlikely to work. Users commonly already have Outlook running for their own use, you'll see that instance as well. You can't tell if that process you see is the one that you started and matches your olk instance or is the one that user is looking at.
The proper workaround is to re-create your olk instance when you get the exception. That can be hard to deal with since it might be generated while you are deeply nested in your code. But it is best to not fix that case, because that hints at your code inducing the crash, you don't want to hide that problem. Implement a "canary test", just sniff at an innocent property before you start doing something non-trivial. If that induces the exception then recreate the instance. Do test this, I'm not 100% sure that the old olk instance is going to bomb your program when it gets finalized. You ought to get a repro by killing Outlook.exe with Task Manager.
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...
I've built a program in C# Windows Forms, now on the first load up it tries to create scheduled tasks. If it raises an exception and it's in main computer then this is the first time the softwere loads (you can intall this program on many computers but one computer is the main with the scheduled tasks).
I've tried this program on many computers and it worked perfectly (XP-SP1/2, Vista-SP1/2, Win7), now when I try to install it on a limited user (on Win XP Pro SP2) it tries to create the scheduled tasks. I get an Argument Null Reference and when I enter the admin user, it installs the scheduled task on the admin user and won't run if the limited user is logged in (which is 99.9% of the time) .Why do I get this exception? I've looked for hours on the code searching for the reason of this exception but I can't find it!
Thanks a lot!
Amit
MainOrSec = true;
User and Pass are public variables whice return from FirstTimeUp.
private bool CreateNoExit()
{
try
{
RegistryKey key = Registry.CurrentUser;
key = key.OpenSubKey("Crm");
MainOrSec = Convert.ToBoolean(AESIMP.Decrypt((string)key.GetValue(AESIMP.Encrypt("MorS"))));
}
catch (ArgumentNullException)
{
MainOrSec = true;
}
if (MainOrSec)
{
ScheduledTasks sc = new ScheduledTasks();
Task task;
try
{
task = sc.CreateTask("NoExit");
FirstTimeUp f = new FirstTimeUp(this);
f.ShowDialog();
}
catch (ArgumentException)
{
return false;
}
if (!CreatT)
return false;
task.ApplicationName = #"C:\Program Files\Triffon\Crm Setup
2.0.0002\noexit.exe";
task.Comment = "Check For no exit on the database.";
task.SetAccountInformation(User, Pass);
task.IdleWaitMinutes = 10;
task.Triggers.Add(new DailyTrigger(5, 0));
try
{
task.Save();
task.Close();
sc.Dispose();
}
catch (COMException ex)
{
MessageBox.Show(ex.Message);
return false;
}
return true;
}
return false;
}
OK, so if you get an exception, the best thing to do is to run your program under Visual Studio's debugger so you can see exactly where the exception is called. Here, Ctrl-Alt-E is your friend: turn on the checkbox in the "Thrown" column next to "Common Language Runtime Exceptions" and you'll break to the debugger no matter what.
If you are testing your application on a user's computer without Visual Studio then you have some other options. One (if you're using Pro and above) is to run the Remote Debugger on the remote PC. Then you can attach to the running program and see the exception.
If you don't have Pro, or can't easily use the remote debugger, then it is definitely worth using a decent logging framework like log4net to make sure that all exceptions are caught, trapped, and written to a log file. Frankly no production application should be released until this is done.
When you've done this, take a careful look at the exception trace to see where the problem is caused. I'd be willing to bet that that ScheduledTasks class is throwing an exception somewhere that you're not expecting.
Finally, you'll be getting downvotes because the culture here is "we'll help if you let us know everything we need to know to help." There's been a couple of requests in the comments for the full stack trace, which hasn't appeared, so people here will consider that rude, I'm afraid.
It's hard to figure this out without a stack trace, but there is a suspicious line of code.
According to MSDN RegistryKey.GetValue() returns:
The value associated with name, or a
null reference (Nothing in Visual
Basic) if name is not found.
Here you pass the result of that function directly to another function:
MainOrSec = Convert.ToBoolean(AESIMP.Decrypt((string)key.GetValue(AESIMP.Encrypt("MorS"))));
Try to call it in a few steps instead, checking for null where needed:
string s = key.GetValue(AESIMP.Encrypt("MorS")) as string;
if(!string.IsNullOrEmpty(s))
MainOrSec = Convert.ToBoolean(AESIMP.Decrypt(s));
else
MainOrSec = true;