コード例 #1
0
        internal void AppendCitation(CitationCluster citation_cluster)
        {
            if (0 == citation_cluster.citation_items.Count)
            {
                Logging.Warn("Not appending zero citations");
                return;
            }

            CitationCluster existing_citation_cluster;
            Field           existing_field;

            GetCurrentlySelectedCitationCluster(out existing_citation_cluster, out existing_field);
            if (null != existing_citation_cluster)
            {
                existing_citation_cluster.citation_items.AddRange(citation_cluster.citation_items);
                PopulateFieldWithRawCitationCluster(existing_field, existing_citation_cluster);
                word_application.Activate();
            }
            else
            {
                // Shrink the selection to the end of it, so that we can add a citation after it...
                Range range = GetInsertionPointRange();
                Field field = range.Fields.Add(range, WdFieldType.wdFieldMergeField, citation_cluster.ToString(), true);
                field.Locked = true;
                PopulateFieldWithRawCitationCluster(field, citation_cluster);
                word_application.Activate();
            }
        }
コード例 #2
0
ファイル: WordDoc.cs プロジェクト: TradeControl/office
        public bool OpenDocument(short _docType, string _fileName, string _documentReference, bool _activateWord)
        {
            try
            {
                if (LoadDocument(_docType, _fileName, _documentReference))
                {
                    if (_activateWord)
                    {
                        MicrosoftWord.Application appWord = new MicrosoftWord.Application();

                        object template    = _fileName;
                        object newTemplate = false;
                        object docType     = MicrosoftWord.WdNewDocumentType.wdNewBlankDocument;
                        object visible     = true;

                        MicrosoftWord.Document doc = appWord.Documents.Add(ref template, ref newTemplate, ref docType, ref visible);
                        doc.PrintPreview();
                        appWord.Visible = true;
                        appWord.Activate();
                    }

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, $"{err.Source}.{err.TargetSite.Name}", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
        }
コード例 #3
0
        public void saveFile(string path, bool isOpen)
        {
            object readOnly  = true;
            object isVisible = true;

            wordApp.Visible = true;
            object fileName = path;

            try
            {
                wordDoc.SaveAs(path);

                if (isOpen)
                {
                    wordApp.Documents.Open(ref fileName, ref missing, ref readOnly,
                                           ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing);
                    wordDoc.Activate();
                    wordApp.Activate();
                    wordApp.Options.SaveNormalPrompt        = false;
                    wordApp.Options.SavePropertiesPrompt    = false;
                    wordDoc.Windows.Application.WindowState = Word.WdWindowState.wdWindowStateMaximize;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
コード例 #4
0
 public void OnWindowActivate()
 {
     if (m_ShowPaneOnActivate && !m_ManuallyHidden)
     {
         if (this.InvokeRequired)
         {
             OnWindowActivateCallback callback = new OnWindowActivateCallback(OnWindowActivate);
             this.Invoke(callback);
         }
         else
         {
             this.Show();
             m_WordApplication.Activate();
         }
     }
 }
コード例 #5
0
ファイル: Util.cs プロジェクト: SciGit/scigit-client
    public static void CompareInWord(string fullpath, string newFullpath, string saveName, string saveDir, string author, bool save = false) {
      Object missing = Type.Missing;
      try {
        var wordapp = new Microsoft.Office.Interop.Word.Application();
        try {
          var doc = wordapp.Documents.Open(fullpath, ReadOnly: true);
          doc.Compare(newFullpath, author ?? missing);
          doc.Close(WdSaveOptions.wdDoNotSaveChanges); // Close the original document
          var dialog = wordapp.Dialogs[WdWordDialog.wdDialogFileSummaryInfo];
          // Pre-set the save destination by setting the Title in the save dialog.
          // This must be done through reflection, since "dynamic" is only supported in .NET 4
          dialog.GetType().InvokeMember("Title", BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty,
                                        null, dialog, new object[] {saveName});
          dialog.Execute();
          wordapp.ChangeFileOpenDirectory(saveDir);
          if (!save) {
            wordapp.ActiveDocument.Saved = true;
          }

          wordapp.Visible = true;
          wordapp.Activate();

          // Simple hack to bring the window to the front.
          wordapp.ActiveWindow.WindowState = WdWindowState.wdWindowStateMinimize;
          wordapp.ActiveWindow.WindowState = WdWindowState.wdWindowStateMaximize;
        } catch (Exception ex) {
          Logger.LogException(ex);
          ShowMessageBox("Word could not open these documents. Please edit the file manually.", "Error");
          wordapp.Quit();
        }
      } catch (Exception ex) {
        Logger.LogException(ex);
        ShowMessageBox("Could not start Microsoft Word. Office 2003 or higher is required.", "Could not start Word");
      }
    }
コード例 #6
0
        public static Microsoft.Office.Interop.Word.Document OpenWordDoc(string FileName)
        {
            const int wdStory = 6;

            Microsoft.Office.Interop.Word.Application wordApp = null;
            try
            {
                wordApp         = new Microsoft.Office.Interop.Word.Application();
                wordApp.Visible = true;
                var doc = wordApp.Documents.Open(FileName);
                doc.Select();
                doc.Activate();
                wordApp.Activate();
                wordApp.Selection.EndKey(wdStory);
                return(doc);
            }
            catch (Exception ex)
            {
                if (wordApp != null)
                {
                    wordApp.Quit(false);
                    wordApp = null;
                }
                StaticFunctions.HandleException(ex);
                return(null);
            }
        }
コード例 #7
0
        public WordInstance(Word.Application app)
        {
            m_App = app;
            m_App.Activate();

            // Get the window handle.
            m_WindowHandle = WindowsApi.GetForegroundWindow();
        }
コード例 #8
0
 private void btnInsertField_Click(object sender, EventArgs e)
 {
     if (trvDefendant.SelectedNode != null && _wrdApp != null && _wrdApp.Documents.Count > 0)
     {
         _wrdApp.ActiveDocument.MailMerge.Fields.Add(_wrdApp.Selection.Range, trvDefendant.SelectedNode.Text.Trim().Replace(" ", "_"));
         _wrdApp.Activate();
     }
 }
コード例 #9
0
        public static Word.Application OpenWordApp()
        {
            Word.Application wordApp = new Word.Application();
            // Make Word visible (optional).
            wordApp.Visible = true;
            wordApp.Activate();

            return(wordApp);
        }
コード例 #10
0
 public void SetVisible(bool bVisible)
 {
     if (m_pApp != null)
     {
         WordDocumentToFront();
         m_pApp.Visible = true;
         m_pApp.Activate();
     }
 }
コード例 #11
0
        public static void fillTemplate(string templatePath, Dictionary <string, string> mappedValues)
        {
            Word.Document doc = null;
            try
            {
                Word.Application app = new Word.Application();
                doc = app.Documents.Open(templatePath);
                doc.Activate();

                Word.Paragraphs paragraphs = doc.Paragraphs;
                Word.Range      wRange;

                foreach (Word.Paragraph mark in paragraphs)
                {
                    wRange = mark.Range;
                    foreach (KeyValuePair <string, string> entry in mappedValues)
                    {
                        string oldValue = wRange.Text;
                        if (oldValue.Contains(entry.Key))
                        {
                            string newParagraphVal = oldValue.Replace(entry.Key, entry.Value).Trim();
                            Console.Write(newParagraphVal);
                            wRange.Text = newParagraphVal;
                        }
                    }
                }

                string filledDocPath = Path.GetTempFileName();
                Console.WriteLine(filledDocPath);
                doc.SaveAs2(filledDocPath);

                app.Documents.Open(filledDocPath);
                app.Activate();
                app.Visible = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                Console.ReadLine();
            }
            finally
            {
                if (doc != null)
                {
                    doc = null;
                }
            }
        }
コード例 #12
0
 /// <summary>
 ///     Método responsável por abrir o documento do word e exibi-lo na tela
 /// para o usuário corrente.
 /// </summary>
 public void AbrirWord()
 {
     if (mWord == null)
     {
         throw new Exception("Não há instalações válidas do Microsoft Office Word");
     }
     else if (!System.IO.File.Exists(mCaminhoArqWord))
     {
         throw new System.IO.FileNotFoundException(String.Format("Não foi possível encontrar o arquivo '{0}'.", mCaminhoArqWord));
     }
     else
     {
         mDoc = (Document)mWord.Documents.Open(mCaminhoArqWord, Type.Missing, (object)false, (object)Missing.Value, (object)Missing.Value, (object)Missing.Value, (object)Missing.Value, (object)Missing.Value, (object)Missing.Value, (object)Missing.Value, (object)Missing.Value, (object)Missing.Value, (object)Missing.Value, (object)Missing.Value, (object)Missing.Value);
         //Abre a visualização da planilha designada (define a mesma como ativa).
         mWord.Activate();
     }
 }
コード例 #13
0
ファイル: UserControl1.cs プロジェクト: vs6060cn/nim-solution
        private void GenerateWord()
        {
            var app = Globals.ThisAddIn.Application;

            Excel.Workbook oWorkbook = Globals.ThisAddIn.Application.ActiveWorkbook;
            oWorkbook.Save();


            var excelFileName = Globals.ThisAddIn.Application.ActiveWorkbook.FullName;

            this.InitPathManager();

            var parser = NIM.CertificationGenerator.Core.WordParseFactory.GetWordParse(excelFileName);

            var wordResultFileName = parser.GeneraterFile();


            var docFileName = Path.Combine(Path.GetDirectoryName(wordResultFileName), Path.GetFileNameWithoutExtension(wordResultFileName) + ".doc");

            var document = new Aspose.Words.Document(wordResultFileName);

            try
            {
                document.Save(docFileName, Aspose.Words.SaveFormat.Doc);
            }
            catch (Exception ex)
            {
                this.ShowMessage($@"自动删除上次生成的证书文件失败,请手动删除它{docFileName},({ex.Message})", true);
                return;
            }
            System.IO.File.Delete(wordResultFileName);


            wordResultFileName = docFileName;
            this.ShowMessage($"WORD已生成,正在打开文档({wordResultFileName})...", false);


            var wordApp = new Word.Application();

            ((Word.Application)wordApp).Visible = true;

            wordApp.Documents.Open(wordResultFileName);
            this.ShowMessage(wordResultFileName, false);
            wordApp.Activate();
        }
コード例 #14
0
        public void HandleOpenQuestion(OpenWFileQuestion question, Dictionary <int, Word.Document> mapIdDocuments, Word.Application wordApplication)
        {
            int    index         = question.Index;
            string emptyFilePath = question.EmptyFilePath;

            if (wordApplication != null && wordApplication.Documents != null)
            {
                // if not open yet
                if (!mapIdDocuments.ContainsKey(index))
                {
                    var doc = wordApplication.Documents.Open(emptyFilePath);
                    mapIdDocuments.Add(index, doc);
                }
                else
                {
                    wordApplication.Activate();
                    mapIdDocuments[index].Activate();
                }
            }
            FitIntoArea(wordApplication);
        }
コード例 #15
0
        void CreateWordDocument(Client client)
        {
            string fileQrPath = string.Format(@"{0}\{1}", Environment.CurrentDirectory, filenameQrCode);

            Word.Application wApp = new Word.Application();
            Word.Document    wDoc = wApp.Documents.Add(patternCardPath);

            foreach (Word.Bookmark b in wDoc.Bookmarks)
            {
                if (b.Name == "clientInfo")
                {
                    Word.Range range = b.Range;
                    range.Text = client.ToString();
                }

                if (b.Name == "qrCode")
                {
                    Word.Range      rangeB = b.Range;
                    object          f      = false;
                    object          t      = true;
                    object          left   = Type.Missing;
                    object          top    = Type.Missing;
                    object          width  = 93;
                    object          height = 93;
                    object          range  = rangeB;
                    Word.WdWrapType wrap   = Word.WdWrapType.wdWrapSquare;

                    wDoc.Shapes.AddPicture(fileQrPath, ref f, ref t, ref left, ref top, ref width, ref height, ref range).WrapFormat.Type = wrap;
                }
            }

            wDoc.SaveAs(string.Format(@"{0}\ClientCards\{1}",
                                      Environment.CurrentDirectory,
                                      client + ".docx"
                                      ));

            wApp.Visible = true;
            wApp.Activate();
        }
コード例 #16
0
        // open a document and fit into area
        public void OpenDocument(IQuestion question, Dictionary <int, Word.Document> mapIdDocuments, Word.Application wordApplication)
        {
            int index = question.Index;

            if (question.File != null && question.File.Path != null)
            {
                if (wordApplication != null && wordApplication.Documents != null)
                {
                    // if not open yet
                    if (!mapIdDocuments.ContainsKey(index))
                    {
                        var doc = wordApplication.Documents.Open(question.File.Path);
                        mapIdDocuments.Add(index, doc);
                    }
                    else
                    {
                        wordApplication.Activate();
                        mapIdDocuments[index].Activate();
                    }
                }
                FitIntoArea(wordApplication);
            }
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: engrbugs/Journal
        static void Main(string[] args)
        {
            Console.WriteLine($"Creating Journal {VERSION}");
            Console.WriteLine($"Loading WinWord App");
            Word.Application objWord = new Word.Application();
            Console.WriteLine($"Making it visible and maximized");
            objWord.Visible     = true;
            objWord.WindowState = Word.WdWindowState.wdWindowStateMaximize;

            Console.WriteLine($"Creating a document");
            Word.Document objDoc = objWord.Documents.Add();

            Console.WriteLine($"What is the date for today... hmmm...");
            objWord.Selection.TypeText(strHeader1Text());

            Console.WriteLine($"Typing the header");
            objDoc.Paragraphs[1].set_Style(Word.WdBuiltinStyle.wdStyleHeading1);
            objDoc.Paragraphs[1].Range.Underline = Word.WdUnderline.wdUnderlineSingle;

            Console.WriteLine($"Clear formatting for you to type");
            objWord.Selection.TypeParagraph();
            objWord.Selection.TypeText(Environment.NewLine);
            objDoc.Paragraphs[2].set_Style(Word.WdBuiltinStyle.wdStyleNormal);

            try
            {
                Console.WriteLine($"Making a folder");
                Directory.CreateDirectory($"{JOURNAL_PATH}\\" +
                                          $"{strFolderYear()}\\{strFolderMonth()}");
                Console.WriteLine($"I'm close... Saving the file for you");
                objDoc.SaveAs2($"{JOURNAL_PATH}\\{strFolderYear()}\\" +
                               $"{strFolderMonth()}\\{strFilename()}.docx");
            }
            catch (Exception e)
            {
                Console.WriteLine("The process failed: {0}", e.ToString());
            }

            Console.WriteLine($"Focus on WinWord app");
            objWord.Activate();
            BringMainWindowToFront("WinWord");
            Console.WriteLine($"Bye.");
            SetCursorPos(972, 1028);
            SetCursorPos(-1950, 800);
            SetCursorPos(-1950, 1240);
            LeftMouseClick(-1993, 1408);

            /*
             * BringMainWindowToFront("WINWORD.EXE");
             * objWord.Visible = true;
             * objWord.WindowState = Word.WdWindowState.wdWindowStateMaximize;
             * Console.WriteLine($"Bye.");
             * Process[] processes = Process.GetProcessesByName("WinWord");
             * RECT rct = new RECT();
             * foreach (Process p in processes)
             * {
             *  IntPtr windowHandle = p.MainWindowHandle;
             *
             *  // do something with windowHandle
             *
             *
             *  GetWindowRect(windowHandle, ref rct);
             *
             *
             * }
             * SetCursorPos(972, 1028);
             * SetCursorPos(-1950, 800);
             * SetCursorPos(-1950, 1240);
             * Console.WriteLine($"{rct.Left}, {rct.Top}, {rct.Right}, {rct.Bottom}");
             * LeftMouseClick(-1950, 1240);
             * Console.WriteLine((int)((rct.Left + rct.Right) / 2));
             * Console.WriteLine((int)((rct.Bottom + rct.Top) / 2));
             */
        }
コード例 #18
0
 static Wd.Application CreateWordApp()
 {
     var app = new Wd.Application() { Visible = true };
     app.Activate(true);
     return app;
 }
コード例 #19
0
ファイル: Form1.cs プロジェクト: Rosov/Sapr_piping
        private void ведомостьТрубопроводовToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Word.Application app;
            Word.Document doc;
            Object missingObj = System.Reflection.Missing.Value;
            Object trueObj = true;
            Object falseObj = false;
            app = new Word.Application();
            Object templatePathObj = Application.StartupPath + "\\vt.docx";
            try
            {
                doc = app.Documents.Add(ref templatePathObj, ref missingObj, ref missingObj, ref missingObj);
                doc.Activate();
                doc = app.ActiveDocument;
                //Колонтитул (шифр проекта)
                /* foreach (Word.Section wordSection in doc.Sections)
                 {
                     Word.Range footerRange = wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                     //footerRange.Font.Size = 20;
                     //footerRange.Font.ColorIndex = Word.WdColorIndex.wdDarkRed;
                     footerRange.Text = PustoString(ShifrTextBox.Text);
                 }*/

                Microsoft.Office.Interop.Word.Find fnd = app.Selection.Find;

                //Колонтитул (шифр проекта)
                foreach (Word.Section wordSection in doc.Sections)
                 {
                     Word.Range footerRange = wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    //footerRange.Font.Size = 20;
                    //footerRange.Font.ColorIndex = Word.WdColorIndex.wdDarkRed;

                    //footerRange.Text = PustoString(ShifrTextBox.Text);
                    Microsoft.Office.Interop.Word.Find fndС =footerRange.Find;

                    fndС.ClearFormatting();
                    fndС.Text = "{cltl}";
                    fndС.Replacement.ClearFormatting();
                    fndС.Replacement.Text = PustoString(ShifrTextBox.Text);
                    ExecuteReplace(fndС);
                }

                // Температура рабочая / max, C (от минус <> до плюс <>)

                fnd.ClearFormatting();
                fnd.Text = "{T}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text= "от " + Describe(TFromNumericUpDown.Value) + " до " + Describe(TToNumericUpDown.Value) + " / " + Pusto(TMaxNumericUpDown.Value);
                ExecuteReplace(fnd);
                //Название секции
                fnd.ClearFormatting();
                fnd.Text = "{Name}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = SectionNameTextBox.Text;
                ExecuteReplace(fnd);
                //Давление: Р(усл) кгс/см2
                fnd.ClearFormatting();
                fnd.Text = "{P_usl}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = PustoString(PUslComboBox.SelectedItem.ToString());
                ExecuteReplace(fnd);
                //Давление: Р(раб) кгс/см2
                fnd.ClearFormatting();
                fnd.Text = "{P_rab}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = Pusto(PRabNumericUpDown.Value);
                ExecuteReplace(fnd);
                //Давление: Р(расч) кгс/см2
                fnd.ClearFormatting();
                fnd.Text = "{P_ras}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = Pusto(PRaschNumericUpDown.Value);
                ExecuteReplace(fnd);
                //Давление: Р(проч) кгс/см2
                fnd.ClearFormatting();
                fnd.Text = "{P_pro}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text =Pusto(PProchNumericUpDown.Value);
                ExecuteReplace(fnd);
                //Давление: Р(плот) кгс/см2
                fnd.ClearFormatting();
                fnd.Text = "{P_plo}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = Pusto(PPlotNumericUpDown.Value);
                ExecuteReplace(fnd);
                //Давление: Р(герм) кгс/см2
                fnd.ClearFormatting();
                fnd.Text = "{P_ger}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = Pusto(PGermNumericUpDown.Value);
                ExecuteReplace(fnd);
                //Способ испытания: Р(проч)-"Г" или "П"
                fnd.ClearFormatting();
                fnd.Text = "{M_pro}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = PustoString(PProchMethodComboBox.SelectedItem.ToString());
                ExecuteReplace(fnd);
                //Способ испытания: Р(плот)-"Г" или "П"
                fnd.ClearFormatting();
                fnd.Text = "{M_plo}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = PustoString(PPlotMethodComboBox.SelectedItem.ToString());
                ExecuteReplace(fnd);
                //Способ испытания: Р(герм)-"Г" или "П"
                fnd.ClearFormatting();
                fnd.Text = "{M_ger}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = PustoString(PGermMethodComboBox.SelectedItem.ToString());
                ExecuteReplace(fnd);
                //
                fnd.ClearFormatting();
                fnd.Text = "{dP}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = Pusto(dPNumericUpDown.Value);
                ExecuteReplace(fnd);
                //Время (ч)
                fnd.ClearFormatting();
                fnd.Text = "{th}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = Pusto(tChNumericUpDown.Value);
                ExecuteReplace(fnd);
                //Категория и группа трубопровода
                fnd.ClearFormatting();
                fnd.Text = "{category}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = PustoString(CategoryOfProductComboBox.SelectedItem.ToString());
                ExecuteReplace(fnd);
                //Наименование транспортируемого продукта
                fnd.ClearFormatting();
                fnd.Text = "{product}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = PustoString(GroupOfProductComboBox.SelectedItem.ToString());
                ExecuteReplace(fnd);
                //Граница участка "ОТ"
                fnd.ClearFormatting();
                fnd.Text = "{from}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = PustoString(FromTextBox.Text);
                ExecuteReplace(fnd);
                //Граница участка "ДО"
                fnd.ClearFormatting();
                fnd.Text = "{to}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = PustoString(ToTextBox.Text);
                ExecuteReplace(fnd);
                //Объем контроля сварных швов, %
                fnd.ClearFormatting();
                fnd.Text = "{weldCtrl}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = Pusto(VControlOfWeldSeamNumericUpDown.Value);
                ExecuteReplace(fnd);
                //Скорость коррозии, мм/год
                fnd.ClearFormatting();
                fnd.Text = "{corr}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = Pusto(SpeedOfCorrosionNumericUpDown.Value);
                ExecuteReplace(fnd);
                //Расчетный(назначенный) срок службы трубопровода, лет
                fnd.ClearFormatting();
                fnd.Text = "{workPeriod}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text = Pusto(LifeTimeNumericUpDown.Value);
                ExecuteReplace(fnd);
                //Термообработка (да, нет)
                string term="нет";
                if (HeatTreatmentCheckBox.Checked)
                {
                    term = "да";
                }
                fnd.ClearFormatting();
                fnd.Text = "{therm}";
                fnd.Replacement.ClearFormatting();
                fnd.Replacement.Text =term;
                ExecuteReplace(fnd);
                //

                //

                //
                int row = 2;
                Microsoft.Office.Interop.Word.Table tbl;
                tbl = doc.Content.Tables[3];
                tbl.Rows[row].HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightAuto;
                VT obj;
                int num;
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    obj = vTBindingSource[i] as VT;
                    num = obj.VtElementID;
                    for (int j = 1; j < dataGridView1.ColumnCount; j++)
                    {
                        tbl.Cell(i + 3, 1).Range.Text = Convert.ToString(num);
                        if (dataGridView1.Rows[i].Cells[j].Value != null)
                        {
                        tbl.Cell(i + 3, j+1 ).Range.Text = dataGridView1.Rows[i].Cells[j].Value.ToString();
                        }
                    }
                }
                tbl.Range.Font.Size = 10;
                app.Visible = true;
                app.Activate();
                //app.Quit(ref deflt, ref deflt, ref deflt);
                //doc = null;
                //app = null;
                //GC.Collect();
                //GC.WaitForPendingFinalizers();
                //GC.Collect();
                //GC.WaitForPendingFinalizers();
            }
            catch (Exception ex)
            {
                app.Quit(ref missingObj, ref missingObj, ref missingObj);
                doc = null;
                app = null;
                MessageBox.Show(ex.Message);
            }

            //doc.Close(ref templatePathObj, ref missingObj, ref missingObj, ref missingObj);

            /*  tbl.Rows[n].Range.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorGray10;

              tbl.Rows[n].Range.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorGray20;

              tbl.Range.Font.Name = "Tahoma";
              tbl.Range.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed;
              tbl.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;
              tbl.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;
              tbl.Borders.InsideColor = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;
              tbl.Borders.OutsideColor = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;
              tbl.Rows[1].Range.Cells[1].Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBrown;
              tbl.Rows[1].Range.Cells[1].Range.Bold = 1;
              tbl.Rows[1].Range.Cells[1].Range.Borders.Shadow = false; */
        }
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            Word.Application wa     = null;
            Word.Document    doc    = main.CreateNewWordDoc(ref wa);
            object           nulval = Type.Missing;

            string prname = KursRabotaList.Rows[kursRablistBox.SelectedIndex][2].ToString();

            Word.Range Range = doc.Range(ref nulval, ref nulval);
            Range.Select();
            Range.ParagraphFormat.FirstLineIndent = 0.0f;

            Range = doc.Paragraphs[1].Range;
            Range.Select();
            Range.Text = "А К Т";
            Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            Range.Font.Bold   = 1;
            Range.Font.Italic = 1;

            Range = main.AddWordDocParagraph(ref doc,
                                             "сдачи курсовых работ  в архив", Word.WdParagraphAlignment.wdAlignParagraphCenter);
            Range.Font.Bold   = 0;
            Range.Font.Italic = 0;

            Range = main.AddWordDocParagraph(ref doc,
                                             " ", Word.WdParagraphAlignment.wdAlignParagraphCenter);

            Range = main.AddWordDocParagraph(ref doc,
                                             "Комиссия в составе:  архивариус Зуенок Е.В.",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "\t\t\t" +
                                             " зам. декана ФИВТ     В.В. Семикина",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "\t\t\t" +
                                             " зав. кафедры КТИС   И.К. Мазур",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             " ",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);


            Range = main.AddWordDocParagraph(ref doc,
                                             "FSystem ИВТ, кафедра  “Компьютерные технологии и системы”",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);


            Range = main.AddWordDocParagraph(ref doc,
                                             " ",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "За " + main.year_start.Year.ToString() + "/" + main.year_end.Year.ToString() + " уч. год",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);


            Range = main.AddWordDocParagraph(ref doc,
                                             " ",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "Группа " + StudRabotaList.Rows[0][12].ToString().ToUpper(),
                                             Word.WdParagraphAlignment.wdAlignParagraphCenter);
            Range.Font.Bold = 1;

            Range = main.AddWordDocParagraph(ref doc,
                                             "Дисциплина “" + prname + "”",
                                             Word.WdParagraphAlignment.wdAlignParagraphCenter);
            Range.Font.Bold = 1;

            Range = main.AddWordDocParagraph(ref doc,
                                             " ",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);
            Range.Font.Bold = 0;


            List <int> tabrows = new List <int>();

            foreach (DataGridViewCell c in RabListdataGridView.SelectedCells)
            {
                MessageBox.Show(c.Value.ToString());

                if (!tabrows.Contains(c.RowIndex))
                {
                    tabrows.Add(c.RowIndex);
                }
            }

            int k = 1;

            for (int i = 0; i < tabrows.Count; i++)
            {
                int ind = tabrows[i];
                if (RabListdataGridView.Rows[ind].Cells[2].Value.ToString() != "2")
                {
                    if (RabListdataGridView.Rows[ind].Cells[1].Value.ToString().Length != 0)
                    {
                        Range = main.AddWordDocParagraph(ref doc,
                                                         k.ToString() + ". " + RabListdataGridView.Rows[ind].Cells[0].Value.ToString() +
                                                         " (" + RabListdataGridView.Rows[ind].Cells[1].Value.ToString() + ")",
                                                         Word.WdParagraphAlignment.wdAlignParagraphLeft);
                        k++;
                    }
                }
            }

            if (k == 1)
            {
                MessageBox.Show("Акт не построен. В таблице нет работ, " +
                                "которые могут быть актированы (либо у работ не указана тема,\nлибо все выбранные работы оценены на неудовлетворительно.",
                                "Отказ операции", MessageBoxButtons.OK, MessageBoxIcon.Error);
                main.WordQuit(wa);
                return;
            }

            saveExcel.Title    = "Введите имя для файла акта курсовой работы.";
            saveExcel.Filter   = "Файл акта КР в формате MS Word|*.doc";
            saveExcel.FileName = "Акт курс. работ по " + prname + ".doc";

            if (saveExcel.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            string FileName = saveExcel.FileName;

            Range = main.AddWordDocParagraph(ref doc,
                                             " ",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             " ",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "Итого сдано работ: " + (k - 1).ToString(),
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);
            Range.Font.Bold      = 1;
            Range.Font.Underline = Word.WdUnderline.wdUnderlineSingle;

            Range = main.AddWordDocParagraph(ref doc,
                                             " ",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);
            Range.ParagraphFormat.LineSpacing = wa.LinesToPoints(1.5f);
            Range.Font.Bold      = 0;
            Range.Font.Underline = Word.WdUnderline.wdUnderlineNone;

            Range = main.AddWordDocParagraph(ref doc,
                                             "Преподаватель           " + main.active_user_name + "___________________",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "Зав. кафедры КТИС   И.К. Мазур________________________",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "Зам. декана ФИВТ     В.В. Семикина_____________________",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "Архивариус           Зуенок Е.В._______________________",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             "Бухгалтер                   ________________________________",
                                             Word.WdParagraphAlignment.wdAlignParagraphLeft);

            Range = main.AddWordDocParagraph(ref doc,
                                             DateTime.Now.ToLongDateString(),
                                             Word.WdParagraphAlignment.wdAlignParagraphRight);

            main.SaveWordDoc(FileName, ref doc);
            wa.Visible = true;
            wa.Activate();
        }
コード例 #21
0
        /// <summary>
        /// Generate word document with register of system documents
        /// </summary>
        /// <param name="tv"></param>
        public string RegisterOfSytemDocuments(TreeView tv, string clientFolder)
        {
            object oMissing = System.Reflection.Missing.Value;
            var    pastPlannedActivities = string.Empty;

            //Start Word and create a new document.
            WordNet._Application oWord = new Application {
                Visible = false
            };
            WordNet._Document oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
                                                         ref oMissing, ref oMissing);

            oDoc.PageSetup.Orientation = WordNet.WdOrientation.wdOrientLandscape;

            PrintToWord(oDoc, "Register of System Documents", 16, 0, FCMWordAlign.CENTER);
            PrintToWord(oDoc, " ", 8, 0);

            // Locate client folder
            //
            string clientFileLocationName = Utils.getFilePathName(@"%TEMPLATEFOLDER%\ClientSource\", "ROS-001 Register Of System Documents.doc");

            FullFileNamePath = clientFileLocationName;
            FileName         = "RegisterOfSystemDocuments.doc";

            if (File.Exists(clientFileLocationName))
            {
                // Delete file
                try
                {
                    File.Delete(clientFileLocationName);
                    uioutput.AddOutputMessage("File replaced: " + clientFileLocationName);
                }
                catch (Exception)
                {
                    uioutput.AddOutputMessage("Error deleting file " + clientFileLocationName);
                    uioutput.AddErrorMessage("Error deleting file " + clientFileLocationName);
                    return(clientFileLocationName);
                }
            }


            // string filename = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Path.GetTempFileName(), "doc"));
            oDoc.SaveAs(clientFileLocationName);

            string msg = ">>> Generating file... ";

            if (uioutput != null)
            {
                uioutput.AddOutputMessage(msg);
            }

            PrintToWord(oDoc, " ", 8, 1);

            WordNet.Range wrdRng;
            WordNet.Table oTable;

            wrdRng = oDoc.Bookmarks.get_Item(oEndOfDoc).Range;
            int rowCount = 30;

            // Get number of rows for a client document, client document set
            //
            var cds = new BUSClientDocumentSet(Utils.ClientID, Utils.ClientSetID);

            rowCount = cds.DocumentCount;

            if (rowCount < 1)
            {
                return(clientFileLocationName);
            }

            oTable = oDoc.Tables.Add(wrdRng, rowCount, 6, ref vkFalse, ref vkFalse);

            //oTable.Borders.InsideLineWidth = WordNet.WdLineWidth.wdLineWidth050pt;
            //oTable.Borders.InsideColor = WordNet.WdColor.wdColorAutomatic;
            //oTable.Borders.OutsideLineWidth = WordNet.WdLineWidth.wdLineWidth050pt;
            //oTable.Borders.OutsideColor = WordNet.WdColor.wdColorAutomatic;

            oTable.Rows[1].HeadingFormat = -1;

            WordNet.Row headingRow = oTable.Rows[1];

            ApplyHeadingStyle(headingRow.Cells[1], 40);
            headingRow.Cells[1].Range.Text = "";

            ApplyHeadingStyle(headingRow.Cells[2], 30);
            headingRow.Cells[2].Range.Text = "";

            ApplyHeadingStyle(headingRow.Cells[3], 60);
            headingRow.Cells[3].Range.Text = "Document Number";

            ApplyHeadingStyle(headingRow.Cells[4], 50);
            headingRow.Cells[4].Range.Text = "Version";

            ApplyHeadingStyle(headingRow.Cells[5], 300);
            headingRow.Cells[5].Range.Text = "Document Name";

            ApplyHeadingStyle(headingRow.Cells[6], 100);
            headingRow.Cells[6].Range.Text = "Comments";

            int line = 0;

            foreach (var treeNode in tv.Nodes)
            {
                line++;
                WriteLineToRoSD(tv.Nodes[0], oDoc, oTable, prefix: "", parent: "", seqnum: line);
            }


            msg = ">>> End ";
            if (uioutput != null)
            {
                uioutput.AddOutputMessage(msg);
            }

            PrintToWord(oDoc, " ", 12, 1);

            oDoc.Save();
            oDoc.Close();

            oWord.Visible = true;
            oWord.Documents.Open(FileName: clientFileLocationName);
            oWord.Activate();

            return(clientFileLocationName);
        }
コード例 #22
0
        //Сохранение в файл
        public static void CreatingWordList(string fileName, List <Publication> filterPublications, int type)
        {
            Word.Application wordApp = new Word.Application();
            wordApp.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
            Word.Document wordDoc = new Word.Document();
            wordDoc = wordApp.Documents.Add();

            object endOfDoc = "\\endofdoc";

            for (int i = 0, fbCnt = filterPublications.Count; i < fbCnt; i++)
            {
                string authors = "";
                string editors = "";
                string info = "";
                string pages = "";
                int    start = 0, end = 0;

                var item = filterPublications[i];

                if (type == 1)
                {
                    //Попытка вычисления кол-ва страниц
                    try
                    {
                        string[] endStart = item.pages.Split(new string[] { " - " }, StringSplitOptions.None);
                        pages = (int.Parse(endStart[1]) - int.Parse(endStart[0])).ToString();
                    }
                    catch
                    {
                        pages = item.pages;
                    }

                    //Формирование строки
                    //Авторов от 1 до 3 включительно
                    if (item.authors.Count <= 3)
                    {
                        for (int j = 0, authCnt = item.authors.Count; j < authCnt; j++)
                        {
                            if (j != authCnt - 1)
                            {
                                authors += item.authors[j] + ", ";
                            }
                            else
                            {
                                authors += item.authors[j];
                            }
                        }
                        //Для книги
                        if (item.isbn != "")
                        {
                            info = item.authors[0] + ". " + item.booktitle +
                                   " : " + item.title + " / " + authors + ". – " + item.publisher + ", " +
                                   item.year + ". – " + pages + " p.";
                        }
                        //Для других типов
                        else
                        {
                            info = item.authors[0] + ". " + item.title +
                                   " / " + authors + " // " + item.journal + ". – " + item.year + ". – Vol. " + item.volume
                                   + ". – P. " + item.pages + ".";
                        }
                    }
                    //Авторов больше 3
                    else
                    {
                        authors = item.authors[0] + " [et al.]";
                        //Для книг
                        if (item.isbn != "")
                        {
                            info = item.booktitle + " : " + item.title + " / " +
                                   authors + ". – " + item.publisher + ", " + item.year + ". – " + pages + " p.";
                        }
                        else
                        {
                            info = item.title + " / " + authors + " // " + item.journal +
                                   ". - " + item.year + ". – Vol. " + item.volume + ". – P. " + item.pages + ".";
                        }
                    }
                }
                else
                {
                    if (item.authors.Count == 1)
                    {
                        authors = item.authors[0] + ", ";
                    }
                    else
                    {
                        for (int j = 0; j < item.authors.Count; j++)
                        {
                            if (j != item.authors.Count - 2)
                            {
                                authors += item.authors[j] + ", ";
                            }
                            else
                            {
                                authors += item.authors[j] + " and " + item.authors[j + 1] + ", ";
                                break;
                            }
                        }
                    }

                    if (item.editor.Count == 1)
                    {
                        editors = item.editor[0] + ", Ed., ";
                    }
                    else
                    {
                        for (int j = 0; j < item.editor.Count; j++)
                        {
                            if (j != item.editor.Count - 2)
                            {
                                editors += item.editor[j] + ", ";
                            }
                            else
                            {
                                editors += item.editor[j] + " and " + item.editor[j + 1] + ", Eds., ";
                                break;
                            }
                        }
                    }

                    bool   flag      = false;
                    string edAuthors = authors;
                    if (new HashSet <string>(item.authors).SetEquals(item.editor))
                    {
                        if (item.authors.Count == 1)
                        {
                            edAuthors += " Ed., ";
                        }
                        else
                        {
                            edAuthors += " Eds., ";
                        }
                        flag = true;
                    }

                    start = edAuthors.Length + 7 + item.title.Length;
                    //Если книга
                    if (item.isbn != "")
                    {
                        if (!flag)
                        {
                            info = edAuthors + "\"" + item.title + ",\" in " + item.booktitle + ", " + editors +
                                   item.publisher + ", " + item.year + ", pp. " + item.pages + ".";
                        }
                        else
                        {
                            info = edAuthors + "\"" + item.title + ",\" in " + item.booktitle + ", " +
                                   item.publisher + ", " + item.year + ", pp. " + item.pages + ".";
                        }
                        end = start + item.booktitle.Length + 1;
                    }
                    //Другие варианты
                    else
                    {
                        info = authors + "\"" + item.title + ",\" in " + item.journal + ", " +
                               item.year + ", vol. " + item.volume + ", pp. " + item.pages + ", doi: " + item.doi + ".";
                        end = start + item.journal.Length + 1;
                    }
                }

                //Запись строки в файл
                Word.Paragraph paragraph;
                paragraph            = wordDoc.Content.Paragraphs.Add();
                paragraph.Range.Text = info;
                if (type == 2)
                {
                    object     oStart = paragraph.Range.Start + start;
                    object     oEnd   = paragraph.Range.Start + end;
                    Word.Range rBold  = wordDoc.Range(ref oStart, ref oEnd);
                    rBold.Italic = 1;
                }
                paragraph.Range.Font.Size = 14;
                paragraph.Range.Font.Name = "Times New Roman";

                if (i == 0)
                {
                    paragraph.Range.ListFormat.ApplyNumberDefault(Word.WdListGalleryType.wdNumberGallery);
                }
                if (i != fbCnt - 1)
                {
                    paragraph.Range.InsertParagraphAfter();
                }
            }

            //Сохранение Word
            DialogResult dialogResult = DialogResult.No;

            try
            {
                wordDoc.SaveAs2(fileName);
                dialogResult = MessageBox.Show("Сохранение прошло успешно\nОткрыть файл?", "Science Direct Systematizer",
                                               MessageBoxButtons.YesNo);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка при сохранении.\nФайл не сохранен.\n" + ex.Message.ToString(),
                                "Science Direct Systematizer");
            }

            if (dialogResult == DialogResult.Yes)
            {
                wordApp.Visible = true;
                wordApp.Activate();
                wordApp.WindowState = Word.WdWindowState.wdWindowStateMaximize;
            }
            else
            {
                wordApp.Quit();
            }
        }
コード例 #23
0
ファイル: ucFactuur.cs プロジェクト: tim-vdv/Carbus
        private void btnPrintCredit_Click(object sender, EventArgs e)
        {
            String  opdrachtenInhoud = "";
            decimal totalAmount      = 0;

            if (cbbID.SelectedItem == null)
            {
                return;
            }

            opdracht op = (opdracht)cbbID.SelectedItem;

            if (op.FactuurNummering1 == null)
            {
                return;
            }
            if (op.FactuurNummering1.FactuurJaar == null || op.FactuurNummering1.FactuurNr == null)
            {
                return;
            }

            opdracht_factuur of = FactuurManagement.getFactuurVanOpdracht(op);

            opdrachtenInhoud += of.opdracht_id + "\t";
            opdrachtenInhoud += of.credit_omschrijving + "\t";
            opdrachtenInhoud += of.credit_basis + "\t";
            opdrachtenInhoud += of.credit_btwpercent + "\t";
            opdrachtenInhoud += of.credit_btwbedrag + "\t";
            opdrachtenInhoud += of.credit_inc + "\t";
            opdrachtenInhoud += System.Environment.NewLine;

            totalAmount += of.credit_inc.Value;



            //opdrachtenInhoud += row.Cells[1].Value + "\t" + row.Cells[2].Value + "\t" + row.Cells[4].Value + "\t" + row.Cells[5].Value + "\t€" + row.Cells[6].Value + System.Environment.NewLine;
            //totalAmount += Convert.ToDouble(row.Cells[6].Value.ToString());


            if (totalAmount > 0)
            {
                locatie adres = KlantManagement.getAdresVanKlant(opdracht.klant.klant_id);

                //Convert date to acceptable format for use in file name
                String datum = DateTime.Today.ToString("yyyy-MM-dd");

                //missing oject to use with various word commands
                object missing = System.Reflection.Missing.Value;

                //the template file you will be using
                //object fileToOpen = (object)@"R:\CarGo\CreditNota_template.docx";
                object fileToOpen = (object)@"R:\CarGo\opdracht_template.docx";

                //Where the new file will be saved to.
                object fileToSave = (object)@"R:\CarGo\opdrachten\Credit_" + opdracht.klant.naam + "_" + datum + ".docx";

                //Create new instance of word and create a new document
                Word.Application wordApp = new Word.Application();
                Word.Document    doc     = null;

                //Properties for the new word document
                object readOnly  = false;
                object isVisible = false;

                //Settings the application to invisible, so the user doesn't notice that anything is going on
                wordApp.Visible = false;
                try
                {
                    try
                    {
                        File.Copy(fileToOpen.ToString(), fileToSave.ToString(), true);
                    }
                    catch
                    {
                        MessageBox.Show("Loading the template file failed.", "Important Note", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                        return;
                    }

                    readOnly = false;
                    doc      = wordApp.Documents.Open(ref fileToSave, ref missing,
                                                      ref readOnly, 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);
                }
                catch { }



                PrintManagement.findAndReplace(doc, "factuurdatum", datum);
                PrintManagement.findAndReplace(doc, "factuurnummer", opdracht.FactuurNummering1.FactuurNr + " " + opdracht.FactuurNummering1.FactuurJaar);
                PrintManagement.findAndReplace(doc, "startOfDocument", opdrachtenInhoud);
                PrintManagement.findAndReplace(doc, "totaal", "Totaal: €" + totalAmount);
                Console.WriteLine(opdrachtenInhoud);

                doc.Save();
                doc.Activate();
                //Making word visible to be able to show the print preview.
                wordApp.Visible = true;
                wordApp.Activate();
                //doc.PrintPreview();
            }
            else
            {
                MessageBox.Show("Credit bedrag moet groter dan 0 zijn.", "Important Note", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            }
        }
コード例 #24
0
        void Navigate()
        {
            try
            {
                Encoding       encode  = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(urlTextBox.Text);
                request.Method    = "GET";
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome Safari/537.36";
                request.KeepAlive = false;
                IAsyncResult iar1 = request.BeginGetResponse(null, null);
                try
                {
                    using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(iar1))
                    {
                        if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created)
                        {
                            string       temp   = Path.GetTempFileName();
                            BinaryReader br     = new BinaryReader(response.GetResponseStream());
                            byte[]       buffer = new byte[4096];
                            MemoryStream ms     = new MemoryStream();
                            int          n      = 0;
                            do
                            {
                                n = br.Read(buffer, 0, buffer.Length);
                                ms.Write(buffer, 0, n);
                            } while (n > 0);
                            br.Dispose();
                            buffer = ms.ToArray();
                            ms.Close();

                            String html = Encoding.ASCII.GetString(buffer);
                            try
                            {
                                Match match = Regex.Match(html, @"<meta[^>]*charset[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                if (match.Success)
                                {
                                    string[] ss      = match.Value.Split(new string[] { "charset=" }, StringSplitOptions.RemoveEmptyEntries);
                                    string   charset = ss[ss.Length - 1].Split(new char[] { '"', ' ' }, StringSplitOptions.RemoveEmptyEntries)[0];
                                    encode = Encoding.GetEncoding(charset);
                                }
                            }
                            catch
                            {
                            }


                            html = encode.GetString(buffer);
                            // http://bytes.com/topic/c-sharp/answers/228303-using-mshtml-parsing-html-files-c
                            try
                            {
                                // http://stackoverflow.com/questions/2505957/using-regex-to-remove-script-tags
                                // http://go4answers.webhost4life.com/Example/regex-match-body-tag-help-111595.aspx
                                Match match = Regex.Match(html, @"<body[^>]*>(.*?)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                if (match.Success)
                                {
                                    html = match.Value;
                                    HTMLDocument   doc  = new HTMLDocument();
                                    IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
                                    doc2.write(new object[] { html });

                                    IHTMLDOMNode dom = (IHTMLDOMNode)doc2;

                                    IHTMLElementCollection scripts = ((IHTMLElement2)doc2.body).getElementsByTagName("script");
                                    foreach (IHTMLElement script in scripts)
                                    {
                                        // http://stackoverflow.com/questions/554233/removing-htmlelement-objects-programmatically-using-c-sharp
                                        IHTMLDOMNode node = script as IHTMLDOMNode;
                                        node.parentNode.removeChild(node);
                                    }

                                    IHTMLElementCollection imgs = ((IHTMLElement2)doc2.body).getElementsByTagName("img");
                                    foreach (IHTMLElement img in imgs)
                                    {
                                        IHTMLDOMNode node = img as IHTMLDOMNode;
                                        IHTMLElement el   = img as IHTMLElement;
                                        string       src  = el.getAttribute("src");
                                        if (removeImageCheckBox.Checked || !src.StartsWith("http"))
                                        {
                                            node.parentNode.removeChild(node);
                                        }
                                    }

                                    if (removeHyperlinkCheckBox.Checked)
                                    {
                                        IHTMLElementCollection @as = ((IHTMLElement2)doc2.body).getElementsByTagName("a");
                                        foreach (IHTMLElement a in @as)
                                        {
                                            IHTMLDOMNode node = a as IHTMLDOMNode;
                                            node.parentNode.removeChild(node);
                                        }
                                    }

                                    html = doc2.body.innerHTML;
                                }
                            }
                            catch
                            {
                            }
                            html = String.Format("<html><body>{0}</body></html>", html);
                            File.WriteAllText(temp, html, encode);

                            // http://stackoverflow.com/questions/5362591/how-to-display-the-string-html-contents-into-webbrowser-control
                            //webBrowser1.DocumentText = html;

                            // http://www.c-sharpcorner.com/uploadfile/d2dcfc/convert-html-to-word-then-word-to-pdf-with-C-Sharp/
                            object           missing = System.Reflection.Missing.Value;
                            Word.Application word    = new Word.Application();
                            // http://bytes.com/topic/c-sharp/answers/243445-word-interop-quickly-inserting-html-files-into-word-doc
                            word.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
                            Word.Document document = word.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                            // http://www.cprogramdevelop.com/3434569/
                            document.ActiveWindow.View.Type = Word.WdViewType.wdWebView;
                            //word.Options.Pagination = false;
                            //word.ScreenUpdating = false;
                            word.Visible = true;

                            // http://charliedigital.com/2010/09/29/inserting-html-into-word-documents/
                            // http://msdn.microsoft.com/en-us/library/bb217015%28office.12%29.aspx
                            // http://msdn.microsoft.com/en-us/library/office/ff191763(v=office.15).aspx
                            document.Range().InsertFile(temp, missing, false, false, false);
                            //Clipboard.SetText(html, TextDataFormat.Text);
                            //word.Selection.PasteSpecial(missing, missing, missing, missing, Word.WdPasteDataType.wdPasteHTML, missing, missing);

                            word.Activate();
                        }
                        else
                        {
                        }
                    }
                }
                catch (WebException e4)
                {
                    if (e4.Message == "要求已經中止: 無法建立 SSL/TLS 的安全通道。")
                    {
                        if (retry > 0)
                        {
                            retry--;
                            // https://peacemeditation.ljm.org.tw/page.aspx?id=982
                            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
                            Navigate();
                        }
                        else
                        {
                            throw e4;
                        }
                    }
                    else
                    {
                        throw e4;
                    }
                }
                catch (Exception e2)
                {
                    throw e2;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
コード例 #25
0
        /// <summary>
        /// Loads a document into the control
        /// </summary>
        /// <param name="t_filename">path to the file (every type word can handle)</param>
        public void LoadDocument(string t_filename)
        {
            deactivateevents = true;
            filename         = t_filename;

            if (wd == null)
            {
                wd = new Word.Application();
            }
            try
            {
                wd.CommandBars.AdaptiveMenus = false;
                wd.DocumentBeforeClose      += new Word.ApplicationEvents4_DocumentBeforeCloseEventHandler(OnClose);
                ((Word.ApplicationEvents4_Event)wd).NewDocument += new Microsoft.Office.Interop.Word.ApplicationEvents4_NewDocumentEventHandler(OnNewDoc);
                wd.DocumentOpen += new Word.ApplicationEvents4_DocumentOpenEventHandler(OnOpenDoc);
                ((Word.ApplicationEvents4_Event)wd).Quit += new Word.ApplicationEvents4_QuitEventHandler(OnQuit);
            }
            catch { }

            if (document != null)
            {
                try
                {
                    object dummy = null;
                    wd.Documents.Close(ref dummy, ref dummy, ref dummy);
                }
                catch { }
            }

            if (wordWnd == 0)
            {
                wordWnd = FindWindow("Opusapp", null);
            }
            if (wordWnd != 0)
            {
                SetParent(wordWnd, this.Handle.ToInt32());

                object fileName    = filename;
                object newTemplate = false;
                object docType     = 0;
                object readOnly    = true;
                object isVisible   = true;
                object missing     = System.Reflection.Missing.Value;

                try
                {
                    if (wd == null)
                    {
                        throw new WordInstanceException();
                    }

                    if (wd.Documents == null)
                    {
                        throw new DocumentInstanceException();
                    }

                    if (wd != null && wd.Documents != null)
                    {
                        document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
                    }

                    if (document == null)
                    {
                        throw new ValidDocumentException();
                    }
                }
                catch
                {
                }


                // =============================================================================================
                // Display for word property
                // =============================================================================================
                try
                {
                    wd.ActiveWindow.DisplayRightRuler        = false;
                    wd.ActiveWindow.DisplayScreenTips        = false;
                    wd.ActiveWindow.DisplayVerticalRuler     = false;
                    wd.ActiveWindow.DisplayRightRuler        = false;
                    wd.ActiveWindow.ActivePane.DisplayRulers = false;
                    wd.ActiveWindow.ActivePane.View.Type     = Word.WdViewType.wdWebView;
                    //wd.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdPrintView;//wdWebView; // .wdNormalView;
                }
                catch
                {
                }


                /// Code Added
                /// Disable the specific buttons of the command bar
                /// By default, we disable/hide the menu bar
                /// The New/Open buttons of the command bar are disabled
                /// Other things can be added as required (and supported ..:) )
                /// Lots of commented code in here, if somebody needs to disable specific menu or sub-menu items.
                ///
                int counter = wd.ActiveWindow.Application.CommandBars.Count;
                for (int i = 1; i <= counter; i++)
                {
                    try
                    {
                        String nm = wd.ActiveWindow.Application.CommandBars[i].Name;
                        if (nm == "Standard")
                        {
                            //nm=i.ToString()+" "+nm;
                            //MessageBox.Show(nm);
                            int count_control = wd.ActiveWindow.Application.CommandBars[i].Controls.Count;
                            for (int j = 1; j <= 3; j++)
                            {
                                //MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].ToString());
                                wd.ActiveWindow.Application.CommandBars[i].Controls[j].Enabled = false;
                            }
                        }

                        if (nm == "Menu Bar")
                        {
                            //To disable the menubar, use the following (1) line
                            //wd.ActiveWindow.Application.CommandBars[i].Enabled=false;
                            for (int j = 1; j <= 6; j++)
                            {
                                //((Office.CommandBarPopup)wd.ActiveWindow.Application.CommandBars[i].Controls[1]).Controls[j].Enabled = false;
                                ((Microsoft.Office.Core.CommandBarPopup)wd.ActiveWindow.Application.CommandBars[i].Controls[1]).Controls[j].Enabled = false;
                            }



                            /// If you want to have specific menu or sub-menu items, write the code here.
                            /// Samples commented below

                            //							MessageBox.Show(nm);
                            //int count_control=wd.ActiveWindow.Application.CommandBars[i].Controls.Count;
                            //MessageBox.Show(count_control.ToString());

                            /*
                             *                          for(int j=1;j<=count_control;j++)
                             *                          {
                             *                                  /// The following can be used to disable specific menuitems in the menubar
                             *                                  /// wd.ActiveWindow.Application.CommandBars[i].Controls[j].Enabled=false;
                             *
                             *                                  //MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].ToString());
                             *                                  //MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].Caption);
                             *                                  //MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].accChildCount.ToString());
                             *
                             *
                             *                                  ///The following can be used to disable some or all the sub-menuitems in the menubar
                             *
                             *
                             *                                  ////Office.CommandBarPopup c;
                             *                                  ////c = (Office.CommandBarPopup)wd.ActiveWindow.Application.CommandBars[i].Controls[j];
                             *                                  ////
                             *                                  ////for(int k=1;k<=c.Controls.Count;k++)
                             *                                  ////{
                             *                                  ////	//MessageBox.Show(k.ToString()+" "+c.Controls[k].Caption + " -- " + c.Controls[k].DescriptionText + " -- " );
                             *                                  ////	try
                             *                                  ////	{
                             *                                  ////		c.Controls[k].Enabled=false;
                             *                                  ////		c.Controls["Close Window"].Enabled=false;
                             *                                  ////	}
                             *                                  ////	catch
                             *                                  ////	{
                             *                                  ////
                             *                                  ////	}
                             *                                  ////}
                             *
                             *
                             *
                             *                                          //wd.ActiveWindow.Application.CommandBars[i].Controls[j].Control	 Controls[0].Enabled=false;
                             *                                  }
                             */
                        }

                        nm = "";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }



                // Show the word-document
                try
                {
                    wd.Visible = true;
                    wd.Activate();

                    SetWindowPos(wordWnd, this.Handle.ToInt32(), 0, 0, this.Bounds.Width, this.Bounds.Height, SWP_NOZORDER | SWP_NOMOVE | SWP_DRAWFRAME | SWP_NOSIZE);

                    //Call onresize--I dont want to write the same lines twice
                    OnResize();
                }
                catch
                {
                    MessageBox.Show("Error: do not load the document into the control until the parent window is shown!");
                }

                /// We want to remove the system menu also. The title bar is not visible, but we want to avoid accidental minimize, maximize, etc ..by disabling the system menu(Alt+Space)
                try
                {
                    int hMenu = GetSystemMenu(wordWnd, false);
                    if (hMenu > 0)
                    {
                        int menuItemCount = GetMenuItemCount(hMenu);
                        RemoveMenu(hMenu, menuItemCount - 1, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 2, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 3, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 4, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 5, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 6, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 7, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 8, MF_REMOVE | MF_BYPOSITION);
                        DrawMenuBar(wordWnd);
                    }
                }
                catch { };



                this.Parent.Focus();
            }
            deactivateevents = false;
        }
コード例 #26
0
ファイル: Form1.cs プロジェクト: Oblongmana/Bulk-Distributor
        private void btnRun_Click(object sender, EventArgs e)
        {
            //Column header references for Alpha extract file, 0-indexed. Update as needed.
            int alphaDBIRDCol = 0;
            int alphaDBFirstNameCol = 1;
            int alphaDBSurnameCol = 2;
            int alphaDBMobileCol = 6;
            int alphaDBEmailCol = 7;
            int alphaDBStatusCol = 8;
            int alphaDBAddress1Col = 10;
            int alphaDBAddress2Col = 11;
            int alphaDBSuburbCol = 12;
            int alphaDBCityCol = 13;
            int alphaDBPostcodeCol = 14;

            //Column header references for MYOB extract file, 0-indexed. Update as needed.
            int myobIRDCol = 0;
            int myobNameCol = 1;
            int myobClientIDCol = 2;

            //Column header references for Client List file, 0-indexed. These are the Mail Merge field names. Update as needed
            string clientListIRD = "IRDNum";
            string clientListFirstName = "FirstName";
            string clientListSurname = "Surname";
            string clientListEmail = "Email";
            string clientListCellphone = "Cellphone";
            string clientListAddress1 = "Address1";
            string clientListAddress2 = "Address2";
            string clientListSuburb = "Suburb";
            string clientListCity = "City";
            string clientListPostcode = "Postcode";

            //Record our sending priorities
            int letterPriority = cmbLetterPriorities.SelectedIndex + 1;
            int emailPriority = cmbEmailPriorities.SelectedIndex + 1;
            int cellPriority = cmbTxtPriorities.SelectedIndex + 1;

            if (!(letterPriority == 4 && emailPriority == 4 && cellPriority == 4))
            {
                //Stash all Alpha extract info in a DataTable, and clean the IRD numbers. Don't bother cleaning anything else till later - we'll only clean if we want that client's info
                GenericParserAdapter alphaDBParser = new GenericParserAdapter();
                alphaDBParser.SetDataSource(tbAlphaDB.Text);
                alphaDBParser.FirstRowHasHeader = false;
                alphaDBParser.ColumnDelimiter = ',';
                System.Data.DataTable alphaDBTable = alphaDBParser.GetDataTable();
                //This column gets a name because we need to do SELECT statements using this later
                alphaDBTable.Columns[alphaDBIRDCol].ColumnName = clientListIRD;

                //Stash all MYOB (NZAccountant) extract info in a DataTable
                GenericParserAdapter myobDBParser = new GenericParserAdapter();
                System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
                myobDBParser.SetDataSource((new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent.FullName) + "\\Resources\\20120309_myob_client_dump.csv");

                myobDBParser.FirstRowHasHeader = true;
                myobDBParser.ColumnDelimiter = ',';
                System.Data.DataTable myobDBTable = myobDBParser.GetDataTable();
                //This column gets a name because we need to do SELECT statements using this later
                myobDBTable.Columns[myobIRDCol].ColumnName = clientListIRD;

                foreach (DataRow currRow in alphaDBTable.Rows)
                {
                    string irdNumString = Regex.Replace((string)currRow[alphaDBIRDCol], "\\D", ""); //TODO: This can cause exceptions. Really should handle this
                    int extractedIRDNum = 0;
                    bool extractedIRDBool = Int32.TryParse(irdNumString, out extractedIRDNum);

                    currRow[alphaDBIRDCol] = extractedIRDBool ? extractedIRDNum.ToString() : irdNumString;
                }

                //Put all the supplied ird numbers for clients we're distributing to into a DataTable
                GenericParserAdapter clientListParser = new GenericParserAdapter();
                clientListParser.SetDataSource(tbClientNums.Text);
                clientListParser.FirstRowHasHeader = false;
                clientListParser.ColumnDelimiter = ',';
                clientListParser.ExpectedColumnCount = 1;
                System.Data.DataTable clientListTable = clientListParser.GetDataTable();

                clientListTable.Columns[0].ColumnName = clientListIRD;
                clientListTable.Columns.Add(clientListFirstName);
                clientListTable.Columns.Add(clientListSurname);
                clientListTable.Columns.Add(clientListEmail);
                clientListTable.Columns.Add(clientListCellphone);
                clientListTable.Columns.Add(clientListAddress1);
                clientListTable.Columns.Add(clientListAddress2);
                clientListTable.Columns.Add(clientListSuburb);
                clientListTable.Columns.Add(clientListCity);
                clientListTable.Columns.Add(clientListPostcode);

                //We're going to need a DataTable for reporting errors too
                System.Data.DataTable errorTable = new System.Data.DataTable();
                errorTable.Columns.Add("IRD Number");
                errorTable.Columns.Add("Error Description");

                //For each client we're distributing to, retrieve (and clean) their information from the alphaDbTable
                Regex emailRegex = new Regex(@"^(([^<>()[\]\\.,;:\s@\""]+"
                            + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                            + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                            + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                            + @"[a-zA-Z]{2,}))$"); //http://geekswithblogs.net/VROD/archive/2007/03/16/109007.aspx

                System.Data.DataTable postListTable = clientListTable.Clone();
                System.Data.DataTable emailListTable = clientListTable.Clone();
                System.Data.DataTable cellListTable = clientListTable.Clone();

                foreach (DataRow currClient in clientListTable.Rows)
                {

                    //Check if it's an MYOB client. If so, this is an error
                    if (myobDBTable.Select(clientListIRD + " = \'" + ((string)currClient[clientListIRD]) + "\'").Length == 0)
                    {
                        DataRow[] alphaClientDetailsArray;
                        alphaClientDetailsArray = alphaDBTable.Select(clientListIRD + " = \'" + ((string)currClient[clientListIRD]) + "\'"); //"IRDNum = [search term]"
                        DataColumnCollection test = alphaDBTable.Columns;
                        //If we successfully retrieved the client's details, clean and record them. If not, mark this as an error client
                        if (alphaClientDetailsArray.Length > 0)
                        {
                            //Ignore multiple results, just take the first match.
                            DataRow alphaClientDetails = alphaClientDetailsArray[0];

                            //If successfully retrieved data, check if Address Line 1 is a dud. If so, mark this as an error client
                            currClient[clientListFirstName] = EncapsulateSpeech(ToTitleCase((string)alphaClientDetails[alphaDBFirstNameCol]));
                            currClient[clientListSurname] = EncapsulateSpeech(ToTitleCase((string)alphaClientDetails[alphaDBSurnameCol]));
                            currClient[clientListEmail] = emailRegex.IsMatch((string)alphaClientDetails[alphaDBEmailCol]) ? EncapsulateSpeech((string)alphaClientDetails[alphaDBEmailCol]) : "";

                            string tempCellphone = EncapsulateSpeech((string)alphaClientDetails[alphaDBMobileCol]);
                            currClient[clientListCellphone] = cleanCellphone(ref tempCellphone) ? EncapsulateSpeech((string)tempCellphone) : "";

                            currClient[clientListAddress1] = EncapsulateSpeech(ToTitleCase((string)alphaClientDetails[alphaDBAddress1Col]));
                            currClient[clientListAddress2] = EncapsulateSpeech(ToTitleCase((string)alphaClientDetails[alphaDBAddress2Col]));

                            //If the city is blank (after removing whitespace), but there's a postcode, then put the postcode on the end of the suburb
                            string tempCity = Regex.Replace((string)alphaClientDetails[alphaDBCityCol], @"\s+", "");
                            string tempPostCode = (string)alphaClientDetails[alphaDBPostcodeCol];
                            try
                            {
                                tempPostCode = Int32.Parse(tempPostCode) == 0 ? tempPostCode = "" : ((tempPostCode).Length < 4 && (tempPostCode).Length > 0 ? (tempPostCode).PadLeft(4, '0') : tempPostCode); //TRAP! If inside an if :)
                            }
                            catch (Exception postCodeFailed) //catch all :)
                            {
                                tempPostCode = "";
                            }

                            string tempSuburb = (string)alphaClientDetails[alphaDBSuburbCol];

                            if (tempCity == "" && tempPostCode.Length > 0)
                            {
                                tempSuburb = tempSuburb + " " + tempPostCode;
                                tempCity = "";
                                tempPostCode = "";
                            }

                            currClient[clientListSuburb] = EncapsulateSpeech(ToTitleCase(tempSuburb));
                            currClient[clientListCity] = EncapsulateSpeech(ToTitleCase(tempCity));
                            currClient[clientListPostcode] = EncapsulateSpeech(tempPostCode);

                            //Decide whether this is a mail client, an email client, or a cell client - then put into appropo DataTable
                            //    //TODO: This whole section is hideous and needs rewriting
                            bool firstLevelFailure = false;
                            bool secondLevelFailure = false;
                            bool thirdLevelFailure = false;
                            string tempTestAddress1 = (string)currClient[clientListAddress1];
                            string tempTestEmail = (string)currClient[clientListEmail];
                            string tempTestCellphone = (string)currClient[clientListCellphone];
                            switch (letterPriority)
                            {
                                case 1: firstLevelFailure = ((tempTestAddress1 == "" || tempTestAddress1 == "\"\"" || tempTestAddress1 == "0") && firstLevelFailure != true); break;
                                case 2: secondLevelFailure = ((tempTestAddress1 == "" || tempTestAddress1 == "\"\"" || tempTestAddress1 == "0") && secondLevelFailure != true); break;
                                case 3: thirdLevelFailure = ((tempTestAddress1 == "" || tempTestAddress1 == "\"\"" || tempTestAddress1 == "0") && thirdLevelFailure != true); break;
                                default: break;
                            }
                            switch (emailPriority)
                            {
                                case 1: firstLevelFailure = ((tempTestEmail == "" || tempTestEmail == "\"\"" || tempTestEmail == "0") && firstLevelFailure != true); break;
                                case 2: secondLevelFailure = ((tempTestEmail == "" || tempTestEmail == "\"\"" || tempTestEmail == "0") && secondLevelFailure != true); break;
                                case 3: thirdLevelFailure = ((tempTestEmail == "" || tempTestEmail == "\"\"" || tempTestEmail == "0") && thirdLevelFailure != true); break;
                                default: break;
                            }
                            switch (cellPriority)
                            {
                                case 1: firstLevelFailure = ((tempTestCellphone == "" || tempTestCellphone == "\"\"" || tempTestCellphone == "0") && firstLevelFailure != true); break;
                                case 2: secondLevelFailure = ((tempTestCellphone == "" || tempTestCellphone == "\"\"" || tempTestCellphone == "0") && secondLevelFailure != true); break;
                                case 3: thirdLevelFailure = ((tempTestCellphone == "" || tempTestCellphone == "\"\"" || tempTestCellphone == "0") && thirdLevelFailure != true); break;
                                default: break;
                            }

                            bool actuallySentSomething = false;
                            if (firstLevelFailure == false)
                            {
                                if (letterPriority == 1) { postListTable.ImportRow(currClient); actuallySentSomething = true; }
                                if(emailPriority == 1) { emailListTable.ImportRow(currClient); actuallySentSomething = true; }
                                if (cellPriority == 1) { cellListTable.ImportRow(currClient); actuallySentSomething = true; }
                            }
                            else if (secondLevelFailure == false)
                            {
                                if (letterPriority == 2) { postListTable.ImportRow(currClient); actuallySentSomething = true; }
                                if (emailPriority == 2) { emailListTable.ImportRow(currClient); actuallySentSomething = true; }
                                if (cellPriority == 2) { cellListTable.ImportRow(currClient); actuallySentSomething = true; }
                            }
                            else if (thirdLevelFailure == false)
                            {
                                if (letterPriority == 3) { postListTable.ImportRow(currClient); actuallySentSomething = true; }
                                if (emailPriority == 3) { emailListTable.ImportRow(currClient); actuallySentSomething = true; }
                                if (cellPriority == 3) { cellListTable.ImportRow(currClient); actuallySentSomething = true; }
                            }
                            else //Whelp, we've completely failed.
                            {
                                DataRow newErrorRow = errorTable.NewRow();
                                newErrorRow["IRD Number"] = currClient[clientListIRD];
                                newErrorRow["Error Description"] = "No valid contact details that match with what you want to send";
                                errorTable.Rows.Add(newErrorRow);
                            }

                            //Just in case we didn't find anything we could send to, but didn't have a failure at each level. Not sure this actually reachable, but being safe :)
                            if (!actuallySentSomething)
                            {
                                DataRow newErrorRow = errorTable.NewRow();
                                newErrorRow["IRD Number"] = currClient[clientListIRD];
                                newErrorRow["Error Description"] = "No valid contact details that match with what you want to send. You should contact the client to update details or try and send your message by a different method.";
                                errorTable.Rows.Add(newErrorRow);
                            }
                        }
                        else
                        {
                            DataRow newErrorRow = errorTable.NewRow();
                            newErrorRow["IRD Number"] = currClient[clientListIRD];
                            newErrorRow["Error Description"] = "Could not find the client in the database. Please check you entered this correctly. If you did then check with NZAccountant and PBA. Tell developer/manager/team leader if not a client of either of them.";
                            errorTable.Rows.Add(newErrorRow);
                        }
                    }
                    else
                    {
                        DataRow newErrorRow = errorTable.NewRow();
                        newErrorRow["IRD Number"] = currClient[clientListIRD];
                        newErrorRow["Error Description"] = "This appears to be an NZAccountant Client; check with them. Tell developer/manager/team leader if not a client of NZA.";
                        errorTable.Rows.Add(newErrorRow);
                    }
                }

                //Create a temp file for the Error data, dump it out, and open it in Excel
                String errorFileLocation = System.IO.Path.GetTempFileName() + ".csv";
                FileStream errorOutputStream = File.Create(errorFileLocation);
                if (errorTable.Rows.Count > 0)
                {
                    //write headers
                    int errorColumnCount = errorTable.Columns.Count;
                    for (int i = 0; i < errorColumnCount; i++)
                    {
                        AddText(errorOutputStream, errorTable.Columns[i].ColumnName);
                        if (i != errorColumnCount - 1) AddText(errorOutputStream, ",");
                    }
                    AddText(errorOutputStream, Environment.NewLine);

                    //write data
                    foreach (DataRow currClient in errorTable.Rows)
                    {
                        for (int i = 0; i < errorColumnCount; i++)
                        {
                            AddText(errorOutputStream, (string)currClient[i]);
                            if (i != errorColumnCount - 1) AddText(errorOutputStream, ",");
                        }
                        AddText(errorOutputStream, Environment.NewLine);
                    }
                    errorOutputStream.Close();
                }

                //Create a temp file for the Alpha import data, dump it out, and open it in Excel
                String alphaFileLocation = System.IO.Path.GetTempFileName() + ".csv";
                FileStream alphaOutputStream = File.Create(alphaFileLocation);

                //write data
                foreach (DataRow currClient in postListTable.Rows)
                {
                    AddText(alphaOutputStream, (string)currClient[clientListIRD] + ",");
                    AddText(alphaOutputStream, EncapsulateSpeech(tbAlphaNotes.Text + ". Sent by Post"));
                    AddText(alphaOutputStream, Environment.NewLine);
                }
                foreach (DataRow currClient in emailListTable.Rows)
                {
                    AddText(alphaOutputStream, (string)currClient[clientListIRD] + ",");
                    AddText(alphaOutputStream, EncapsulateSpeech(tbAlphaNotes.Text + ". Sent by Email"));
                    AddText(alphaOutputStream, Environment.NewLine);
                }
                foreach (DataRow currClient in cellListTable.Rows)
                {
                    AddText(alphaOutputStream, (string)currClient[clientListIRD] + ",");
                    AddText(alphaOutputStream, EncapsulateSpeech(tbAlphaNotes.Text + ". Sent by Text Message"));
                    AddText(alphaOutputStream, Environment.NewLine);
                }
                alphaOutputStream.Close();

                //Make the error file visible
                Excel._Application oExcel = new Excel.Application();
                oExcel.Visible = true;
                oExcel.ScreenUpdating = true;
                if (errorTable.Rows.Count > 0)
                {
                    oExcel.Workbooks.Open(errorFileLocation, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                }

                //Make the notes file visible
                oExcel.Workbooks.Open(alphaFileLocation, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                //Send emails. //COMMENTED OUT BEHAVIOUR: If no emails, let the user know
                if (emailListTable.Rows.Count > 0)
                {
                    int columnCount = emailListTable.Columns.Count;
                    StreamReader myEmailStream = new System.IO.StreamReader(@tbEmailTemplate.Text);
                    string myEmailString = myEmailStream.ReadToEnd();
                    myEmailStream.Close();

                    foreach (DataRow currClient in emailListTable.Rows)
                    {
                        string tempEmailString = myEmailString;
                        tempEmailString = tempEmailString.Replace("[[[[FIRST_NAME]]]]", RemoveSpeech((string)currClient[clientListFirstName]));
                        tempEmailString = tempEmailString.Replace("[[[[IRD_NUMBER]]]]", RemoveSpeech((string)currClient[clientListIRD]));
                        tempEmailString = tempEmailString.Replace(Environment.NewLine, "<br/>");
                        tempEmailString = HTMLEncodeSpecialChars(tempEmailString);
                        //myEmailString = myEmailString.Replace("[[[[FULL_NAME]]]]", (string)currClient[clientListIRD]);
                        tempEmailString = Resources.EmailContent.Replace("[[[[EMAIL_CONTENT]]]]", tempEmailString);
                        SendEmail(
                            RemoveSpeech((string)currClient[clientListEmail]),
                            tempEmailString,tbSubject.Text.Replace("<FirstName>",RemoveSpeech((string)currClient[clientListFirstName])).Replace("<LastName>",RemoveSpeech((string)currClient[clientListSurname])),
                            BodyType.HTML);
                    }

                }
                else
                {
                    //MessageBox.Show("No emails were sent");
                }

                //Send texts. //COMMENTED OUT BEHAVIOUR: If no emails, let the user know
                if (cellListTable.Rows.Count > 0)
                {
                    int columnCount = cellListTable.Columns.Count;
                    StreamReader myEmailStream = new System.IO.StreamReader(tbTextTemplate.Text);
                    string myEmailString = myEmailStream.ReadToEnd();
                    myEmailStream.Close();

                    foreach (DataRow currClient in cellListTable.Rows)
                    {
                        string tempEmailString = myEmailString;
                        tempEmailString = tempEmailString.Replace("[[[[FIRST_NAME]]]]", RemoveSpeech((string)currClient[clientListFirstName]));
                        tempEmailString = tempEmailString.Replace("[[[[IRD_NUMBER]]]]", RemoveSpeech((string)currClient[clientListIRD]));
                        SendEmail(
                            RemoveSpeech((string)currClient[clientListCellphone] + "@sms.tnz.co.nz"),
                            tempEmailString,
                            "",
                            BodyType.Text);
                    }

                }
                else
                {
                    //MessageBox.Show("No emails were sent");
                }

                //Create a temp file for the mail merge data, and dump it all out. //COMMENTED OUT BEHAVIOUR: If no letters, let the user know
                if (postListTable.Rows.Count > 0)
                {
                    String mergeFileLocation = System.IO.Path.GetTempFileName() + ".csv";
                    FileStream mergeOutputStream = File.Create(mergeFileLocation);

                    //write headers
                    int columnCount = postListTable.Columns.Count;
                    for (int i = 0; i < columnCount; i++)
                    {
                        AddText(mergeOutputStream, postListTable.Columns[i].ColumnName);
                        if (i != columnCount - 1) AddText(mergeOutputStream, ",");
                    }
                    AddText(mergeOutputStream, Environment.NewLine);

                    //write data
                    foreach (DataRow currClient in postListTable.Rows)
                    {
                        for (int i = 0; i < columnCount; i++)
                        {
                            AddText(mergeOutputStream, (string)currClient[i]);
                            if (i != columnCount - 1) AddText(mergeOutputStream, ",");
                        }
                        AddText(mergeOutputStream, Environment.NewLine);
                    }
                    mergeOutputStream.Close();

                    //Run the mail merge
                    Object oMailMergeFile = tbLetterTemplate.Text;
                    Object oMissing = System.Reflection.Missing.Value;
                    Object oFalse = false;
                    Object oTrue = true;
                    Object oSql = "Select * from [Table1$]";

                    Word._Application oWord = new Word.Application();
                    oWord.Visible = false;
                    oWord.ScreenUpdating = false;
                    Word._Document myDoc = oWord.Documents.Add(ref oMailMergeFile, ref oMissing, ref oMissing, ref oMissing);
                    myDoc.MailMerge.MainDocumentType = Word.WdMailMergeMainDocType.wdFormLetters;
                    myDoc.MailMerge.OpenDataSource(@mergeFileLocation, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oSql, ref oMissing, ref oMissing, ref oMissing);
                    myDoc.MailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument;
                    myDoc.MailMerge.Execute(ref oFalse);
                    saveMergeDocs(oWord);
                    myDoc.Close(ref oFalse, ref oMissing, ref oMissing);

                    //Make the merge visible
                    oWord.Visible = true;
                    oWord.ScreenUpdating = true;
                    oWord.Activate();

                    File.Delete(mergeFileLocation);
                }
                else
                {
                    //MessageBox.Show("No letters were printed");
                }

                //DEBUG: comment the following out for production
                //oExcel.Workbooks.Open(mergeFileLocation, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            }
            else
            {
                MessageBox.Show("Please set either email, text, or letter to something other than \"Do Not Send\"");
            }
        }
コード例 #27
0
ファイル: WordSpecExport.cs プロジェクト: rubilnik4/SveraG
        private void podgotovWord(Microsoft.Office.Interop.Word.Application oWord, Microsoft.Office.Interop.Excel.Application oExcel, bool rezhim, Boolean needOfvisible)
        {
            try
            {
                if (rezhim == false)
                {
                    oWord.Application.ScreenUpdating       = false;
                    oWord.Application.Visible              = false;
                    oWord.Options.AnimateScreenMovements   = false;
                    oWord.Options.UpdateLinksAtOpen        = false;
                    oWord.Options.CheckGrammarAsYouType    = false;
                    oWord.Options.CheckGrammarWithSpelling = false;
                    oWord.Options.BackgroundSave           = false;
                    oWord.Options.AutoWordSelection        = false;
                    oWord.Options.AllowClickAndTypeMouse   = false;
                    oWord.Options.SmartCursoring           = false;
                    oWord.DisplayAutoCompleteTips          = false;
                    oWord.Options.ContextualSpeller        = false;
                    oWord.Options.CheckSpellingAsYouType   = false;

                    if (oExcel != null)
                    {
                        oExcel.DisplayAlerts = false;
                        oExcel.Application.ScreenUpdating = false;
                        oExcel.Application.Visible        = false;
                    }
                }
                else
                {
                    if (oWord != null)
                    {
                        oWord.Options.AnimateScreenMovements   = true;
                        oWord.Options.UpdateLinksAtOpen        = true;
                        oWord.Options.CheckGrammarAsYouType    = true;
                        oWord.Options.CheckGrammarWithSpelling = true;
                        oWord.Options.BackgroundSave           = true;
                        oWord.Options.AutoWordSelection        = true;
                        oWord.Options.AllowClickAndTypeMouse   = true;
                        oWord.Options.SmartCursoring           = true;
                        oWord.DisplayAutoCompleteTips          = true;
                        oWord.Options.ContextualSpeller        = true;
                        oWord.Options.CheckSpellingAsYouType   = true;
                        oWord.Application.ScreenUpdating       = true;
                        if (needOfvisible == true)
                        {
                            oWord.Application.Visible = true;
                            oWord.Activate();
                        }
                    }
                    if (oExcel != null)
                    {
                        oExcel.DisplayAlerts = true;
                        oExcel.Application.ScreenUpdating = true;
                        if (needOfvisible == true)
                        {
                            oExcel.Application.Visible = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("podgotovWord", ex);
            }
        }
コード例 #28
0
        private void btnPrint_Click(object sender, EventArgs e)
        {
            String  opdrachtenInhoud = "";
            decimal totalAmount      = 0;

            foreach (DataGridViewRow row in facturenGridView.Rows)
            {
                if ((Boolean)row.Cells[0].Value != false)
                {
                    int opdrachtID = 0;
                    if (!int.TryParse(row.Cells[1].Value.ToString(), out opdrachtID))
                    {
                        continue;
                    }
                    opdracht         op = OpdrachtManagement.getOpdracht(opdrachtID);
                    opdracht_factuur of = FactuurManagement.getFactuurVanOpdracht(op);
                    foreach (opdracht_factuur_detail ofd in FactuurManagement.getFactuurDetails(of))
                    {
                        opdrachtenInhoud += of.opdracht_id + "\t";
                        opdrachtenInhoud += ofd.omschrijving + "\t";
                        opdrachtenInhoud += ofd.bedrag_basis + "\t";
                        opdrachtenInhoud += ofd.btw_percent + "\t";
                        opdrachtenInhoud += ofd.btw_bedrag + "\t";
                        opdrachtenInhoud += ofd.bedrag_inclusief + "\t";
                        opdrachtenInhoud += System.Environment.NewLine;

                        totalAmount += ofd.bedrag_inclusief.Value;
                        FactuurNummering nummer = new FactuurNummering();
                        nummer.bedrijf      = opdracht.FactuurNummering.bedrijf;
                        nummer.FactuurNr    = opdracht.FactuurNummering.FactuurNr;
                        nummer.FactuurJaar  = opdracht.FactuurNummering.FactuurJaar;
                        op.FactuurNummering = nummer;
                        Backend.DataContext.dc.SubmitChanges();
                    }


                    //opdrachtenInhoud += row.Cells[1].Value + "\t" + row.Cells[2].Value + "\t" + row.Cells[4].Value + "\t" + row.Cells[5].Value + "\t€" + row.Cells[6].Value + System.Environment.NewLine;
                    //totalAmount += Convert.ToDouble(row.Cells[6].Value.ToString());
                }
            }

            if (totalAmount > 0)
            {
                locatie adres = KlantManagement.getAdresVanKlant(opdracht.klant.klant_id);

                //Convert date to acceptable format for use in file name
                String datum = DateTime.Today.ToString("yyyy-MM-dd");

                //missing oject to use with various word commands
                object missing = System.Reflection.Missing.Value;

                //the template file you will be using
                object fileToOpen = (object)@"R:\CarGo\opdracht_template.docx";

                //Where the new file will be saved to.
                object fileToSave = (object)@"R:\CarGo\opdrachten\opdracht_" + opdracht.klant.naam + "_" + datum + ".docx";

                //Create new instance of word and create a new document
                Word.Application wordApp = new Word.Application();
                Word.Document    doc     = null;

                //Properties for the new word document
                object readOnly  = false;
                object isVisible = false;

                //Settings the application to invisible, so the user doesn't notice that anything is going on
                wordApp.Visible = false;
                try
                {
                    try
                    {
                        File.Copy(fileToOpen.ToString(), fileToSave.ToString(), true);
                    }
                    catch
                    {
                        MessageBox.Show("Loading the template file failed.", "Important Note", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                        return;
                    }

                    readOnly = false;
                    doc      = wordApp.Documents.Open(ref fileToSave, ref missing,
                                                      ref readOnly, 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);
                }
                catch { }



                PrintManagement.findAndReplace(doc, "factuurdatum", datum);
                PrintManagement.findAndReplace(doc, "factuurnummer", opdracht.FactuurNummering.FactuurNr + " " + opdracht.FactuurNummering.FactuurJaar);
                PrintManagement.findAndReplace(doc, "startOfDocument", opdrachtenInhoud);
                PrintManagement.findAndReplace(doc, "totaal", "Totaal: €" + totalAmount);
                Console.WriteLine(opdrachtenInhoud);

                doc.Save();
                doc.Activate();
                //Making word visible to be able to show the print preview.
                wordApp.Visible = true;
                wordApp.Activate();
                //doc.PrintPreview();
            }
            else
            {
                MessageBox.Show("Onvoldoende gegevens om factuur op te stellen. Kijk Detail Facturatie na", "Important Note", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            }
        }
コード例 #29
0
ファイル: MainWindow.cs プロジェクト: lawenliu/MaRK
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Dictionary <int, string> sortedPageContent = new Dictionary <int, string>();

            sortedPageContent = pageResult.OrderByDescending(x => x.Value.Length).ToDictionary(x => x.Key, x => x.Value);
            if (sortedPageContent.Count == 0)
            {
                return;
            }

            int mostRelevantPage = sortedPageContent.Keys.ElementAt(0);

            string  filePath  = tvHighlightingResult.Nodes[0].Text;
            Process myProcess = new Process();

            if (filePath.EndsWith(".pdf"))
            {
                string    fileName            = FileNameParse.GetFileName(filePath);
                Process[] collectionOfProcess = Process.GetProcessesByName("AcroRd32");
                foreach (Process p in collectionOfProcess)
                {
                    string runningFile = p.MainWindowTitle;
                    if (runningFile.Contains("- Adobe Reader"))
                    {
                        int adobeIndex = runningFile.IndexOf("- Adobe Reader");
                        runningFile = runningFile.Substring(0, adobeIndex - 1);
                    }

                    if (runningFile.Equals(fileName))
                    {
                        p.Kill();
                    }
                }

                try
                {
                    myProcess.StartInfo.FileName  = "AcroRd32.exe";
                    myProcess.StartInfo.Arguments = string.Format("/A \"page={0}\" \"{1}\"", mostRelevantPage, filePath);
                    myProcess.Start();
                }

                catch
                {
                    MessageBox.Show("Failed to open pdf file. We need adobe reader to open the pdf file. Please make sure you have setup Adobe reader.");
                }
            }
            else
            {
                object missing = System.Reflection.Missing.Value;

                int  pageNumValue = Convert.ToInt32(mostRelevantPage);
                bool isActive     = Relocate(filePath, pageNumValue);

                if (!isActive)
                {
                    try
                    {
                        Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

                        app.Visible = true;
                        object readOnly = false;

                        var    doc   = app.Documents.Open(filePath, missing, readOnly);
                        object what  = WdGoToItem.wdGoToPage;
                        object which = WdGoToDirection.wdGoToAbsolute;
                        Range  range = app.Selection.GoTo(what, which, mostRelevantPage, missing);
                        doc.Activate();
                        app.Activate();
                        doc.Save();
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
コード例 #30
0
ファイル: WordDiff.cs プロジェクト: CIOIL/WordCompare
        static void Main(string[] args)
        {
            //
            //      Check for filenames and validate files exist
            //
            if (args.Length != 2)
            {
                System.Console.WriteLine("To compare two Microsoft Word documents use the following syntax:");
                System.Console.WriteLine("\tWordDiff [Document1] [Document2]");
                return;
            }

            object file1 = args[0];
            object file2 = args[1];

            if (!System.IO.File.Exists((string)file1))
            {
                System.Console.WriteLine("File does not exist: {0}", file1);
                return;
            }
            object fullPath1 = System.IO.Path.GetFullPath((string)file1);

            if (!System.IO.File.Exists((string)file2))
            {
                System.Console.WriteLine("File does not exist: {0}", file2);
                return;
            }
            object fullPath2 = System.IO.Path.GetFullPath((string)file2);

            //
            //      Open Word and compare files
            //
            MSWord.Application msWordApp = new MSWord.Application();
            msWordApp.Visible = false;
            object trueObj    = (object)true;
            object falseObj   = (object)false;
            object missingObj = Type.Missing;

            MSWord.Document msWordDocument1 = msWordApp.Documents.Open(ref fullPath1, ref missingObj, ref falseObj, ref falseObj,
                                                                       ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj,
                                                                       ref trueObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj);

            MSWord.Document msWordDocument2 = msWordApp.Documents.Open(ref fullPath2, ref missingObj, ref falseObj, ref falseObj,
                                                                       ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj,
                                                                       ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj);

            MSWord.Document msWordDocumentDiff = msWordApp.CompareDocuments(msWordDocument1, msWordDocument2,
                                                                            MSWord.WdCompareDestination.wdCompareDestinationNew, MSWord.WdGranularity.wdGranularityWordLevel,
                                                                            true, true, true, true, true, true, true, true, true, true, "", true);

            msWordDocument1.Close(ref missingObj, ref missingObj, ref missingObj);
            msWordDocument2.Close(ref missingObj, ref missingObj, ref missingObj);

            //
            //      Make sure Word is active and in the foreground
            //
            msWordApp.Visible = true;
            msWordApp.Activate();
            msWordApp.ActiveWindow.SetFocus();
            SetForegroundWindow((System.IntPtr)msWordApp.ActiveWindow.Hwnd);

            return;
        }
コード例 #31
0
ファイル: MainWindow.cs プロジェクト: lawenliu/MaRK
        private void tvSummaryResult_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            object  pageNumber = e.Node.Tag;
            string  filePath   = tvHighlightingResult.Nodes[0].Text;
            string  fileName   = FileNameParse.GetFileName(filePath);
            Process myProcess  = new Process();

            if (filePath.EndsWith(".pdf"))
            {
                Process[] collectionOfProcess = Process.GetProcessesByName("AcroRd32");
                foreach (Process p in collectionOfProcess)
                {
                    string runningFile = p.MainWindowTitle;
                    if (runningFile.Contains("- Adobe Reader"))
                    {
                        int adobeIndex = runningFile.IndexOf("- Adobe Reader");
                        runningFile = runningFile.Substring(0, adobeIndex - 1);
                    }

                    if (runningFile.Equals(fileName))
                    {
                        p.Kill();
                    }
                }

                try
                {
                    myProcess.StartInfo.FileName  = "AcroRd32.exe";
                    myProcess.StartInfo.Arguments = string.Format("/A \"page={0}\" \"{1}\"", pageNumber, filePath);
                    myProcess.Start();
                }

                catch
                {
                    MessageBox.Show("Failed to open pdf file. We need adobe reader to open the pdf file. Please make sure you have setup Adobe reader.");
                }
            }
            else
            {
                object missing = System.Reflection.Missing.Value;

                int  pageNumValue = Convert.ToInt32(pageNumber);
                bool isActive     = Relocate(filePath, pageNumValue);

                if (!isActive)
                {
                    try
                    {
                        Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();

                        app.Visible = true;
                        object readOnly = false;

                        var    doc   = app.Documents.Open(filePath, missing, readOnly);
                        object what  = WdGoToItem.wdGoToPage;
                        object which = WdGoToDirection.wdGoToAbsolute;
                        Range  range = app.Selection.GoTo(what, which, pageNumber, missing);
                        doc.Activate();
                        app.Activate();
                        doc.Save();
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }