Auto-Save fires `DocumentBeforeSave` event - How to circumvent this? - c#

When a file is saved (on purpose) I would like to perform a certain action.
This all works with the following code:
Application.DocumentBeforeSave += new word.ApplicationEvents4_DocumentBeforeSaveEventHandler(ThisAddIn_BeforeSave);
There is only one problem, this event also fires when a change is made to the document and the 'Autorecover' function saves this change.
Is there a way to circumvent this action or at least detect if it was an auto-save?

So I've managed to find the answer to this question on this site.
Essentially, this makes use of the VBA properties of a Word application I assume.
object oBasic = Application.WordBasic;
object fIsAutoSave =
oBasic.GetType().InvokeMember(
"IsAutosaveEvent",
BindingFlags.GetProperty,
null, oBasic, null);
if (int.Parse(fIsAutoSave.ToString()) == 1)
MessageBox.Show("Is AutoSave");
else
MessageBox.Show("Is regular save");
This solution seems to work for office 2007 and up.

Related

In coded ui how do you correctly retrieve a browser window that contains an embedded Adobe PDF reader in browser

I'am running across this issue when I'm debugging or running my coded UI automation project, where i get the exception labeled "{"COM object that has been separated from its underlying RCW cannot be used." System.Exception {System.Runtime.InteropServices.InvalidComObjectException}" everytime i come from a browser window that contains a pdf reader embedded in it. This happens every time I retrieve the window and try to click back. It barfs when i perform the back method on it. I've tried different things but none has worked including the playback wait.
var hereIsmypdf = ReturnPDFDoc();
public BrowserWindow ReturnPDFDoc()
{
Playback.Wait(1000);
var myPdFdoc = GlobalVariables.Browser;
return myPdFdoc;
}
hereIsmypdf.Back();
The only way i was able to get around this issue was not to use the BrowserWindow class. I ended up using the WinWindow class and just getting the tab of the window from it. The BrowserWindow class seemed to trigger the exception "COM object that has been separated from its underlying RCW cannot be used." System.Exception {System.Runtime.InteropServices.InvalidComObjectException}" everytime i tried to retrieve it. I hope this helps someone one or maybe someone has a better way to handle this issue.
For the people that voted my question down, i really did try to figure it out. Sorry i wasnt clear about what i was asking the community or couldn't properly articulate what this pain was. I'm sure someone probably is going through the same pain i did and having a hard time articulating whats going on.
Here is my code on what i ended up doing
public WinTabPage ReturnPDFDoc()
{
WinWindow Wnd = new WinWindow();
Wnd.SearchProperties[BrowserWindow.PropertyNames.ClassName] = "IEFrame";
WinTabList tabRoWlist = new WinTabList(Wnd);
tabRoWlist.SearchProperties[WinTabPage.PropertyNames.Name] = "Tab Row";
WinTabPage myTab = new WinTabPage(tabRoWlist);
myTab.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
myTab.SearchProperties[WinTabPage.PropertyNames.Name] = "something";
//UITestControlCollection windows = newWin.FindMatchingControls();
return myTab;
}

Failed to perform action on hidden control exception

