tags:

views:

1103

answers:

0

i am open word document using word(Word 11.0 library , version 8.3) reference. it opens fine. And then i am working on Document events (like DocumentBeforeprint , documentbeforesave ..).at the time the word document DocumentBeforeprint event parameter word.Document DOC throws An error.

error is function evaluation time out.

my code is

// Global Diclaration of Word object

    Word.ApplicationClass oWordApp = new Word.ApplicationClass();
    Word.Document oWordDoc;        
    object readOnlytrue = true;
    object readOnlyfalse = false;
    object isVisible = true;
    object password = "abc";
    object Count = 200;
    object missing = System.Reflection.Missing.Value;

    private void CreatePdf(string strSeverPath)
    {
        object fileName = strSeverPath;
        object temp = WdTemplateType.wdNormalTemplate;
        object newtemp = false;
        object doctype = WdDocumentType.wdTypeTemplate;
        object visbule = true;
        //oWordDoc = oWordApp.Documents.Add(ref fileName, ref missing, ref missing, ref missing);
        oWordDoc = oWordApp.Documents.Open(ref fileName,
                                   ref missing, ref readOnlytrue,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing, ref isVisible,
                                   ref missing, ref missing, ref missing, ref missing);
        oWordDoc = oWordApp.ActiveDocument;
        oWordDoc.CommandBars.ActiveMenuBar.Enabled = true;
        oWordDoc.ActiveWindow.Application.CommandBars["Standard"].Visible = true;
        oWordDoc.ActiveWindow.Application.CommandBars["Frames"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Forms"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Picture"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Visual Basic"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Web"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Web Tools"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["WordArt"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Reading Layout"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Reviewing"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Formatting"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Drawing"].Enabled = false;

        //INSERTING TEXT IN THE CENTRE RIGHT, TILTED AT 90 DEGREES
        oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader;
        Word.Shape midRightText;

        midRightText = oWordApp.Selection.HeaderFooter.Shapes.AddTextEffect(
            Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1,
            "Display Copy", "Arial", (float)40,
            Microsoft.Office.Core.MsoTriState.msoTrue,
            Microsoft.Office.Core.MsoTriState.msoFalse,
            0, 0, ref missing);
        //FORMATTING THE SECURITY CLASSIFICATION TEXT
        midRightText.Select(ref missing);
        midRightText.Name = "PowerPlusWaterMarkObject2";            
        midRightText.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
        midRightText.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;
        midRightText.Fill.Solid();
        midRightText.Fill.ForeColor.RGB = (int)Word.WdColor.wdColorGray375;
        midRightText.ZOrder(Microsoft.Office.Core.MsoZOrderCmd.msoBringToFront);
        //MAKING THE TEXT VERTICAL & ALIGNING
        midRightText.Rotation = (float)-45;
        midRightText.Fill.Transparency = 0.6f;
        midRightText.RelativeHorizontalPosition =
            Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin;
        midRightText.RelativeVerticalPosition =
            Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionMargin;
        midRightText.Top = (float)Word.WdShapePosition.wdShapeCenter;
        midRightText.Left = (float)Word.WdShapePosition.wdShapeCenter;
        midRightText.Height = oWordApp.InchesToPoints(2f);
        midRightText.Width = oWordApp.InchesToPoints(5f);
        int i = midRightText.ID;

        //SETTING FOCUES BACK TO DOCUMENT
        oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

        if (oWordDoc.ProtectionType == Word.WdProtectionType.wdNoProtection)
        {
            oWordDoc.Protect(Word.WdProtectionType.wdAllowOnlyFormFields, ref missing, ref password, ref missing, ref isVisible);
        }

        //unprotect
        //oWordDoc.Unprotect(ref password);

        oWordApp.DocumentBeforePrint += new Word.ApplicationEvents4_DocumentBeforePrintEventHandler(oWordApp_DocumentBeforePrint);
        oWordApp.DocumentBeforeClose += new ApplicationEvents4_DocumentBeforeCloseEventHandler(oWordApp_DocumentBeforeClose);
        oWordApp.DocumentBeforeSave += new ApplicationEvents4_DocumentBeforeSaveEventHandler(oWordApp_DocumentBeforeSave); 
        oWordApp.DocumentChange += new ApplicationEvents4_DocumentChangeEventHandler(oWordApp_DocumentChange);

        //oWordDoc.ActiveWindow.Application.CommandBars["File"].Enabled = true; 
        //oWordDoc.ActiveWindow.Application.CommandBars["File"].FindControl(missing, 18, missing, missing, missing).Enabled = true;
        //oWordDoc.ActiveWindow.Application.CommandBars["File"].FindControl(missing, 4, missing, missing, missing).Enabled = true;
        //oWordDoc.ActiveWindow.Application.CommandBars["File"].FindControl(missing, 3, missing, missing, missing).Enabled = true;            
        ////oWordDoc.ActiveWindow.Application.CommandBars["File"].FindControl(missing, 5, missing, missing, missing).Enabled = false;
        //object i = 3;            
        //oWordDoc.ActiveWindow.Application.CommandBars["Standard"].FindControl(missing, i, missing, missing,missing).Visible = true;           
       // oWordDoc.CommandBars.ActiveMenuBar.FindControl(missing, 1, missing, missing, missing).OnAction.Remove(1); 

        string ac = oWordDoc.ActiveWindow.Application.CommandBars["File"].FindControl(missing, 3, missing, missing, missing).Id.ToString();// = Microsoft.Office.Core.MsoControlOLEUsage.msoControlOLEUsageNeither; 
        oWordDoc.Saved = true;
        oWordApp.Visible = true;
        oWordDoc.Activate();

    }
    private void documentSettings()
    {
       oWordDoc.PageSetup.BottomMargin = 0;
       oWordDoc.PageSetup.TopMargin = 40f;
       oWordDoc.PageSetup.FooterDistance = 0.4f;
       oWordDoc.PageSetup.FooterDistance = 0.4f;
    }


    void oWordApp_DocumentChange()
    {
        //throw new NotImplementedException();
       // string abc = oWordDoc.Path.ToString();
       //if(oWordDoc.Path.ToString() == @" C:\Documents and Settings\11608\My Documents\Visual Studio 2008\Projects\StandardOperatingProcedure\StandardOperatingProcedure\Documents\Annexures")
       //{

       //}
    }

    protected void oWordApp_DocumentBeforeClose(Word.Document Doc, ref bool Cancel)
    {
        oWordDoc.Close(ref missing, ref missing, ref missing);
        oWordApp.Quit(ref missing, ref missing, ref missing);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordApp);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordDoc);                      
    }       

    protected void oWordApp_DocumentBeforePrint(Word.Document Doc, ref bool Cancel)
    {
        try
        {
            oWordDoc = oWordApp.ActiveDocument;

            oWordDoc.Unprotect(ref password);

            oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
            oWordApp.ActiveWindow.Application.Selection.WholeStory();
            string strtext = "Printed By : " + Session["UserID"].ToString() + "  -  " + DateTime.Now.ToString("dd/MM/yyyy");
            string abc = oWordApp.ActiveWindow.Selection.Text;
            if (abc.Contains(strtext))
            {

            }
            else
            {
                // Remove WaterMark

                oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader;
                Word.ShapeRange midRightText;
                object name = "PowerPlusWaterMarkObject2";
                midRightText = oWordApp.Selection.HeaderFooter.Shapes.Range(ref name);
                midRightText.Delete();
                oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

                // Remove WaterMark  

                oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
                //oWordDoc.PageSetup.BottomMargin = 0;
                ////oWordDoc.PageSetup.TopMargin = 0.10f;
                //oWordDoc.PageSetup.FooterDistance = 0.4f;
                documentSettings();


                oWordApp.Selection.TypeParagraph();

                oWordApp.Selection.MoveDown(ref missing, ref Count, ref missing);
                oWordDoc.ActiveWindow.Application.Selection.EndKey(ref missing, ref missing);
                oWordApp.ActiveWindow.Selection.TypeText("\n");
                oWordApp.ActiveWindow.Selection.TypeText("\n");
                oWordApp.ActiveWindow.Selection.Font.Name = "Arial";
                oWordApp.ActiveWindow.Selection.Font.Size = 12;
                if (Session["UserID"] != null)
                {
                    oWordApp.ActiveWindow.Selection.TypeText("Printed By : " + Session["UserID"].ToString() + "  -  " + DateTime.Now.ToString("dd/MM/yyyy"));
                    oWordApp.ActiveWindow.Selection.TypeText("\t");
                    oWordApp.ActiveWindow.Selection.TypeText("\t");
                    //oWordApp.ActiveWindow.Selection.TypeText("\t");
                    Word.InlineShape CustLogo;
                    //String logoPath = "D:\\Malyadri\\Refresh.gif";
                    string strSecurityLogoPath = Server.MapPath(string.Empty);

                    strSecurityLogoPath = strSecurityLogoPath + "\\Images\\Security_img4.gif";
                    //object fileName = strSeverPath
                    //String logoPath = 

                    CustLogo = oWordApp.ActiveWindow.Selection.InlineShapes.AddPicture(strSecurityLogoPath, ref missing, ref missing, ref missing);
                    string type = CustLogo.Type.ToString();
                    CustLogo.Select();
                    CustLogo.AlternativeText = "PowerPlusInlineObject2";
                    SqlConnection conn = new SqlConnection();
                    conn.ConnectionString = "server=APLU7-DSK-057; user id=sa; password=password123; database =DisplaySops";
                    conn.Open();
                    string date2 = DateTime.Now.ToString("dd/MM/yyyy");
                    string AnneID2 = ViewState["AnnexureID"].ToString();
                    SqlCommand cmd2 = new SqlCommand("UPDATE [DisplaySops].[dbo].[TBL_ANNEXURE] SET [PRINTEDBYDATE] = '" + DateTime.Now + "' where [ANNEXUREID] ='" + AnneID2 + "'", conn);
                    cmd2.ExecuteNonQuery();
                    //oWordDoc.PageSetup.FooterDistance = 0.2f;
                }
            }


            /* if (oWordApp.ActiveWindow.Selection.Text == "\r")
             {                
                 oWordApp.ActiveWindow.Selection.MoveDown(ref missing, ref Count, ref missing);
                 oWordDoc.ActiveWindow.Application.Selection.EndKey(ref missing, ref missing);

                 if (oWordApp.ActiveWindow.Selection.Text == "P")
                 {
                     string AnneID = ViewState["AnnexureID"].ToString();
                     string strPrientedByDate = string.Empty;
                     oWordDoc.PageSetup.BottomMargin = 0;
                     oWordDoc.PageSetup.TopMargin = 0;
                     SqlConnection conn = new SqlConnection();
                     conn.ConnectionString = "server=APLU7-DSK-057; user id=sa; password=password123; database =DisplaySops";
                     conn.Open();
                     SqlCommand cmd = new SqlCommand("select PRINTEDBYDATE from TBL_ANNEXURE where ANNEXUREID = '" + AnneID + "'", conn);
                     DateTime date1 = Convert.ToDateTime(cmd.ExecuteScalar());
                     strPrientedByDate = date1.ToString("dd/MM/yyyy");

                     foreach (Word.Range tmpRange in oWordDoc.StoryRanges)
                     {
                         // Set the text to find and replace
                         string strtext = "Printed By : " + Session["UserID"].ToString() + "  -  " + strPrientedByDate;
                         tmpRange.Find.Text = strtext;
                         //string date1 = DateTime.Now.ToString("dd/MM/yyyy");
                         string AnneID1 = ViewState["AnnexureID"].ToString();
                         try
                         {
                             SqlCommand cmd1 = new SqlCommand("UPDATE [DisplaySops].[dbo].[TBL_ANNEXURE] SET [PRINTEDBYDATE] = '" + DateTime.Now + "' where [ANNEXUREID] ='" + AnneID1 + "'", conn);
                             cmd1.ExecuteNonQuery();
                         }
                         catch (Exception ex)
                         {
                             continue;
                         }
                         string strReplaceText = "Printed By : " + Session["UserID"].ToString() + "  -  " + DateTime.Now.ToString("dd/MM/yyy");
                         tmpRange.Find.Replacement.Text = strReplaceText;

                         // Set the Find.Wrap property to continue (so it doesn't
                         // prompt the user or stop when it hits the end of
                         // the section)
                         tmpRange.Find.Wrap = Word.WdFindWrap.wdFindContinue;

                         // Declare an object to pass as a parameter that sets
                         // the Replace parameter to the "wdReplaceAll" enum
                         object replaceAll = Word.WdReplace.wdReplaceAll;

                         // Execute the Find and Replace -- notice that the
                         // 11th parameter is the "replaceAll" enum object
                         tmpRange.Find.Execute(ref missing, ref missing, ref missing,
                             ref missing, ref missing, ref missing, ref missing,
                             ref missing, ref missing, ref missing, ref replaceAll,
                             ref missing, ref missing, ref missing, ref missing);
                     }              
                 }
                 else
                 {
                     // Remove WaterMark

                     oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader;
                     Word.ShapeRange midRightText;
                     object name = "PowerPlusWaterMarkObject2";
                     midRightText = oWordApp.Selection.HeaderFooter.Shapes.Range(ref name);
                     midRightText.Delete();
                     oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

                     // Remove WaterMark  

                     oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
                     oWordDoc.PageSetup.BottomMargin = 0;
                     oWordDoc.PageSetup.TopMargin = 0;  

                     oWordApp.Selection.TypeParagraph();
                     int i = oWordApp.Selection.Paragraphs.Count;

                     oWordApp.Selection.MoveDown(ref missing, ref Count, ref missing);
                     oWordDoc.ActiveWindow.Application.Selection.EndKey(ref missing, ref missing);
                     oWordApp.ActiveWindow.Selection.TypeText("\n");
                     oWordApp.ActiveWindow.Selection.Font.Name = "Arial";
                     oWordApp.ActiveWindow.Selection.Font.Size = 12;

                     if (Session["UserID"] != null)
                     {
                         oWordApp.ActiveWindow.Selection.TypeText("Printed By : " + Session["UserID"].ToString() + "  -  " + DateTime.Now.ToString("dd/MM/yyyy"));
                         oWordApp.ActiveWindow.Selection.TypeText("\t");
                         oWordApp.ActiveWindow.Selection.TypeText("\t");                        
                         Word.InlineShape CustLogo;
                         String logoPath = "D:\\Malyadri\\Refresh.gif";                        
                         CustLogo = oWordApp.ActiveWindow.Selection.InlineShapes.AddPicture(logoPath, ref missing, ref missing, ref missing);
                         string type = CustLogo.Type.ToString();
                         CustLogo.Select();
                         CustLogo.AlternativeText = "PowerPlusInlineObject2";                        

                         SqlConnection conn = new SqlConnection();
                         conn.ConnectionString = "server=APLU7-DSK-057; user id=sa; password=password123; database =DisplaySops";
                         conn.Open();
                         string date2 = DateTime.Now.ToString("dd/MM/yyyy");
                         string AnneID2 = ViewState["AnnexureID"].ToString();
                         SqlCommand cmd2 = new SqlCommand("UPDATE [DisplaySops].[dbo].[TBL_ANNEXURE] SET [PRINTEDBYDATE] = '" + DateTime.Now + "' where [ANNEXUREID] ='" + AnneID2 + "'", conn);
                         cmd2.ExecuteNonQuery();                   

                     }                                      
                 }                
             } */

            oWordDoc.PrintRevisions = true;
            oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
            if (oWordDoc.ProtectionType == Word.WdProtectionType.wdNoProtection)
            {
                oWordDoc.Protect(Word.WdProtectionType.wdAllowOnlyFormFields, ref missing, ref password, ref missing, ref isVisible);
            }
            oWordDoc.Saved = true;
            oWordDoc.Activate();

        }
        catch (Exception ex)
        {

        }                     

    }

please give solution

Cheers

Malyadri.