Posts Tagged .Net 4

C# Open Word Documents using Visual Studio 2010 and .Net 4

With VS2010 and .Net 4, working with the office interops has become a lot easier. This article gives a step by step view of how to open a word document without needing the tools of Visual Studio Tools for Office (VSTO). *

The following topics are demonstrated:

  1. Open and properly close a Word Document.
  2. Write to a Word document.
  3. Remove the Word document’s meta data.
  4. Properly close the Word Application and clean up resources opened by the underlying Office Interop calls.
  5. Properly cast method calls to specific interops to avoid “Ambiguity between method” issue CS0467 C# compiler warning.
  6. Why the developer no longer has to reference null when passing in optional parameters to COM objects thanks to .Net 4.

Steps

  1. In VS2010 create a Console Application.
  2. In the Solutions Explorer right click on the References folder and select Add Reference.  In the .Net tab search for
    Microsoft.Office.Interop.Word.
    Note you can use version 12 or version 14; but you might as well use the latest 14.  
  3. Insert the following usings:
    using Microsoft.Office.Interop.Word;
  4. Create an existing Word document. The example code below uses an existing document at C:\TestDoc.docx.
  5. Insert this code:
    Application ap = new Application();
    
    try
    {
    
        Document doc = ap.Documents.Open( @"C:\TestDoc.docx", ReadOnly: false, Visible: false );
        doc.Activate();
    
        Selection sel =  ap.Selection;
    
        if ( sel != null )
        {
            switch ( sel.Type )
            {
                case WdSelectionType.wdSelectionIP:
                    sel.TypeText( DateTime.Now.ToString() );
                    sel.TypeParagraph();
                    break;
    
                default:
                    Console.WriteLine( "Selection type not handled; no writing done" );
                    break;
    
            }
    
            // Remove all meta data.
            doc.RemoveDocumentInformation( WdRemoveDocInfoType.wdRDIAll );
    
            ap.Documents.Save( NoPrompt: true, OriginalFormat: true );
    
        }
        else
        {
            Console.WriteLine( "Unable to acquire Selection...no writing to document done.." );
        }
    
        ap.Documents.Close( SaveChanges: false, OriginalFormat: false, RouteDocument: false );
    
    }
    catch ( Exception ex )
    {
        Console.WriteLine( "Exception Caught: " + ex.Message ); // Could be that the document is already open (/) or Word is in Memory(?)
    }
    finally
    {
        // Ambiguity between method 'Microsoft.Office.Interop.Word._Application.Quit(ref object, ref object, ref object)' and non-method 'Microsoft.Office.Interop.Word.ApplicationEvents4_Event.Quit'. Using method group.
        // ap.Quit( SaveChanges: false, OriginalFormat: false, RouteDocument: false );
        ( (_Application)ap ).Quit( SaveChanges: false, OriginalFormat: false, RouteDocument: false );
    
        System.Runtime.InteropServices.Marshal.ReleaseComObject( ap );
    }

Explanation

  • Line 1: Open Word application object found in the Microsoft.Office.Interop.Word namespace.
  • Line 6: Open up the Word document we are interested in. This is first instance of using named parameters in calling the underlying COM functionality.
  • Line 7: Activate makes sure our document has focus in the event that Word is already open.
  • Line 9-17: This code is a template to working with a selection and its type. Word distinguishes areas of interest by selections. Our selection is at the beginning of the document. When we get the selection we write the current date and time (line 16).
  • Line 27: Remove all of the meta data of the document. This is not required for writing, just as an added bonus of how-to.
  • Line 29: Save what we have done.
  • Line 37: Close the document.
  • Line 48: In line 47 if we call without the cast we get the ambiguity warning message from the compiler. By casting to the Application interface we avoid that warning.
  • Line 50: Release any COM handles or resources we may have inadvertently gotten in this process.

 

* For the record VSTO is only needed when we are creating a smart document or an addin to one of the office applications. This is pure interop programming and not VSTO.

  • Share/Bookmark

Tags: ,

SQL Server SP1 Setup: Does it really need a beta version of .Net 4?

BabyWaitingI  upgraded my development box to Windows 7 and ignored, whistled past the graveyard as it were, the warning that SQL Server 2008 should be uninstalled due to incompatibilities. Upon the new OS install/upgrade I ventured out and tried to bring up the management studio. Much to my chagrin it crapped out on me, ya chagrin thats it.

So with that darned internet so handy I researched came to the conclusion, from the advice of the internet millions that SP1 should be installed to get it to work on Windows 7. Here is what greeted me for my efforts once as I attemped install:

SP1 2008

Maybe you are reading this in the future where there is a flying car in every drive way and hanging a television on a wall is really passé because the wall is a TV; but as of this writing .Net 4 is only in beta.

So here is the text (a little trick which one can do is that on most dialogs one can do CTRL-C and get the text copied to the clipboard) as received:

—————————
setup.exe – .NET Framework Initialization Error
—————————
To run this application, you first must install one of the following versions of the .NET Framework:

  v4.0.20506

Contact your application publisher for instructions about obtaining the appropriate version of the .NET Framework.

So I leave it up to you my small but loyal (?) readership what is going on? Here is what I know

  1. Upgraded from Vista to Windows 7.
  2. Visual Studio 2010 version is installed but doesn’t run. So there is a version of .Net 4 on my system…
    NetVersions
  3. It all worked before I upgraded. ;-)

Thoughts?

  • Share/Bookmark

Tags: ,

OmegaMan's Musings is Digg proof thanks to caching by WP Super Cache