I am trying to create a UI test in VS 2010 using IE 9 in IE 8 compatibilty mode however when trying to record an action recording many of the steps fail. Then when I manually code in the missing steps and try to fill in a log in form with a username and password I get an exception that says I have failed to perform an action on hidden control.
The UI Test code:
public void Recordedmethod()
{
BrowserWindow uILogInWindowsInternetWindow = this.UILogInWindowsInternetWindow;
HtmlHyperlink uILogInHyperlink = this.UILogInWindowsInternetWindow.UIHomePageDocument.UILogInHyperlink;
HtmlEdit uIUsernameEdit = this.UILogInWindowsInternetWindow.UILogInDocument1.UIUsernameEdit;
HtmlEdit uIPasswordEdit = this.UILogInWindowsInternetWindow.UILogInDocument1.UIPasswordEdit;
#endregion
// Go to web page 'http://localhost:15856/WebSite1/'
uILogInWindowsInternetWindow.NavigateToUrl(new System.Uri(this.RecordedMethodParams.UILogInWindowsInternetWindowUrl));
// Set flag to allow play back to continue if non-essential actions fail. (For example, if a mouse hover action fails.)
Playback.PlaybackSettings.ContinueOnError = true;
// Mouse hover 'Log In' link at (1, 1)
Mouse.Click(uILogInHyperlink);
// Reset flag to ensure that play back stops if there is an error.
Playback.PlaybackSettings.ContinueOnError = false;
// Type 'test' in 'Username:' text box
uIUsernameEdit.Text = this.RecordedMethodParams.UIUsernameEditText;
// The following element is no longer available: IE web control; Process Id [6320], window handle [3168166]
// Type '********' in 'Password:' text box
uIPasswordEdit.Password = this.RecordedMethodParams.UIPasswordEditPassword;
// The following element is no longer available: IE web control; Process Id [6320], window handle [3168166]
}
This is an issue linked to an Internet Explorer patch that was released in September.
KB2870699
This affects VS2010 and VS2012.
Microsoft released a patch that corrects the issue for VS2012 (and I've confirmed that it fixed the issue for me).
http://blogs.msdn.com/b/visualstudioalm/archive/2013/09/17/coded-ui-mtm-issues-on-internet-explorer-with-kb2870699.aspx
Currently the only workaround for VS2010 is to uninstall the patch (KB2870699); however, as with any sort of security patch you'll want to consider carefully whether pulling it is safe to do given your situation.
EDIT: This was not a fun bug for me to deal with. I had just upgraded to VS2012 from VS2010 and all of a sudden I found none of my previously functioning CodedUI tests working. I assumed it was an issue with VS2012 and after banging my head against the wall for the better part of a day I found out it was an issue with a patch. It was just my luck that I upgraded to 2012 at the same time the patch had been installed on my system. Good times!
There is actually an updated for VS 2012 to fix this issue
http://blogs.msdn.com/b/visualstudioalm/archive/2013/09/17/coded-ui-mtm-issues-on-internet-explorer-with-kb2870699.aspx
Hope this helps!
I was having the same problem with my coded ui test. It's an issue with VS-2012 i guess, i tried every update (installing/uninstalling them and everything..) nothing worked.
I tried VS-2013 Ultimate and it worked.
You can use exception handling to capture the error while still not having the test failed.
The test is failing because at the time it performs click action, the control is hidden.
try
{
//your code goes here
}
catch(FailedToPerformActionOnHiddenControlException e)
{
Console.WriteLine(e.Message);
}

microsoft.interop.selection text

Before asking my question I would like to describe briefly background of my problem: I'm developing ms word COM addin on C# and I need to handle user's text selections. Now I'm able to catch selection event - it's look like
Microsoft.Interop.Word._Application app;
app = (Word._Application )Application; // Application object comes on addin's connection
app.Application.WindowSelectionChange+=
new Word.ApplicationEvents4_WindowSelectionChangeEventHandler(selChange);
///
void selChange(Word.Selection selection){
MessageBox.Show(selection.Text); // this is my problem, Text property is not available
}
// property Text doesn't exist,but documentation tells that it exists. I suspect, that this property is not available for ms word 2007 - in the documentation only 2003,2010 versions are mentioned. But how I can do something like selection.getSelectedText()? I tryed to play with selection.Rows, selection.Rows[0],selection.Words,selection.Words[0] - no success.
According to the documentation, the Selection.Text property should be available for Word 2007 as well. I made a small sample implementation of your case to test it, and I cannot make it fail on Word 2010 and 2013 at least:
var wordApplication = new Application() { Visible = true };
wordApplication.Documents.Add();
wordApplication.WindowSelectionChange += delegate(Selection mySelection) { Console.WriteLine(mySelection.Text); };
So, I suggest you check that you have included the right namespaces and that the Selection interface you are using are actually the one from the Microsoft.Office.Interop.Word namespace.

Documents.Close makes Word visible

I have been trying a workaround for this, for quite a long time, but haven't found one yet.
On calling Documents.Close(), Word, which was opened with visible = false, becomes visible.
This is my close statement (document is already saved so no need to save again):
WordApp.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges,
Word.WdOriginalFormat.wdOriginalDocumentFormat);
You could just call WordApp.Quit().
Office apps still follow the MDI approach: You run 1 App and in that app you can open 1 or more documents.
It's easy to lose track of that App in the background as we usually only open one document. But there are two levels of Close here.
You could also explicitly set WordApp.Visible = false immediately after the operation; this might cause a brief flash, but should set the application back to invisible.
To avoid the brief flash of visibility, sometimes using the WordApp.ScreenUpdating property as well can help. Set it to false before attempting the Documents.Close() call, then reset to true after that's complete.
The accepted solution (calling WordApp.Quit()) was not a viable option for me. I tried setting
WordApp.ScreenUpdating = false
immediately prior to calling Documents.Close() and that did not help either - I still got the screen flash.
I then tried setting
WordApp.ActiveWindow.Visible = false
immediately after opening the document. That did not make any difference either.
Finally I tried setting
WordApp.ActiveWindow.Top = -5000
(so as to move the window display well out of the visible desktop area in my monitor setup - if you have an unusual (giant!) monitor setup that might not work for you, adjust accordingly) and that solved the problem - no more flashing.
An annoying hack, but worked in my case.
None of above comments work for me. I tried with:
WordApp.ActiveWindow.Top = -5000
But my program terminates with "active window is maximized" exception.
I ultimately resolved it by following call before invoke Document.Close():
m_word.ActiveWindow.WindowState = WdWindowState.wdWindowStateMinimize;
It's a perfect solution for me. Hope it would work for you as well.
Using the ActiveDocument.Close() method will not show the window.
WordApp.ActiveDocument.Close(saveChanges: false);
None of the above solutions worked for me.
I finally realized that for me it was the AutoOpen macro that was the problem. Every time a Word document was opened, AutoOpen would make the ActiveDocument.Visible = False, run some changes (like opening the style pane), then turn ActiveDocument.Visible = True at the end.
This final line in AutoOpen is what caused every document to briefly flash on the screen. Removing both ActiveDocument.Visible = False and ActiveDocument.Visible = True from the AutoOpen macro solved the issue.

