Beispiel #1
0
        private static Word.ContentControl GetBodyContentControl(Word.Document doc, string name)
        {
            Word.ContentControl contentControl = null;

            try
            {
                foreach (Microsoft.Office.Interop.Word.ContentControl control in doc.ContentControls)
                {
                    if (control.Tag.ToUpper().Equals(name.ToUpper()))
                    {
                        contentControl = control;
                        break;
                    }

                    if (Marshal.IsComObject(control))
                    {
                        Marshal.ReleaseComObject(control);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogException(LogLevel.Error, "GetBodyContentControl", ex);
            }

            return(contentControl);
        }
        /// <summary>
        /// Create a new CC if not already in one.
        /// </summary>
        /// <param name="controlType"></param>
        /// <param name="docx"></param>
        /// <param name="selection"></param>
        /// <returns></returns>
        public static Word.ContentControl MakeOrReuse(bool tryToReuse, Word.WdContentControlType controlType,
                                                      Word.Document docx, Word.Selection selection)
        {
            // step 1: create content control, if necessary
            // are we in a content control?
            Word.ContentControl cc = null;
            if (tryToReuse)
            {
                cc = ContentControlMaker.getActiveContentControl(docx, selection);
            }
            object missing = System.Type.Missing;

            if (cc == null)
            {
                // Add one
                cc       = docx.ContentControls.Add(controlType, ref missing);
                cc.Title = "[New]";
            }
            else
            {
                // we're in a content control already.
                // Have they selected all of it?
                // If so, is this add or re-map?
                if (controlType.Equals(Word.WdContentControlType.wdContentControlRichText))
                {
                    cc.XMLMapping.Delete();
                }
                cc.Type = controlType;
            }

            return(cc);
        }
Beispiel #3
0
        /// <summary>
        /// Bu metot o an aktif olan soru grubu kutusundaki tabloya
        /// içine bir soru metni yazılacak bir zengin metin kutusu
        /// ve o sorunun için bir seçim kutusu ekler.
        /// </summary>
        public void SoruEkle()
        {
            // Her bir form kutusunu tara ve o bir soru grubu mu diye bak.
            foreach (Word.ContentControl ctrlGroup in this.ContentControls)
            {
                HurTestDataSet.QuestionGroupsRow qgroupRow =
                    docDataSet.QuestionGroups.FindByGroupID(ctrlGroup.ID);
                if (qgroupRow == null)
                {
                    continue;
                }
                // O an seçili konum hangi soru grubu kutusundaysa o kutudaki
                // tabloya bir soru kutusu ekle.
                if (Globals.ThisDocument.Application.Selection.Range.InRange(ctrlGroup.Range))
                {
                    Word.Table tblGroup = ctrlGroup.Range.Tables[1];
                    tblGroup.Rows.Add();

                    Word.ContentControl chkIncludeQuestion = this.ContentControls.Add(
                        Word.WdContentControlType.wdContentControlCheckBox,
                        tblGroup.Rows.Last.Cells[1].Range);
                    chkIncludeQuestion.Checked            = true;
                    chkIncludeQuestion.LockContentControl = true;

                    Word.ContentControl ctrlQuestion = this.ContentControls.Add(
                        Word.WdContentControlType.wdContentControlRichText,
                        tblGroup.Rows.Last.Cells[2].Range);
                    docDataSet.Questions.AddQuestionsRow(ctrlQuestion.ID, qgroupRow, chkIncludeQuestion.ID, true, 0);
                    ctrlQuestion.SetPlaceholderText(null, null, "Soru metnini buraya yazın");
                    ctrlQuestion.LockContentControl = true;
                }
            }
        }
Beispiel #4
0
        private bool ccStartsAtStartOfParagraph(Word.ContentControl currentCC)
        {
            /*
             * from start of P
             *  p  S
             *  cc S+1
             *
             *  exc pmark:
             *  p  Z
             *  cc Z-2
             *
             *  inc p mark:
             *  p   Z
             *  cc  Z
             *
             *  Index of pmark = index of start of next P.
             */

            Word.Document document = Globals.ThisAddIn.Application.ActiveDocument;
            Word.Range    ccRange  = currentCC.Range;
            ccRange.Select();
            Word.Range pRange = document.Windows[1].Selection.Paragraphs[1].Range;

            log.Info("p {0}, {1}", pRange.Start, pRange.End);
            log.Info("cc {0}, {1}", ccRange.Start, ccRange.End);

            return(pRange.Start == (ccRange.Start + 1));
        }
Beispiel #5
0
        public static Word.ContentControl Insert1DChemistry(Word.Document doc, string text, bool isFormula, string tag)
        {
            string module = $"{Product}.{Class}.{MethodBase.GetCurrentMethod().Name}()";

            if (Globals.Chem4WordV3.SystemOptions == null)
            {
                Globals.Chem4WordV3.LoadOptions();
            }

            Word.Application app = Globals.Chem4WordV3.Application;

            bool existingStateOfCorrectSentenceCaps = app.AutoCorrect.CorrectSentenceCaps;
            bool existingStateOfSmartCutPaste       = app.Options.SmartCutPaste;

            Word.ContentControl cc = doc.ContentControls.Add(Word.WdContentControlType.wdContentControlRichText, ref _missing);

            app.AutoCorrect.CorrectSentenceCaps = false;
            app.Options.SmartCutPaste           = false;

            SetRichText(cc, text, isFormula);

            app.AutoCorrect.CorrectSentenceCaps = existingStateOfCorrectSentenceCaps;
            app.Options.SmartCutPaste           = existingStateOfSmartCutPaste;

            cc.Tag          = tag;
            cc.Title        = Constants.ContentControlTitle;
            cc.LockContents = true;

            return(cc);
        }
Beispiel #6
0
        public void ProcContentControls(WORD.ContentControl contentControl)
        {
            contentControl.Range.LanguageID = LocalLang.wdID;

            var targetFont = LocalLang.GetLocFont(contentControl.Range.Font.Name);

            //_SetFontProperty(targetFont, contentControl.Range.Font.Name, contentControl.Range.Font.NameAscii,
            //contentControl.Range.Font.NameOther);

            contentControl.Range.Font.Name      = targetFont;
            contentControl.Range.Font.NameAscii = targetFont;
            contentControl.Range.Font.NameOther = targetFont;

            if (LocalLang.IsFarEast)
            {
                contentControl.Range.LanguageIDFarEast = LocalLang.wdID;
                contentControl.Range.Font.NameFarEast  = targetFont;
            }

            if (LocalLang.IsRightToLeft)
            {
                contentControl.Range.LanguageIDOther = LocalLang.wdID;
                contentControl.Range.Font.NameBi     = targetFont;
            }
        }
Beispiel #7
0
        public static Word.ContentControl Insert1DChemistry(Word.Document doc, string text, bool isFormula, string tag)
        {
            string module = $"{Product}.{Class}.{MethodBase.GetCurrentMethod().Name}()";

            if (Globals.Chem4WordV3.SystemOptions == null)
            {
                Globals.Chem4WordV3.LoadOptions();
            }

            Word.Application app = Globals.Chem4WordV3.Application;

            var wordSettings = new WordSettings(app);

            Word.ContentControl cc = doc.ContentControls.Add(Word.WdContentControlType.wdContentControlRichText, ref _missing);

            SetRichText(cc.ID, text, isFormula);

            wordSettings.RestoreSettings(app);

            cc.Tag          = tag;
            cc.Title        = Constants.ContentControlTitle;
            cc.LockContents = true;

            return(cc);
        }
Beispiel #8
0
        public void btnSyncField_Click(IRibbonControl control)
        {
            var doc             = new OfficeDocument(Globals.ThisAddIn.Application.ActiveDocument);
            int proptectionType = -1;

            try
            {
                proptectionType = doc.TurnOffProtection(String.Empty);
                WordOM.ContentControl contentcontrol = Globals.ThisAddIn.Application.Selection.Range.ParentContentControl;
                if (contentcontrol == null)
                {
                    return;
                }
                WordOM.ContentControls matchingControls =
                    Globals.ThisAddIn.Application.ActiveDocument.SelectContentControlsByTag(contentcontrol.Tag);
                foreach (WordOM.ContentControl mc in matchingControls)
                {
                    mc.Range.Text = contentcontrol.Range.Text;
                }
            }
            catch (Exception e)
            {
                var logger = new EventViewerLogger();
                logger.Log(e.ToString(), Type.Error);

#if DEBUG
                MessageBox.Show(e.ToString(), @"sorry");
#endif
            }
            finally
            {
                doc.TurnOnProtection(proptectionType, String.Empty);
            }
        }
Beispiel #9
0
 private void ThisDocument_ContentControlBeforeDelete(Word.ContentControl OldContentControl, bool InUndoRedo)
 {
     if (OldContentControl.Tag == "question" && InUndoRedo == false)
     {
         string questionTitle = OldContentControl.Title;
         string resultString  = Regex.Match(questionTitle, @"\d+").Value;
         int    qNo           = Int32.Parse(resultString);
         questionList[qNo - 1].QuestionItem = null;
         questionList[qNo - 1] = null;
         questionList.RemoveAt(qNo - 1);
         Controls.Remove(OldContentControl);
         questionList.Select(c => { c.QuestionPosition = c.QuestionItem.Range.Information[Word.WdInformation.wdVerticalPositionRelativeToPage] + c.QuestionItem.Range.Information[Word.WdInformation.wdActiveEndPageNumber] * 1000; return(c); }).ToList();
         questionList = questionList.OrderBy(o => o.QuestionPosition).ToList();
         questionList.Select(c => { c.QuestionNumber = questionList.IndexOf(c) + 1; return(c); }).ToList();
         questionList.Select(c => { c.QuestionItem.Title = "Question " + c.QuestionNumber; return(c); }).ToList();
     }
     else if (OldContentControl.Tag == "question" && InUndoRedo == true)
     {
         string questionTitle = OldContentControl.Title;
         string resultString  = Regex.Match(questionTitle, @"\d+").Value;
         int    qNo           = Int32.Parse(resultString);
         questionList[qNo - 1].QuestionItem = null;
         questionList[qNo - 1] = null;
         questionList.RemoveAt(qNo - 1);
         Controls.Remove(OldContentControl);
         questionList.Select(c => { c.QuestionPosition = c.QuestionItem.Range.Information[Word.WdInformation.wdVerticalPositionRelativeToPage] + c.QuestionItem.Range.Information[Word.WdInformation.wdActiveEndPageNumber] * 1000; return(c); }).ToList();
         questionList = questionList.OrderBy(o => o.QuestionPosition).ToList();
         questionList.Select(c => { c.QuestionNumber = questionList.IndexOf(c) + 1; return(c); }).ToList();
         //questionList.Select(c => { c.QuestionItem.Title = "Question " + c.QuestionNumber; return c; }).ToList();
     }
 }
        private void doc_ContentControlOnExit(Word.ContentControl ContentControl, ref bool Cancel)
        {
            log.Debug("doc_ContentControlOnExit fired.");
            //Cancel = false;

            Ribbon.buttonEditEnabled   = false;
            Ribbon.buttonDeleteEnabled = false;

            // Visually indicate in the task pane that we're no longer in a mapped control
            m_cmTaskPane.controlTreeView.DeselectNode();
            m_cmTaskPane.PropertiesClear();

            // Note that this event does not fire when a selected control
            // (created by drag) loses focus after user clicks elsewhere.
            // So more would be required to clear the properties in this case.


            // TODO: only do that if not in another content control?
            // Doesn't seem to be necessary


            // Necessary only in the case where the clipboard is used
            //ContentControlStyle.CopyAdjacentFormat(ContentControl);

            Ribbon.myInvalidate();
        }
        private void ManuallySetImage(Document doc, ContentControl cc, Title title)
        {
            cc.LockContents = false;
            PictureContentControl pcc = null;

            foreach (var obj in doc.Controls)
            {
                if (obj is PictureContentControl)
                {
                    var tempPcc = obj as PictureContentControl;
                    if (tempPcc.ID == cc.ID)
                    {
                        pcc = tempPcc;
                        break;
                    }
                }
            }

            if (pcc == null)
            {
                pcc = doc.Controls.AddPictureContentControl(cc, cc.ID);
            }
            var newImage = GetBitmapFromUrl(title.BoxArt.LargeUrl);

            if (newImage != null)
            {
                pcc.Image = newImage;
                pcc.InnerObject.Range.InlineShapes[1].LockAspectRatio = MsoTriState.msoTrue;
                pcc.InnerObject.Range.InlineShapes[1].Width           = 128F;
            }
        }
        public FormFormatDate(Word.ContentControl currentCC)
        {
            InitializeComponent();

            this.currentCC = currentCC;

            if (currentCC.XMLMapping.IsMapped)
            {
                String dateValue = currentCC.XMLMapping.CustomXMLNode.Text;
                if (!DateTime.TryParse(dateValue, out thisDate1)) {
                    thisDate1 = DateTime.Now;
                    }
            }
            else
            {
                thisDate1 = DateTime.Now;
            }

            for (int i = 0; i < formatValues.Length; i++)
            {
                FormatChoice fc = new FormatChoice();
                fc.format = formatValues[i];
                fc.display = thisDate1.ToString(fc.format);
                this.listBoxFormat.Items.Add(fc);
            }

            if (currentCC.DateDisplayFormat != null)
            {
                this.textBoxFormat.Text = currentCC.DateDisplayFormat;
            }
        }
        /// <summary>
        /// Handle Word's AfterAdd event for content controls, to set new controls' placeholder text
        /// </summary>
        /// <param name="ccAdded"></param>
        /// <param name="InUndoRedo"></param>
        private void doc_ContentControlAfterAdd(Word.ContentControl ccAdded, bool InUndoRedo)
        {
            if (!InUndoRedo && m_cmTaskPane.RecentDragDrop)
            {
                ccAdded.Application.ScreenUpdating = false;

                //grab the current text in the node (if any)
                string currentText = null;
                if (ccAdded.XMLMapping.IsMapped)
                {
                    currentText = ccAdded.XMLMapping.CustomXMLNode.Text;
                }

                //set the placeholder text (this has the side effect of clearing out the control's contents)
                ccAdded.SetPlaceholderText(null, null, Utilities.GetPlaceholderText(ccAdded.Type));

                //bring back the original text
                if (currentText != null)
                {
                    ccAdded.Range.Text = currentText;
                }

                ccAdded.Application.ScreenUpdating = true;
                ccAdded.Application.ScreenRefresh();
            }
        }
Beispiel #14
0
        //</Snippet502>

        // PictureContentControl constructor #3: create a PictureContentControl for every
        // native picture control added to the document at run time.
        //<Snippet503>
        void ThisDocument_PictureContentControlAfterAdd(Word.ContentControl NewContentControl, bool InUndoRedo)
        {
            if (NewContentControl.Type == Word.WdContentControlType.wdContentControlPicture)
            {
                this.Controls.AddPictureContentControl(NewContentControl,
                                                       "PictureControl" + NewContentControl.ID);
            }
        }
        //</Snippet302>


        // DropDownListContentControl constructor #3: create a DropDownListContentControl for every
        // native drop down list control added to the document.
        //<Snippet303>
        void ThisDocument_DropDownListContentControlAfterAdd(Word.ContentControl NewContentControl, bool InUndoRedo)
        {
            if (NewContentControl.Type == Word.WdContentControlType.wdContentControlDropdownList)
            {
                this.Controls.AddDropDownListContentControl(NewContentControl,
                                                            "DropDownListControl" + NewContentControl.ID);
            }
        }
        private void ccRemapMenuItem_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.ContentControl selectedCC = ccListView.FocusedItem.Tag as Microsoft.Office.Interop.Word.ContentControl;
            RemapForm remapForm = new RemapForm(selectedCC);

            remapForm.ShowDialog();
            //CustomXMLPart XMLPart = Globals.ThisAddIn.currentDocument.CustomXMLParts.SelectByNamespace
        }
        //</Snippet702>


        // RichTextContentControl constructor #3: create a RichTextContentControl for every
        // native rich text control added to the document.
        //<Snippet703>
        void ThisDocument_RichTextContentControlAfterAdd(Word.ContentControl NewContentControl, bool InUndoRedo)
        {
            if (NewContentControl.Type == Word.WdContentControlType.wdContentControlRichText)
            {
                this.Controls.AddRichTextContentControl(NewContentControl,
                                                        "RichTextControl" + NewContentControl.ID);
            }
        }
        //</Snippet3>


        // BuildingBlockGalleryContentControl constructor #3: create a
        // BuildingBlockGalleryContentControl for every native building block control added to the document.
        //<Snippet4>
        void ThisDocument_BuildingBlockContentControlAfterAdd(Word.ContentControl NewContentControl, bool InUndoRedo)
        {
            if (NewContentControl.Type == Word.WdContentControlType.wdContentControlBuildingBlockGallery)
            {
                this.Controls.AddBuildingBlockGalleryContentControl(NewContentControl,
                                                                    "BuildingBlockControl" + NewContentControl.ID);
            }
        }
        //</Snippet202>

        // DatePickerContentControl constructor #3: create a DatePickerContentControl for every
        // native date control added to the document.
        //<Snippet203>
        void ThisDocument_DatePickerContentControlAfterAdd(Word.ContentControl NewContentControl, bool InUndoRedo)
        {
            if (NewContentControl.Type == Word.WdContentControlType.wdContentControlDate)
            {
                this.Controls.AddDatePickerContentControl(NewContentControl,
                                                          "DatePickerControl" + NewContentControl.ID);
            }
        }
Beispiel #20
0
        //</Snippet102>

        // ComboBoxContentControl constructor #3: create a ComboBoxContentControl for every
        // native combobox control added to the document.
        //<Snippet103>
        void ThisDocument_ComboBoxContentControlAfterAdd(Word.ContentControl NewContentControl, bool InUndoRedo)
        {
            if (NewContentControl.Type == Word.WdContentControlType.wdContentControlComboBox)
            {
                this.Controls.AddComboBoxContentControl(NewContentControl,
                                                        "ComboBoxControl" + NewContentControl.ID);
            }
        }
 /// <summary>
 /// Handle Word's OnEnter event for content controls, to set the selection in the pane (if the option is set).
 /// </summary>
 /// <param name="ccEntered">A ContentControl object specifying the control that was entered.</param>
 private void doc_ContentControlOnEnter(Word.ContentControl ccEntered)
 {
     Debug.WriteLine("Document.ContentControlOnEnter fired.");
     if (ccEntered.XMLMapping.IsMapped && ccEntered.XMLMapping.CustomXMLNode != null)
     {
         m_cmTaskPane.RefreshControls(Controls.ControlMain.ChangeReason.OnEnter, null, null, null, ccEntered.XMLMapping.CustomXMLNode, null);
     }
 }
Beispiel #22
0
        //</Snippet402>

        // GroupContentControl constructor #3: create GroupContentControl objects for every
        // native group controls added to the document.
        //<Snippet403>
        void ThisDocument_GroupContentControlAfterAdd(Word.ContentControl NewContentControl, bool InUndoRedo)
        {
            if (NewContentControl.Type == Word.WdContentControlType.wdContentControlGroup)
            {
                this.Controls.AddGroupContentControl(NewContentControl,
                                                     "GroupControl" + NewContentControl.ID);
            }
        }
 public static bool isCondition(Word.ContentControl cc)
 {
     if // ((cc.Title != null && cc.Title.StartsWith("Condition"))
     (cc.Tag != null && cc.Tag.Contains("od:condition"))
     {
         return(true);
     }
     return(false);
 }
 public static bool isRepeat(Word.ContentControl cc)
 {
     if //((cc.Title != null && cc.Title.StartsWith("Repeat"))
     (cc.Tag != null && cc.Tag.Contains("od:repeat"))
     {
         return(true);
     }
     return(false);
 }
Beispiel #25
0
        private void SetContentControl(string txtTitle, string txtValue)
        {
            Word.ContentControl tmpCtrl = GetContentControl(txtTitle);

            if (tmpCtrl != null)
            {
                tmpCtrl.Range.Text = txtValue;
            }
        }
        public QuestionListHelper(Model model, XPathsPartEntry xppe, questionnaire questionnaire, 
                    Word.ContentControl cc)
        {
            this.model = model;
            this.xppe = xppe;
            this.questionnaire = questionnaire;

            this.cc = cc;
        }
Beispiel #27
0
        private static Word.ContentControl GetFooterContentControl(Word.Document doc, string name)
        {
            Word.ContentControl contentControl = null;
            try
            {
                foreach (Microsoft.Office.Interop.Word.Section wordSection in doc.Sections)
                {
                    foreach (Microsoft.Office.Interop.Word.HeaderFooter wordFooter in wordSection.Footers)
                    {
                        Microsoft.Office.Interop.Word.Range docRange = wordFooter.Range;

                        ContentControls footerControls = docRange.ContentControls;

                        if (footerControls != null)
                        {
                            foreach (Microsoft.Office.Interop.Word.ContentControl control in footerControls)
                            {
                                if (control.Tag.ToUpper().Equals(name.ToUpper()))
                                {
                                    contentControl = control;
                                    break;
                                }
                                if (Marshal.IsComObject(control))
                                {
                                    Marshal.ReleaseComObject(control);
                                }
                            }
                        }
                        if (Marshal.IsComObject(docRange))
                        {
                            Marshal.ReleaseComObject(docRange);
                        }
                        if (Marshal.IsComObject(footerControls))
                        {
                            Marshal.ReleaseComObject(footerControls);
                        }

                        if (Marshal.IsComObject(wordFooter))
                        {
                            Marshal.ReleaseComObject(wordFooter);
                        }
                    }

                    if (Marshal.IsComObject(wordSection))
                    {
                        Marshal.ReleaseComObject(wordSection);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogException(LogLevel.Error, "GetFooterContentControl", ex);
            }
            return(contentControl);
        }
 public static bool isBound(Word.ContentControl cc)
 {
     if //((cc.Title != null && cc.Title.StartsWith("Data"))
     ((cc.Tag != null && cc.Tag.Contains("od:xpath")) ||
      cc.XMLMapping.IsMapped
     )
     {
         return(true);
     }
     return(false);
 }
        private static int countParent(Word.ContentControl ctrl)
        {
            int counter = 0;

            while (ctrl.ParentContentControl != null)
            {
                counter++;
                ctrl = ctrl.ParentContentControl;
            }
            log.Debug("= " + counter);
            return(counter);
        }
Beispiel #30
0
        /// <summary>
        /// Bu metot belgeye içine soru metinler için zengin metin kutucukları konacak
        /// olan bir tablo içeren bir zengin metin kutusu ekler.
        /// </summary>
        public void SoruGrubuEkle()
        {
            // Soru grubu kutusu belge sonuna eklenecek
            object end = this.Content.End - 1;

            Word.ContentControl ctrlGroup = this.ContentControls.Add(
                Word.WdContentControlType.wdContentControlRichText,
                this.Range(ref end, ref end));
            HurTestDataSet.QuestionGroupsRow qgroupRow =
                docDataSet.QuestionGroups.AddQuestionGroupsRow(ctrlGroup.ID, 1, 1);
            // Sorular için bu kutu içinde bir tablo olacak.
            Word.Table tblGroup = this.Tables.Add(ctrlGroup.Range, 1, 2);
            tblGroup.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            tblGroup.Borders.OutsideLineWidth = Word.WdLineWidth.wdLineWidth225pt;
            tblGroup.Borders.OutsideColor     = Word.WdColor.wdColorBlue;
            tblGroup.Borders.InsideLineStyle  = Word.WdLineStyle.wdLineStyleSingle;
            tblGroup.Borders.InsideLineWidth  = Word.WdLineWidth.wdLineWidth025pt;
            tblGroup.Borders.InsideColor      = Word.WdColor.wdColorBlue;
            tblGroup.Columns[1].SetWidth(50, Word.WdRulerStyle.wdAdjustFirstColumn);
            object groupbegin = ctrlGroup.Range.Start;

            this.Range(ref groupbegin, ref groupbegin).InsertBefore("Seçilecek Soru Sayısı: ");
            this.Range(ref groupbegin, ref groupbegin).InsertParagraph();
            Word.Range par1range = ctrlGroup.Range.Paragraphs[1].Range;
            // Soru grubu kutusunda açıklamalar için bir metin kutusu olacak.
            Word.ContentControl ctrlComment = this.ContentControls.Add(
                Word.WdContentControlType.wdContentControlRichText, par1range);
            ctrlComment.SetPlaceholderText(null, null, "Soru grubu açıklamalarını buraya yazın");
            ctrlComment.LockContentControl = true;
            // Soru grubu kutusunda bir de seçilecek soru sayısını belirlemek
            // için bir açılır liste kutusu olacak.
            object par2end = ctrlGroup.Range.Paragraphs[2].Range.End - 1;

            Word.ContentControl cbQuestionCount = this.ContentControls.Add(
                Word.WdContentControlType.wdContentControlComboBox,
                this.Range(ref par2end, ref par2end));
            cbQuestionCount.DropdownListEntries.Add("1", "1", 0);
            cbQuestionCount.SetPlaceholderText(null, null, "Sayı seçin");
            cbQuestionCount.LockContentControl = true;
            // Gruba eklenen ilk boş soru için seçim kutusu konacak.
            Word.ContentControl chkIncludeQuestion = this.ContentControls.Add(
                Word.WdContentControlType.wdContentControlCheckBox,
                tblGroup.Cell(1, 1).Range);
            chkIncludeQuestion.Checked            = true;
            chkIncludeQuestion.LockContentControl = true;
            // Gruba bir boş soru kutusu konacak.
            Word.ContentControl ctrlQuestion = this.ContentControls.Add(
                Word.WdContentControlType.wdContentControlRichText,
                tblGroup.Cell(1, 2).Range);
            docDataSet.Questions.AddQuestionsRow(ctrlQuestion.ID, qgroupRow, chkIncludeQuestion.ID, true, 0);
            ctrlQuestion.SetPlaceholderText(null, null, "Soru metnini buraya yazın");
            ctrlQuestion.LockContentControl = true;
        }
Beispiel #31
0
 internal static Word.ContentControl GetContentControl(Word.Document doc, string name)
 {
     Word.ContentControl contentControl = GetBodyContentControl(doc, name);
     if (contentControl == null)
     {
         contentControl = GetFooterContentControl(doc, name);
     }
     if (contentControl == null)
     {
         contentControl = GetHeaderContentControl(doc, name);
     }
     return(contentControl);
 }
Beispiel #32
0
        /// <summary>
        /// Convert a rich text control to block level, then inject WordML into it.
        /// </summary>
        /// <param name="control"></param>
        public Word.ContentControl blockLevelFlatOPC(Word.ContentControl currentCC, String xml)
        {
            Word.ContentControl cc = convertToBlockLevel(currentCC, false, false);

            object missing = System.Type.Missing;

            cc.Range.InsertXML(xml, ref missing);

            cc.Application.ScreenUpdating = true;  // screen seems to be updating already (Word 2010 x64). bugger.
            cc.Application.ScreenRefresh();

            return(cc);
        }
        public FormConditionBuilder(Word.ContentControl cc, ConditionsPartEntry cpe, condition existingCondition)
        {
            InitializeComponent();

            // NET 4 way; see http://msdn.microsoft.com/en-us/library/microsoft.office.tools.word.extensions.aspx
            FabDocxState fabDocxState = (FabDocxState)Globals.Factory.GetVstoObject(Globals.ThisAddIn.Application.ActiveDocument).Tag;

            // NET 3.5 way, which requires using Microsoft.Office.Tools.Word.Extensions
            //FabDocxState fabDocxState = (FabDocxState)Globals.ThisAddIn.Application.ActiveDocument.GetVstoObject(Globals.Factory).Tag;
            this.model = fabDocxState.model;
            xppe = new XPathsPartEntry(model);

            this.cc = cc;

            this.cpe = cpe;
            this.existingCondition = existingCondition;

            this.questionsPart = model.questionsPart;
            questionnaire qtmp = new questionnaire();
            questionnaire.Deserialize(questionsPart.XML, out qtmp);
            questionnaire = qtmp;

            conditions ctmp = new conditions();
            conditions.Deserialize(model.conditionsPart.XML, out ctmp);
            conditions = ctmp;

            log.Debug("conditions: " + conditions.Serialize());

            this.listBoxGovernor.Items.Add("all");
            this.listBoxGovernor.Items.Add("any");
            this.listBoxGovernor.Items.Add("none");
            this.listBoxGovernor.SelectedItem = "all";

            rowHelper = new Helpers.ConditionsFormRowHelper(model, xppe, questionnaire, cc, this);

            rowHelper.init(this.dataGridView);

            DataGridViewRow row = this.dataGridView.Rows[0];
            rowHelper.populateRow(row, null, null);
        }
        public FormCondition(Word.ContentControl cc, ConditionsPartEntry cpe, condition existingCondition)
        {
            InitializeComponent();

            // NET 4 way; see http://msdn.microsoft.com/en-us/library/microsoft.office.tools.word.extensions.aspx
            FabDocxState fabDocxState = (FabDocxState)Globals.Factory.GetVstoObject(Globals.ThisAddIn.Application.ActiveDocument).Tag;

            // NET 3.5 way, which requires using Microsoft.Office.Tools.Word.Extensions
            //FabDocxState fabDocxState = (FabDocxState)Globals.ThisAddIn.Application.ActiveDocument.GetVstoObject(Globals.Factory).Tag;
            this.model = fabDocxState.model;
            xppe = new XPathsPartEntry(model);

            this.cc = cc;

            this.cpe = cpe;
            this.existingCondition = existingCondition;

            this.questionsPart = model.questionsPart;
            questionnaire = new questionnaire();
            questionnaire.Deserialize(questionsPart.XML, out questionnaire);

            questionListHelper = new Helpers.QuestionListHelperForConditionsForm(model, xppe, questionnaire, cc);
            questionListHelper.listBoxTypeFilter = listBoxTypeFilter;
            questionListHelper.listBoxQuestions = listBoxQuestions;
            questionListHelper.checkBoxScope = checkBoxScope;

            questionListHelper.comboBoxValues = comboBoxValues;
            questionListHelper.listBoxPredicate = listBoxPredicate;

            this.listBoxQuestions.SelectedIndexChanged += new System.EventHandler(questionListHelper.listBoxQuestions_SelectedIndexChanged);
            this.listBoxTypeFilter.SelectedIndexChanged += new System.EventHandler(questionListHelper.listBoxTypeFilter_SelectedIndexChanged);

            question existingQuestion = null;
            string matchResponse = null;
            if (existingCondition != null)
            {
                // Use the question associated with it, to pre-select
                // the correct entries in the dialog.

                // Re-label the window, so user can see what the condition was about
                this.Text = "Editing Condition:   " + cc.Title;

                //List<xpathsXpath> xpaths = ConditionsPartEntry.getXPathsUsedInCondition(existingCondition, xppe);
                List<xpathsXpath> xpaths = new List<xpathsXpath>();
                existingCondition.listXPaths(xpaths, cpe.conditions, xppe.getXPaths());

                if (xpaths.Count > 1)
                {
                    // TODO: use complex conditions editor
                }
                xpathsXpath xpathObj = xpaths[0];

                String xpathVal = xpathObj.dataBinding.xpath;

                if (xpathVal.StartsWith("/"))
                {
                    // simple
                    //System.out.println("question " + xpathObj.getQuestionID()
                    //        + " is in use via boolean condition " + conditionId);

                    existingQuestion = this.questionnaire.getQuestion(xpathObj.questionID);
                    matchResponse = xpathVal;
                }
                else if (xpathVal.Contains("position"))
                {
                    // TODO
                }
                else
                {
                    //System.out.println(xpathVal);

                    String qid = xpathVal.Substring(
                        xpathVal.LastIndexOf("@id") + 5);
                    //						System.out.println("Got qid: " + qid);
                    qid = qid.Substring(0, qid.IndexOf("'"));
                    //						System.out.println("Got qid: " + qid);

                    //System.out.println("question " + qid
                    //        + " is in use via condition " + conditionId);

                    existingQuestion = this.questionnaire.getQuestion(qid);
                    matchResponse = xpathVal;

                }

            }

            questionListHelper.populateTypeFilter(true);

            if (existingQuestion == null)
            {
                // for init, populate with all questions
                questionListHelper.populateQuestions(null);
            }
            else
            {
                // Just show the existing question
                listBoxQuestions.Items.Add(existingQuestion);
            }

            if (this.listBoxQuestions.Items.Count == 0) // Never happens if in a repeat, and nor do we want it to, since user might just want to use "repeat pos" stuff
            {
                // Try including out of scope
                this.checkBoxScope.Checked = true;
                questionListHelper.populateQuestions(null);
                if (this.listBoxQuestions.Items.Count == 0)
                {
                    MessageBox.Show("You can't define a condition until you have set up at least one question. Let's do that now. ");

                    FormQA formQA = new FormQA(cc, false);
                    formQA.ShowDialog();
                    formQA.Dispose();

                    // Refresh these
                    xppe = new XPathsPartEntry(model);
                    questionnaire.Deserialize(questionsPart.XML, out questionnaire);

                    questionListHelper.filterAction();

                    return;
                }
            }
            // value
            question q;
            if (existingQuestion == null)
            {
                // for init, populate with all questions
                q = (question)this.listBoxQuestions.Items[0];
            }
            else
            {
                q = existingQuestion;
            }

            this.listBoxQuestions.SelectedItem = q;
            if (q.response.Item is responseFixed)
            {
                questionListHelper.populateValues((responseFixed)q.response.Item, matchResponse);
            }

            // predicate =
            questionListHelper.populatePredicates(q);  // TODO: set this correctly in editing mode
        }
 void extendedDocument_ContentControlOnExit(Word.ContentControl cc, ref bool Cancel)
 {
     log.Info(".. left cc: " + cc.Title);
     currentCC = null;
     enableQChangeButtons = false;
     myInvalidate();
 }
 private void SetContentControlValue(ContentControl control, string text)
 {
     switch (control.Type)
     {
         case WdContentControlType.wdContentControlRichText:
             control.Range.Text = text;
             break;
         case WdContentControlType.wdContentControlComboBox:
         case WdContentControlType.wdContentControlDropdownList:
             foreach (ContentControlListEntry item in control.DropdownListEntries)
             {
                 if (text == item.Text)
                 {
                     item.Select();
                 }
             }
             break;
     }
 }
Beispiel #37
0
 public Delivery1(Wd.ContentControl control)
 {
     doc = control.Range.Document;
     this.control = control;
 }
        public void RemoveConcept(Word.Document doc,string conceptid)
        {
            if (isTemplate(doc))
            {

                //Remove the handler
                Microsoft.Office.Tools.Word.Document vstoDoc = Globals.Factory.GetVstoObject(doc);
                vstoDoc.ContentControlOnEnter -= new Word.DocumentEvents2_ContentControlOnEnterEventHandler(doc_ContentControlOnEnter);
                //Now step through the doc and update the concept if it matches the one we just updated
                object start = doc.Content.Start;
                object end = doc.Content.End;
                Word.Range r = doc.Range(ref start, ref end);

                //Create an array of concept content controls in the doc - have to copy or we get into problems with the range including the new ones
                //that we created
                Word.ContentControl[] ccs = new Word.ContentControl[r.ContentControls.Count];
                int cnt = 0;
                foreach (Word.ContentControl cc in r.ContentControls)
                {
                    ccs[cnt++] = cc;
                }

                //Now step through all the Contact Controls and update the XML so we get the newest clauses
                foreach (Word.ContentControl cc in ccs)
                {
                    string tag = cc.Tag;
                    if (tag != null && tag != "" && cc.Tag.Contains('|'))
                    {
                        string[] taga = cc.Tag.Split('|');
                        if (taga[0] == "Concept" && Convert.ToString(taga[1]) == conceptid)
                        {

                            //Remove the content control
                            //have to unlock it first
                            cc.LockContents = false;
                            cc.LockContentControl = false;

                            //Also have to unlock any other controls in the range
                            foreach (Word.ContentControl child in cc.Range.ContentControls)
                            {
                                if (child.ID != cc.ID)
                                {
                                    child.LockContents = false;
                                    child.LockContentControl = false;
                                }
                            }

                            cc.Range.Select();
                            Globals.ThisAddIn.Application.Selection.Delete();
                            cc.Delete();

                        }
                    }

                }

                //Add back in the handler
                vstoDoc.ContentControlOnEnter += new Word.DocumentEvents2_ContentControlOnEnterEventHandler(doc_ContentControlOnEnter);
            }
        }
 public PrecedentControl(Wd.ContentControl control)
 {
     this.control = control;
     this.doc = control.Range.Document;
 }
        public void UnlockLockTemplateConcept(Word.Document doc,string conceptid,bool lck)
        {
            //Is it one of ours
            if (isTemplate(doc))
            {
                //Remove the handler
                Microsoft.Office.Tools.Word.Document vstoDoc = Globals.Factory.GetVstoObject(doc);
                vstoDoc.ContentControlOnExit -= new Word.DocumentEvents2_ContentControlOnExitEventHandler(vstoDoc_ContentControlOnExit);

                string templateid = GetDocId(doc);

                //Now step through the doc
                object start = doc.Content.Start;
                object end = doc.Content.End;
                Word.Range r = doc.Range(ref start, ref end);

                Word.ContentControl[] ccs = new Word.ContentControl[r.ContentControls.Count];
                int cnt = 0;
                foreach (Word.ContentControl cc in r.ContentControls)
                {
                    string tag = cc.Tag;
                    if (tag != null && tag != "" && cc.Tag.Contains('|'))
                    {
                        string[] taga = cc.Tag.Split('|');
                        if (taga[0] == "Concept" && Convert.ToString(taga[1]) == conceptid)
                        {

                            cc.LockContents = lck;
                            cc.LockContentControl = true;

                        }
                    }
                    //Add back in the handler
                    vstoDoc.ContentControlOnExit += new Word.DocumentEvents2_ContentControlOnExitEventHandler(vstoDoc_ContentControlOnExit);

                }
            }
        }
        public void UpdateContractTemplatesConcept(Word.Document doc,string conceptid, string clauseid,string xml,string lastmodified)
        {
            if(doc==null) doc = Application.ActiveDocument;
            //Is it one of ours
            if (isTemplate(doc))
            {

                //Remove the handler
                Microsoft.Office.Tools.Word.Document vstoDoc = Globals.Factory.GetVstoObject(doc);
                try
                {
                    vstoDoc.ContentControlOnEnter -= new Word.DocumentEvents2_ContentControlOnEnterEventHandler(doc_ContentControlOnEnter);
                } catch(Exception){

                }

                string templateid = GetDocId(doc);

                //Now step through the doc and update the concept if it matches the one we just updated
                object start = doc.Content.Start;
                object end = doc.Content.End;
                Word.Range r = doc.Range(ref start, ref end);

                //Create an array of concept content controls in the doc - have to copy or we get into problems with the range including the new ones
                //that we created
                Word.ContentControl[] ccs = new Word.ContentControl[r.ContentControls.Count];
                int cnt = 0;
                foreach (Word.ContentControl cc in r.ContentControls)
                {
                    ccs[cnt++] = cc;
                }

                //Now step through all the Contact Controls and update the XML so we get the newest clauses
                foreach (Word.ContentControl cc in ccs)
                {
                    string tag = cc.Tag;
                    if (tag != null && tag != "" && cc.Tag.Contains('|'))
                    {
                        string[] taga = cc.Tag.Split('|');
                        if (taga[0] == "Concept" && Convert.ToString(taga[1]) == conceptid)
                        {

                            // check if we have to do this - when the contract is initially loaded the containters are already
                            // populated so don't update them if not required

                            bool selectedclause = false;
                            if (taga.Length > 3)
                            {
                                if (taga[2] == clauseid && lastmodified == taga[3])
                                {
                                    selectedclause = true;
                                }
                            }

                            if (!selectedclause)
                            {

                                //scratch do to hold the clause
                                Word.Document scratch = Application.Documents.Add(Visible: false);

                                string txt = "";

                                //Get the details of the clause - this would be too chatty when connected to salesforce
                                //store the xml in the tree instead and pass into the function

                                //xml = d.GetClauseXML(clauseid).strRtn;

                                if (xml == "")
                                {
                                    xml = "";
                                    txt = "Sorry! problem clause doesn't exist!";
                                }

                                //Populate the content control with the values from the database
                                //have to unlock it first
                                cc.LockContents = false;
                                cc.LockContentControl = false;

                                //Also have to unlock any other controls in the range
                                foreach (Word.ContentControl child in cc.Range.ContentControls)
                                {
                                    if (child.ID != cc.ID)
                                    {
                                        child.LockContents = false;
                                        child.LockContentControl = false;
                                    }
                                }

                                //OK having lots of problems with large paragraphs inserting into the content
                                //control - had a play manually and it worked when cutting and pasting
                                //*so* get the XML in a sepearate page and then get the formatted text and update
                                //this seems to fix it! need to do some more digging to see if there is a better way
                                Utility.UnlockContentControls(scratch);
                                scratch.Range(scratch.Content.Start, scratch.Content.End).Delete();

                                if (xml != "") scratch.Range().InsertXML(xml);

                                if (xml != "")
                                {
                                    try
                                    {
                                        // delete out what is there
                                        cc.Range.Delete();

                                        // delete out the styles!
                                        cc.Range.set_Style(Word.WdBuiltinStyle.wdStyleNormal);

                                        // delete out the pesky tables
                                        for (int tablesi = cc.Range.Tables.Count; tablesi > 0; tablesi--)
                                        {
                                            cc.Range.Tables[tablesi].Delete();
                                        }

                                        // When we insert into the clause it adds a \r - have to get rid of it
                                        // had a bunch of ways to do it - this seems to work!
                                        Word.Range newr = scratch.Range();
                                        cc.Range.FormattedText = newr.FormattedText;
                                        try{
                                            newr = doc.Range(cc.Range.End-1,cc.Range.End);
                                            if(newr.Characters.Count==1){
                                                if(newr.Characters[1].Text == "\r"){  // Characters starts at 1 - gets me everytime
                                                    newr.Delete();
                                                }
                                            }

                                        } catch(Exception){

                                        }

                                    }
                                    catch (Exception)
                                    {
                                    }

                                    // close the scratch
                                   var docclosescratch = (Microsoft.Office.Interop.Word._Document)scratch;
                                   docclosescratch.Close(false);
                                   System.Runtime.InteropServices.Marshal.ReleaseComObject(docclosescratch);

                                }
                                else
                                {
                                    cc.Range.InsertAfter(txt);
                                }

                                /* DO THIS IN THE SCRATCH NOW! this was causing all sorts of bother
                                //remove any trailing carriage returns

                                for (var i = cc.Range.Characters.Count; i > 0; i--)
                                {
                                    if (i <= cc.Range.Characters.Count)
                                    {
                                        if (cc.Range.Characters[i].Text == "\r")
                                        {
                                            cc.Range.Characters[i].Delete();
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }

                                /*if (cc.Range.Footnotes.Count == 0)
                                {
                                    while (cc.Range.Characters.Last.Text == "\r")
                                    {
                                        cc.Range.Characters.Last.Delete();
                                    }
                                }
                                */

                                // update the tag
                                cc.Tag = "Concept|" + conceptid + "|" + clauseid + "|" + lastmodified;

                                //relock
                                cc.LockContents = true;
                                cc.LockContentControl = true;

                            }
                        }
                    }

                }

                //Add back in the handler
                try
                {
                    vstoDoc.ContentControlOnEnter += new Word.DocumentEvents2_ContentControlOnEnterEventHandler(doc_ContentControlOnEnter);
                }
                catch (Exception)
                {

                }
            }
        }
        //Contract Instance Stuff - might be the same as ContractTemplate
        public void UpdateContractConcept(string conceptid, string clauseid, string xml,string lastmodified, Word.Document doc, Dictionary<string, string> elementValues)
        {
            //Is it one of ours
            if (isContract(doc))
            {
                //Remove the handler
                Microsoft.Office.Tools.Word.Document vstoDoc = Globals.Factory.GetVstoObject(doc);
                vstoDoc.ContentControlOnExit -= new Word.DocumentEvents2_ContentControlOnExitEventHandler(vstoDoc_ContentControlOnExit);

                string contractid = GetDocId(doc);

                //Now step through the doc and update the concept if it matches the one we just updated
                object start = doc.Content.Start;
                object end = doc.Content.End;
                Word.Range r = doc.Range(ref start, ref end);

                //Create an array of concept content controls in the doc - have to copy or we get into problems with the range including the new ones
                //that we created
                Word.ContentControl[] ccs = new Word.ContentControl[r.ContentControls.Count];
                int cnt = 0;
                foreach (Word.ContentControl cc in r.ContentControls)
                {
                    ccs[cnt++] = cc;
                }

                Globals.ThisAddIn.Application.ScreenUpdating = false;

                //scratch do to hold the clause
                Word.Document scratch = Application.Documents.Add(Visible: false);

                //hold the old clauses xml;
                string oldxml = "";

                //Now step through all the Contact Controls and update the XML so we get the newest clauses
                foreach (Word.ContentControl cc in ccs)
                {
                    string tag = cc.Tag;
                    if (tag != null && tag != "" && cc.Tag.Contains('|'))
                    {
                        string[] taga = cc.Tag.Split('|');
                        if (taga[0] == "Concept" && Convert.ToString(taga[1]) == conceptid)
                        {

                            // Get the details of the clause - this would be too chatty when connected to salesforce
                            // store the xml in the tree instead and pass into the function
                            // DataReturn dr = _d.GetClause(clauseid);

                            string txt = "";
                            if (clauseid!="" && xml == "")
                            {
                                xml = "";
                                txt = "Sorry! problem clause doesn't exist!";
                            }

                            if (cc.PlaceholderText != null)
                            {
                                cc.SetPlaceholderText(Text: "");
                            }

                            // Populate the content control with the values from the database
                            // have to unlock it first
                            cc.LockContents = false;
                            cc.LockContentControl = true;

                            //Also have to unlock any other controls in the range
                            foreach (Word.ContentControl child in cc.Range.ContentControls)
                            {
                                if (child.ID != cc.ID)
                                {
                                    child.LockContents = false;
                                    child.LockContentControl = false;
                                }
                            }

                            oldxml = cc.Range.WordOpenXML;

                            // OK having lots of problems with large paragraphs inserting into the content
                            // control - had a play manually and it worked when cutting and pasting
                            // *so* get the XML in a sepearate page and then get the formatted text and update
                            // this seems to fix it! need to do some more digging to see if there is a better way

                            Utility.UnlockContentControls(scratch);
                            scratch.Range(scratch.Content.Start, scratch.Content.End).Delete();
                            if (xml != "") scratch.Range(0).InsertXML(xml);

                            // if clauseid is blank then its a "select none" so do it even though the xml is blank
                            if (clauseid=="" || xml != "")
                            {
                                //cc.Range.InsertXML(xml);

                                //Track changes?
                                if (doc.TrackRevisions)
                                {

                                    // OK - gets more complicated! save the old paragraph to a scratch doc and undo any changes
                                    // then get the new one in another scratch doc - stop tracking changes in the current doc
                                    // do a diff and then insert that in the parra

                                    Word.Document oldclause=Globals.ThisAddIn.Application.Documents.Add(Visible: false);
                                    string oldclausefilename = Utility.SaveTempFile(doc.Name + "-oldclause");
                                    oldclause.Range().InsertXML(oldxml);

                                    // get rid of any changes - have to make it the active doc to do this
                                    oldclause.Activate();
                                    oldclause.RejectAllRevisions();

                                    MakeDropDownElementsText(oldclause);

                                    // Now update the elements of the scratch
                                    Utility.UnlockContentControls(scratch);
                                    UpdateElements(scratch, elementValues);
                                    // Dropdowns don't diff well (they show as changes, so change the content controls to text - they'll get changed back by initiate)
                                    MakeDropDownElementsText(scratch);

                                    // Now run a diff - do it from the old doc rather than a compare so it gives us the redline rather than blue line compare
                                    string scratchfilename = Utility.SaveTempFile(doc.Name + "-newclause");
                                    scratch.SaveAs2(FileName: scratchfilename, FileFormat: Word.WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: Word.WdCompatibilityMode.wdCurrent);
                                    // this is how you do it as a pure compare - Word.Document compare = Application.CompareDocuments(oldclause, scratch,Granularity:Word.WdGranularity.wdGranularityCharLevel);

                                    oldclause.Compare(scratchfilename, CompareTarget: Word.WdCompareTarget.wdCompareTargetCurrent, AddToRecentFiles: false);
                                    oldclause.ActiveWindow.Visible = false;

                                    // Activate the doc - switch of tracking and insert the marked up dif
                                    doc.Activate();
                                    doc.TrackRevisions = false;

                                    // delete out what is there
                                    cc.Range.Delete();

                                    // delete out the styles!
                                    cc.Range.set_Style(Word.WdBuiltinStyle.wdStyleNormal);

                                    // delete out the pesky tables
                                    for (int tablesi = cc.Range.Tables.Count; tablesi > 0; tablesi--)
                                    {
                                        cc.Range.Tables[tablesi].Delete();
                                    }

                                    cc.Range.FormattedText = oldclause.Content.FormattedText;
                                    doc.Activate();
                                    doc.TrackRevisions = true;

                                    var doccloseoldclause = (Microsoft.Office.Interop.Word._Document)oldclause;
                                    doccloseoldclause.Close(false);

                                }
                                else
                                {
                                    try
                                    {
                                        // delete out what is there
                                        cc.Range.Delete();

                                        // delete out the styles!
                                        cc.Range.set_Style(Word.WdBuiltinStyle.wdStyleNormal);

                                        // delete out the pesky tables
                                        for (int tablesi = cc.Range.Tables.Count; tablesi > 0; tablesi--)
                                        {
                                            cc.Range.Tables[tablesi].Delete();
                                        }

                                        Word.Range newr = scratch.Range();
                                        cc.Range.FormattedText = newr.FormattedText;
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }
                            }
                            else
                            {
                                cc.Range.InsertAfter(txt);
                            }

                            // sort out the formatting problems caused by inserting into the container
                            doc.Activate();
                            bool tchanges = doc.TrackRevisions;
                            doc.TrackRevisions = false;

                            // When we insert into the clause it adds a \r - have to get rid of it
                            // had a bunch of ways to do it - this seems to work!
                            try
                            {
                                Word.Range newr = doc.Range(cc.Range.End - 1, cc.Range.End);
                                if (newr.Characters.Count == 1)
                                {
                                    if (newr.Characters[1].Text == "\r")
                                    {  // Characters starts at 1 - gets me everytime
                                       newr.Delete();
                                    }
                                }

                            }
                            catch (Exception)
                            {

                            }

                            doc.TrackRevisions = tchanges;

                            //close the scratch
                            var docclosescratch = (Microsoft.Office.Interop.Word._Document)scratch;
                            docclosescratch.Close(false);
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(docclosescratch);

                            // update the tag
                            cc.Tag = "Concept|" + conceptid + "|" + clauseid + "|" + lastmodified;

                            //relock
                            cc.LockContents = true;
                            cc.LockContentControl = true;
                        }
                    }

                }

                Globals.ThisAddIn.Application.ScreenUpdating = true;

                //Add back in the handler
                vstoDoc.ContentControlOnExit += new Word.DocumentEvents2_ContentControlOnExitEventHandler(vstoDoc_ContentControlOnExit);

            }
        }
        public void UpdateContractTemplatesConceptTag(Word.Document doc, string conceptid, string clauseid, string lastmodified)
        {
            if (doc == null) doc = Application.ActiveDocument;
            //Is it one of ours
            if (isTemplate(doc))
            {

                string templateid = GetDocId(doc);

                //Now step through the doc and update the concept TAG if it matches the one we just updated
                object start = doc.Content.Start;
                object end = doc.Content.End;
                Word.Range r = doc.Range(ref start, ref end);

                //Create an array of concept content controls in the doc - have to copy or we get into problems with the range including the new ones
                //that we created
                Word.ContentControl[] ccs = new Word.ContentControl[r.ContentControls.Count];
                int cnt = 0;
                foreach (Word.ContentControl cc in r.ContentControls)
                {
                    ccs[cnt++] = cc;
                }

                //Now step through all the Contact Controls and update the XML so we get the newest clauses
                foreach (Word.ContentControl cc in ccs)
                {
                    string tag = cc.Tag;
                    if (tag != null && tag != "" && cc.Tag.Contains('|'))
                    {
                        string[] taga = cc.Tag.Split('|');
                        if (taga[0] == "Concept" && Convert.ToString(taga[1]) == conceptid)
                        {
                            // update the tag
                            if (clauseid == "")
                            {
                                cc.Tag = "Concept|" + conceptid;
                            }
                            else
                            {
                                cc.Tag = "Concept|" + conceptid + "|" + clauseid + "|" + lastmodified;
                            }
                        }
                    }

                }
            }
        }
Beispiel #44
0
 public Delivery(Wd.ContentControl control)
 {
     doc = (Wd.Document)control.Parent;
     this.control = control;
 }
 private static void NextLine(ContentControl control, Document doc)
 {
     Selection currSelection = doc.Application.Selection;
     int endOfRange = control.Range.End + 1;
     currSelection.SetRange(endOfRange, endOfRange);
     currSelection.TypeParagraph();
 }
        /*
         * For each question, I need to keep track of the last value
         * it had on a given row.  This I can store in DataGridViewBand.Tag
         * so a Dictionary<Q, object> is OK for this.
          *
          * Actually, the last value seems to be retained. Without looking
          * to see why/how, I don't need to do anything.
         *
         */
        public ConditionsFormRowHelper(Model model, XPathsPartEntry xppe, questionnaire questionnaire, 
                    Word.ContentControl cc, Forms.FormConditionBuilder fcb)
        {
            this.model = model;
            this.xppe = xppe;
            this.questionnaire = questionnaire;
            this.fcb = fcb;

            this.cc = cc;
        }
        public FormRepeat(Office.CustomXMLPart questionsPart,
            Office.CustomXMLPart answersPart,
            Model model,
            Word.ContentControl cc)
        {
            InitializeComponent();

            this.model = model;
            this.cc = cc;

            this.questionsPart = questionsPart;
            questionnaire = new questionnaire();
            questionnaire.Deserialize(questionsPart.XML, out questionnaire);

            this.answersPart = answersPart;

            Office.CustomXMLNodes answers = answersPart.SelectNodes("//oda:repeat");
            foreach (Office.CustomXMLNode answer in answers)
            {
                this.answerID.Add(CustomXMLNodeHelper.getAttribute(answer, "qref")); // ID
            }

            // Suggest ID .. the idea is that
            // the question ID = answer ID.
               // this.ID = generateId();

            xppe = new XPathsPartEntry(model);
            // List of repeat names, for re-use purposes
            // (we need a map from repeat name (shown in the UI) to repeat id,
            //  which is xppe.xpathId).
            // What is it that distinguishes a repeat from any other question?
            // Answer: The fact that the XPath pointing to it ends with oda:row

            // Only show repeats which are in scope (since this repeat is not allowed elsewhere)
            // - if no ancestor repeat, then top level repeats.
            // - if there is an ancestor repeat, then just those which are direct children of it.
            Word.ContentControl rptAncestor = RepeatHelper.getYoungestRepeatAncestor(cc);
            String scope = "/oda:answers";
            if (rptAncestor != null)
            {
                // find its XPath
                scope = xppe.getXPathByID(  (new TagData(rptAncestor.Tag)).getRepeatID() ).dataBinding.xpath;

            }

            repeatNameToIdMap = new Dictionary<string, string>();
            foreach (xpathsXpath xpath in xppe.getXPaths().xpath)
            {
                if (xpath.dataBinding.xpath.EndsWith("oda:row"))
                {
                    if (isRepeatInScope(scope, xpath.dataBinding.xpath)) {
                        // the repeat "name" is its question text.
                        // Get that.
                        question q = questionnaire.getQuestion(xpath.questionID);
                        repeatNameToIdMap.Add(q.text, xpath.id);
                    }
                }
            }
            // Populate the comboBox
            foreach(KeyValuePair<String,String> entry in repeatNameToIdMap)
            {
                this.comboBoxRepeatNames.Items.Add(entry.Key);
            }
        }
        public void UnlockContractConcept(string conceptid,Word.Document doc)
        {
            //Is it one of ours
            if (isContract(doc))
            {
                //Remove the handler
                Microsoft.Office.Tools.Word.Document vstoDoc = Globals.Factory.GetVstoObject(doc);
                vstoDoc.ContentControlOnExit -= new Word.DocumentEvents2_ContentControlOnExitEventHandler(vstoDoc_ContentControlOnExit);

                string contractid = GetDocId(doc);

                //Now step through the doc
                object start = doc.Content.Start;
                object end = doc.Content.End;
                Word.Range r = doc.Range(ref start, ref end);

                Word.ContentControl[] ccs = new Word.ContentControl[r.ContentControls.Count];
                foreach (Word.ContentControl cc in r.ContentControls)
                {
                    string tag = cc.Tag;
                    if (tag != null && tag != "" && cc.Tag.Contains('|'))
                    {
                        string[] taga = cc.Tag.Split('|');
                        if (taga[0] == "Concept" && Convert.ToString(taga[1]) == conceptid)
                        {

                            // unlock the clause
                            cc.LockContents = false;
                            cc.LockContentControl = true;

                            // also have to unlock any other controls in the range
                            foreach (Word.ContentControl child in cc.Range.ContentControls)
                            {
                                if (child.ID != cc.ID)
                                {
                                    child.LockContents = false;
                                    child.LockContentControl = true;
                                }
                            }

                            // update the tag to set the modified to be unlocked so we know to load the clause
                            // from the database
                            cc.Tag = "Concept|" + taga[1].ToString() + "|" + taga[2].ToString() + "|" + "Unlocked";

                        }

                    }
                    //Add back in the handler
                    vstoDoc.ContentControlOnExit += new Word.DocumentEvents2_ContentControlOnExitEventHandler(vstoDoc_ContentControlOnExit);

                }
            }
        }
        public void extendedDocument_ContentControlOnEnter(Word.ContentControl cc)
        {
            /* The on enter / on exit events seem to do what you'd expect,
             * at least in Office 2010:
             *
             * - only the event for the current (ie most deeply nested) cc fires
             * - the exit event for one fires before the enter event for another
             */

            log.Info("Entered cc: " + cc.Title + " of type " + cc.Type);
            currentCC = cc;
            if ( cc.Tag!=null && ((new TagData(cc.Tag)).getXPathID()!=null) ) {
                enableQChangeButtons = true;
            }
            myInvalidate();
        }