locked
Word 2007 bookmarks NullReferenceException RRS feed

  • Question

  • Hello!

    I use Vista SP1 x64, VS2008SP1 and MS Office 2007 SP1 for creating Word 2007 add-in
    I want following: when I open document, or create new from any templates, I want to analyze document content on my special bookmarks. If I found any of it, I create wrapper - Microsoft.Office.Tools.Word.Bookmark control, where handle Selected and Deselected events.
    But when I open more than 1 Word windows and after that close all Word's windows, and my add-in is shutting down, I have NullReferenceException

    Here is source code for reproduce this behavior:

    using System.Collections.Generic;  
    using System.Linq;  
    using Microsoft.Office.Interop.Word;  
    using Word = Microsoft.Office.Interop.Word;  
    using Office = Microsoft.Office.Core;  
    using Microsoft.Office.Tools.Word;  
    using Microsoft.Office.Tools.Word.Extensions;  
    using Document=Microsoft.Office.Interop.Word.Document;  
     
    namespace WordAddIn2  
    {  
        public partial class ThisAddIn  
        {  
            List<Document> _activeDocs = new List<Document>();  
     
            private void ThisAddIn_Startup(object sender, System.EventArgs e)  
            {  
                this.Application.WindowActivate += Application_WindowActivate;  
                this.Application.DocumentBeforeClose += new ApplicationEvents4_DocumentBeforeCloseEventHandler(Application_DocumentBeforeClose);  
                  
            }  
     
            void Application_DocumentBeforeClose(Document Doc, ref bool Cancel)  
            {  
                if(_activeDocs.Contains(Doc))  
                {  
                    _activeDocs.Remove(Doc);  
                }  
            }  
     
            void Application_WindowActivate(Document Doc, Window Wn)  
            {  
                if (_activeDocs.Contains(Doc) == false)  
                {  
                    CheckAndRegister(Doc);  
                    _activeDocs.Add(Doc);  
                }  
            }  
     
            void CheckAndRegister(Document Doc)  
            {  
                if (Doc.Bookmarks.Count > 0)  
                {  
                    Microsoft.Office.Tools.Word.Document extendedDoc = Doc.GetVstoObject();  
                    for (int i = 1; i <= Doc.Bookmarks.Count; i++)  
                    {  
                        object index = i;  
                        Word.Bookmark interopBookmark = Doc.Bookmarks.get_Item(ref index);  
                        if (BkmIds.Ids.Contains(interopBookmark.Name))  
                        {  
                            Microsoft.Office.Tools.Word.Bookmark vstoBookmark = extendedDoc.Controls.AddBookmark(interopBookmark, interopBookmark.Name);  
     
                            vstoBookmark.Selected += vstoBookmark_Selected;  
                            vstoBookmark.Deselected += vstoBookmark_Deselected;  
                            //vstoBookmark.Dispose();  
                        }  
                    }  
                }  
            }  
     
            void vstoBookmark_Deselected(object sender, SelectionEventArgs e)  
            {  
                //Microsoft.Office.Tools.Word.Bookmark bookmark = sender as Microsoft.Office.Tools.Word.Bookmark;  
                //if (bookmark != null)  
                //{  
                //    bookmark.Bold = 0;  
                //}  
            }  
     
            void vstoBookmark_Selected(object sender, SelectionEventArgs e)  
            {  
                //Microsoft.Office.Tools.Word.Bookmark bookmark = sender as Microsoft.Office.Tools.Word.Bookmark;  
                //if (bookmark != null)  
                //{  
                //    bookmark.Bold = 1;  
                //}  
            }  
     
            private void ThisAddIn_Shutdown(object sender, System.EventArgs e)  
            {  
     
            }
            
            #region VSTO generated code  
     
            /// <summary>  
            /// Required method for Designer support - do not modify  
            /// the contents of this method with the code editor.  
            /// </summary>  
            private void InternalStartup()  
            {  
                this.Startup += new System.EventHandler(ThisAddIn_Startup);  
                this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);  
            }
            
            #endregion  
        }  
    }  
     

    BkmIds is following class:
    public class BkmIds  
        {  
            public const string Diagnosis = "DIAGNOSE_BOOKMARK";  
            public const string Poison = "POISON_BOOKMARK";  
     
            public static IEnumerable<string> Ids  
            {  
                get 
                {  
                    return new[] { Diagnosis, Poison };  
                }  
            }  
        } 

    Details of NullReferenceException:
    Data: {System.Collections.ListDictionaryInternal}
    InnerException: null
    Source: "Microsoft.VisualStudio.Tools.Office.HostAdapter.v9.0"
    StackTrace:
       in Microsoft.VisualStudio.Tools.Office.Internal.HostItemProviderExtendedContractAdapter.Microsoft.VisualStudio.Tools.Office.IComReferenceRelease.ReleaseComReference(Object instance)
       in Microsoft.Office.Tools.Word.Adapter.DocumentControlCollectionAdapter.OnFinalRevoke()
       in System.AddIn.Pipeline.ContractBase.RevokeLifetimeToken(Int32 token)
       in System.AddIn.Pipeline.ContractHandle.Dispose(Boolean disposing)
       in Microsoft.VisualStudio.Tools.Applications.ContractLock`1.Dispose(Boolean disposing)
       in System.AddIn.Pipeline.ContractHandle.Finalize()
    TargetSite: {Void Microsoft.VisualStudio.Tools.Office.IComReferenceRelease.ReleaseComReference(System.Object)}

    This exception is thrown if I only open more than 1 instance of Word 2007.

    May be, I should free any resources, used by Microsoft.Office.Tools.Word.Bookmark? But where and when?

    Thanks a lot for any help!
    Sunday, March 15, 2009 4:42 PM

Answers

  • Hello Vitaly,

    I can also reprodcue this error. Interestingly, I noticed that the error goes away if you do not handle the bookmark events.

    I have opened a bug on this issue against the VSTO product team. I will report back to this thread as soon as I find out anything more.

    I hope this helps,
    McLean Schofield
    This posting is provided "AS IS" with no warranties, and confers no rights.
    • Marked as answer by Tim Li Monday, March 23, 2009 2:23 AM
    Monday, March 16, 2009 11:02 PM
    Answerer

All replies

  • <<This exception is thrown if I only open more than 1 instance of Word 2007. >>

    Are you sure you mean more than 1 instance, or do you mean more than 1 document. Word has a pseudo-MDI interface, so will by default display each document in a separate application window. But those will all be a single instance of the application...
    Cindy Meister, VSTO/Word MVP
    Monday, March 16, 2009 2:04 PM
  • Hi, Cindy!

    You are right - only 1 instance of Word app is work (Task Manager detect that only 1 winword.exe running).

    I want to say: "This exception is thrown if I only open more than 1 Word document".
    Sorry for mistake.

    But what about this exception? Is this a bug, or I don't understand something?
    Monday, March 16, 2009 7:32 PM
  • Hello Vitaly,

    I can also reprodcue this error. Interestingly, I noticed that the error goes away if you do not handle the bookmark events.

    I have opened a bug on this issue against the VSTO product team. I will report back to this thread as soon as I find out anything more.

    I hope this helps,
    McLean Schofield
    This posting is provided "AS IS" with no warranties, and confers no rights.
    • Marked as answer by Tim Li Monday, March 23, 2009 2:23 AM
    Monday, March 16, 2009 11:02 PM
    Answerer
  • Ok, thank you, McLean, I'll wait for the response
    Tuesday, March 17, 2009 12:56 AM
  • Hi,
    Did you find a solution to this issue? I am now just where you where last March ;).

    I get this exception thrown when I try to open more than one Word document.

    Interestingly enough, it seems to be my Interop.Word.ApplicationClass object that fails!

    This is how my Open() method looks
    using MSWord = Microsoft.Office.Interop.Word;

    // Defining the MS Word application
    MSWord.ApplicationClass WordApplication;

    // Create and set the objects to pass to MS Word's Open() and SaveAs() methods
    object ReadOnly = false;
    object Visible = false;
    object NoParameter = Type.Missing;
    object Utf8Encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;

    MSWord.Document documentFile = WordApplication.Documents.Open( ref fileObject, ref NoParameter, ref ReadOnly, ref NoParameter, ref NoParameter, ref NoParameter, ref NoParameter, ref NoParameter, ref NoParameter, ref formatOfFile, ref Utf8Encoding, ref Visible, ref NoParameter, ref NoParameter, ref NoParameter, ref NoParameter);

    Now, if I iterate over the Open() method above, I get the NullReferenceException exception. But checking out WHICH was the funky object without a reference in my second pass, I found out that it was actually
    WordApplication
    which is of type
    Microsoft.Office.Interop.Word.ApplicationClass...
    and all other objects reference a valid value.

    Clues?

    :]


    Monday, July 6, 2009 8:11 PM
  • Interestingly enough, it seems to be my Interop.Word.ApplicationClass object that fails!

    Well, of course, as I was terminating the object WordApplication after the first run of Open() !! (dumb me!) :$

    I had misplaced the line that destructed the WordApplication object inside the foreach{} block, instead of outside.
    That's why I got the null value on the second iteration (of the foreach block.)

    Vitaly, this may not help much but, check the curly brackets nearby destructors. (dumb me again!)

    Pablo
    Monday, July 6, 2009 9:47 PM
  • Hi, Pablo!

    Solution of my problems I posted here

    I just use Microsoft.Office.Interop.Word.Bookmark and ContentControlOnEnter& ContentControlOnExit instead of Microsoft.Office.Tools.Word and Selected&Deselected

    In the comment section to blog post you can find link to sample project.
    Tuesday, July 7, 2009 2:07 AM
  • McLean, what ever happened as a result of the bug report? I'm running into the same problem.
    Friday, August 6, 2010 7:07 PM