I must be a heretic for wanting a C# browser with both NewWindow2 and GetElementsByTagName

You can't have your cake and eat it too, apparently.
I'm currently using the System.Windows.Forms.WebBrowser in my application. The program currently depends on using the GetElementsByTagName function. I use it to gather up all the elements of a certain type (either "input"s or "textarea"s), so I can sort through them and return the value of a specific one. This is the code for that function (my WebBrowser is named web1):
// returns the value from a element.
public String FetchValue(String strTagType, String strName)
{
HtmlElementCollection elems;
HtmlDocument page = web1.Document.Window.Frames[1].Document;
elems = page.GetElementsByTagName(strTagType);
foreach (HtmlElement elem in elems)
{
if (elem.GetAttribute("name") == strName ||
elem.GetAttribute("ref") == strName)
{
if (elem.GetAttribute("value") != null)
{
return elem.GetAttribute("value");
}
}
}
return null;
}
(points to note: the webpage I need to pull from is in a frame, and depending on circumstances, the element's identifying name will be either in the name or the ref attribute)
All of that works like a dream with the System.Windows.Forms.WebBrowser.
But what it is unable to do, is redirect the opening of a new window to remain in the application. Anything that opens in a new window shoots to the user's default browser, thus losing the session. This functionality can be easily fixed with the NewWindow2 event, which System.Windows.Forms.WebBrowser doesn't have.
Now forgive me for being stunned at its absence. I have but recently ditched VB6 and moved on to C# (yes VB6, apparently I am employed under a rock), and in VB6, the WebBrowser possessed both the GetElementsByTagName function and the NewWindow2 event.
The AxSHDocVw.WebBrowser has a NewWindow2 event. It would be more than happy to help me route my new windows to where I need them. The code to do this in THAT WebBrowser is (frmNewWindow being a simple form containing only another WebBrowser called web2 (Dock set to Fill)):
private void web1_NewWindow2(
object sender,
AxSHDocVw.DWebBrowserEvents2_NewWindow2Event e)
{
frmNewWindow frmNW = new frmNewWindow();
e.ppDisp = frmNW.web2.Application;
frmNW.web2.RegisterAsBrowser = true;
frmNW.Visible = true;
}
I am unable to produce on my own a way to replicate that function with the underwhelming regular NewWindow event.
I am also unable to figure out how to replicate the FetchValue function I detailed above using the AxSHDocVw.WebBrowser. It appears to go about things in a totally different way and all my knowledge of how to do things is useless.
I know I'm a sick, twisted man for this bizarre fantasy of using these two things in a single application. But can you find it in your heart to help this foolish idealist?
I could no longer rely on the workaround, and had to abandon System.Windows.Forms.WebBrowser. I needed NewWindow2.
I eventually figured out how to accomplish what I needed with the AxWebBrowser. My original post was asking for either a solution for NewWindow2 on the System.Windows.Forms.WebBrowser, or an AxWebBrowser replacement for .GetElementsByTagName. The replacement requires about 4x as much code, but gets the job done. I thought it would be prudent to post my solution, for later Googlers with the same quandary. (also in case there's a better way to have done this)
IHTMLDocument2 webpage = (IHTMLDocument2)webbrowser.Document;
IHTMLFramesCollection2 allframes = webpage.frames;
IHTMLWindow2 targetframe = (IHTMLWindow2)allframes.item("name of target frame");
webpage = (IHTMLDocument2)targetframe.document;
IHTMLElementCollection elements = webpage.all.tags("target tagtype");
foreach (IHTMLElement element in elements)
{
if (elem.getAttribute("name") == strTargetElementName)
{
return element.getAttribute("value");
}
}
The webbrowser.Document is cast into an IHTMLDocument2, then the IHTMLDocument2's frames are put into a IHTMLFramesCollection2, then I cast the specific desired frame into an IHTMLWindow2 (you can choose frame by index # or name), then I cast the frame's .Document member into an IHTMLDocument2 (the originally used one, for convenience sake). From there, the IHTMLDocument2's .all.tags() method is functionally identical to the old WebBrowser.Document.GetElementsByTagName() method, except it requires an IHTMLElementCollection versus an HTMLElementCollection. Then, you can foreach the collection, the individual elements needing to be IHTMLElement, and use .getAttribute to retrieve the attributes. Note that the g is lowercase.
The WebBrowser control can handle the NewWindow event so that new popup windows will be opened in the WebBrowser.
private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
{
// navigate current window to the url
webBrowser1.Navigate(webBrowser1.StatusText);
// cancel the new window opening
e.Cancel = true;
}
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/361b6655-3145-4371-b92c-051c223518f2/
The only solution to this I have seen was a good few years ago now, called csExWb2, now on Google code here.
It gives you an ExWebBrowser control, but with full-on access to all the interfaces and events offered by IE. I used it to get deep and dirty control of elements in a winforms-hosted html editor.
It may be a bit of a leap jumping straight into that, mind.

Categories