Ejemplo n.º 1
0
        public GhostBinding(PalasoDataObject parent,
                            IList <T> targetList,
                            string propertyName,
                            IWritingSystemDefinition writingSystem,
                            IWeSayTextBox textBoxTarget)
        {
            _parent     = parent;
            _listTarget = targetList;
            //           _listTarget.ListChanged +=new ListChangedEventHandler(_listTarget_ListChanged);
            _propertyName  = propertyName;
            _writingSystem = writingSystem;

            _textBoxTarget          = (Control)textBoxTarget;
            _textBoxTarget.KeyDown += _textBoxTarget_KeyDown;
            // Lost Focus doesn't seem to fire for the GeckoBox so added leaving
            _textBoxTarget.LostFocus       += _textBoxTarget_LostFocus;
            _textBoxTarget.Leave           += _textBoxTarget_LostFocus;
            _textBoxTarget.Enter           += OnTextBoxEntered;
            _textBoxTarget.HandleDestroyed += _textBoxTarget_HandleDestroyed;
            _textBoxTarget.Disposed        += _textBoxTarget_Disposed;
            if (_textBoxTarget is IWeSayTextBox)
            {
                ((IWeSayTextBox)_textBoxTarget).UserLostFocus += _textBoxTarget_LostFocus;
                ((IWeSayTextBox)_textBoxTarget).UserGotFocus  += OnTextBoxEntered;
            }
        }
Ejemplo n.º 2
0
        public int AddGhost(PalasoDataObject parent, IList <LexSense> list, bool isHeading, int insertAtRow)
        {
            string label = GetLabelForMeaning(list.Count);

            if (GlossMeaningField)
            {
                return(MakeGhostWidget <LexSense>(parent,
                                                  list,
                                                  LexSense.WellKnownProperties.Gloss,
                                                  label,
                                                  "Gloss",
                                                  isHeading,
                                                  insertAtRow));
            }
            else
            {
                return(MakeGhostWidget <LexSense>(parent,
                                                  list,
                                                  LexSense.WellKnownProperties.Definition,
                                                  label,
                                                  "Definition",
                                                  isHeading,
                                                  insertAtRow));
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Create an appropriate LexSenseLayouter for a new LexSense created from a ghost,
        /// and insert it at the right place in the Layouter tree.
        /// </summary>
        protected override Layouter CreateAndInsertNewLayouter(int row, PalasoDataObject wsdo)
        {
            Debug.Assert(ParentLayouter is LexEntryLayouter);
            var lexEntryLayouter = ParentLayouter as LexEntryLayouter;
            var newLayouter      = new LexSenseLayouter(DetailList, row, ActiveViewTemplate, RecordListManager,
                                                        _serviceProvider, wsdo as LexSense)
            {
                ShowNormallyHiddenFields = ShowNormallyHiddenFields,
                Deletable      = lexEntryLayouter.SensesAreDeletable,
                ParentLayouter = ParentLayouter
            };

            newLayouter.DeleteClicked += lexEntryLayouter.OnSenseDeleteClicked;
            var idx = ParentLayouter.ChildLayouts.IndexOf(this);

            if (idx >= 0)
            {
                ParentLayouter.ChildLayouts.Insert(idx, newLayouter);
            }
            else
            {
                ParentLayouter.ChildLayouts.Add(newLayouter);
            }
            return(newLayouter);
        }
Ejemplo n.º 4
0
        protected int AddCustomFields(PalasoDataObject target, int insertAtRow)
        {
            int rowCount = 0;

            foreach (Field customField in ActiveViewTemplate.GetCustomFields(target.GetType().Name))
            {
#if GlossMeaning
#else
                if (customField.FieldName == LexSense.WellKnownProperties.Definition)
                {
                    continue;                     //already put this in next to "Meaning"
                }
#endif
                rowCount = AddOneCustomField(target,
                                             customField,
                                             insertAtRow + rowCount /*changed feb 2008*/,
                                             rowCount);
            }

            //grab any basetype class (to just one level). E.g., 'Note'
            foreach (Field customField in
                     ActiveViewTemplate.GetCustomFields(target.GetType().BaseType.Name))
            {
                if (target is LexExampleSentence &&
                    customField.FieldName == PalasoDataObject.WellKnownProperties.Note)
                {
                    continue;                     //note actually isn't allowed at the moment
                }
                rowCount = AddOneCustomField(target,
                                             customField,
                                             insertAtRow + rowCount /*changed feb 2008*/,
                                             rowCount);
            }
            return(rowCount);
        }
Ejemplo n.º 5
0
 protected Layouter(DetailList table,
                    int beginningRow,
                    ViewTemplate viewTemplate,
                    LexEntryRepository lexEntryRepository,
                    IServiceProvider serviceProvider,
                    PalasoDataObject pdoToLayout)
 {
     if (table == null)
     {
         throw new ArgumentNullException("table");
     }
     if (viewTemplate == null)
     {
         throw new ArgumentNullException("viewTemplate");
     }
     PdoToLayout         = pdoToLayout;
     FirstRow            = beginningRow;
     _detailList         = table;
     _viewTemplate       = viewTemplate;
     _lexEntryRepository = lexEntryRepository;
     _serviceProvider    = serviceProvider;
     //Set up the space for the delete icon
     _deleteButton.Click  += OnDeleteClicked;
     _deleteButton.Active  = false;
     _deleteButton.Visible = false;
     _deleteButton.ToolTip = StringCatalog.Get("Delete Meaning");
     DetailList.Controls.Add(_deleteButton, 2, beginningRow);
     DetailList.MouseEnteredBounds += OnMouseEnteredBounds;
     DetailList.MouseLeftBounds    += OnMouseLeftBounds;
     ChildLayouts       = new List <Layouter>();
     _glossMeaningField = null;
 }
Ejemplo n.º 6
0
        /// <summary>
        /// NB here is now a misleading name... what we really mean is "is ready to be filled in".
        /// </summary>
        private bool IsMissingCustomField(PalasoDataObject palasoData)
        {
            var content = palasoData.GetProperty <IPalasoDataObjectProperty>(Field.FieldName);

            if (content == null)
            {
                if (IsSkipped(palasoData, Field.FieldName))
                {
                    return(false);
                }

                //	WS-33978 situation: when some writing system is required don't flag it if the entire field is missing
                if (_writingSystemsWhichAreRequired.Length > 0)
                {
                    return(false);
                }
                return(true);
            }
            if (Field.FieldName == "POS")
            {
                if (IsPosUnknown(palasoData))
                {
                    return(true);
                }
            }
            return(IsMissingData(content));
        }
Ejemplo n.º 7
0
        private static Control MakeOptionCollectionWidget(PalasoDataObject target, Field field)
        {
            OptionsList         availableOptions = WeSayWordsProject.Project.GetOptionsList(field, false);
            OptionRefCollection refsOfChoices    =
                target.GetOrCreateProperty <OptionRefCollection>(field.FieldName);
            IList <IWritingSystemDefinition> writingSystems =
                BasilProject.Project.WritingSystemsFromIds(field.WritingSystemIds);
            IChoiceSystemAdaptor <Option, string, OptionRef> displayAdaptor;

            if (field.FieldName == LexSense.WellKnownProperties.SemanticDomainDdp4)
            {
                displayAdaptor = new DdpOptionDisplayAdaptor(availableOptions, field.WritingSystemIds[0]);
            }
            else
            {
                displayAdaptor = new OptionDisplayAdaptor(availableOptions, field.WritingSystemIds[0]);
            }


            ReferenceCollectionEditor <Option, string, OptionRef> control =
                new ReferenceCollectionEditor <Option, string, OptionRef>(refsOfChoices.Members,
                                                                          availableOptions.
                                                                          Options,
                                                                          writingSystems,
                                                                          field.Visibility,
                                                                          displayAdaptor,
                                                                          WeSayWordsProject.Project.ServiceLocator);

            control.AlternateEmptinessHelper = refsOfChoices;
            return(control);
        }
Ejemplo n.º 8
0
        protected virtual void OnGhostBindingLayoutNeeded <T>(GhostBinding <T> sender,
                                                              IList <T> list,
                                                              int index,
                                                              MultiTextControl previouslyGhostedControlToReuse,
                                                              bool doGoToNextField,
                                                              EventArgs args)
            where T : PalasoDataObject, new()
        {
            DetailList.SuspendLayout();
            var position = _detailList.GetCellPosition(sender.ReferenceControl);
            var rowIndex = position.Row;

            _previouslyGhostedControlToReuse = previouslyGhostedControlToReuse;
            PdoToLayout = list[index];
            AddWidgetsAfterGhostTrigger(PdoToLayout, sender.ReferenceControl, doGoToNextField);
            if (GhostRequestedLayout != null)
            {
                GhostRequestedLayout(this, new EventArgs());
            }
            DetailList.ResumeLayout();
            if (doGoToNextField)
            {
                _detailList.MoveInsertionPoint(rowIndex + 1);
            }
            else
            {
                _detailList.MoveInsertionPoint(rowIndex);
            }
            // For Linux/Mono, merely resuming layout and refreshing doesn't work.
            ForceLayoutAndRefresh();
        }
Ejemplo n.º 9
0
 private Control MakeRelationWidget(PalasoDataObject target, LexRelationType type, Field field)
 {
     return(RelationController.CreateWidget(target,
                                            type,
                                            field,
                                            _lexEntryRepository,
                                            _detailList.OnBinding_ChangeOfWhichItemIsInFocus));
 }
Ejemplo n.º 10
0
 public LexSense(PalasoDataObject parent) : base(parent)
 {
     //   _gloss = new SenseGlossMultiText(this);
     _exampleSentences = new BindingList <LexExampleSentence>();
     _notes            = new BindingList <LexNote>();
     _reversals        = new BindingList <LexReversal>();
     WireUpEvents();
 }
Ejemplo n.º 11
0
        private static void AssertPropertyHasExpectedMultiText(PalasoDataObject dataObject,
                                                               string name)
        {
            //must match what is created by MakeBasicLiftMultiText()
            MultiText mt = dataObject.GetProperty <MultiText>(name);

            Assert.AreEqual(2, mt.Forms.Length);
            Assert.AreEqual("dos", mt["ws-two"]);
        }
Ejemplo n.º 12
0
        //
        //        public LexRelation()
        //        {
        //        }

        public LexRelation(string fieldId, string targetId, PalasoDataObject parent)
        {
            _fieldId  = fieldId;
            _targetId = targetId ?? string.Empty;
            _parent   = parent;

            Traits = new List <LexTrait>();
            Fields = new List <LexField>();
        }
Ejemplo n.º 13
0
 private void WriteCustomProperties(PalasoDataObject item,
                                    ICollection <string> propertiesAlreadyOutput)
 {
     foreach (KeyValuePair <string, IPalasoDataObjectProperty> pair in item.Properties)
     {
         if (propertiesAlreadyOutput.Contains(pair.Key))
         {
             continue;
         }
         if (!ShouldOutputProperty(pair.Key))
         {
             continue;
         }
         if (pair.Value is EmbeddedXmlCollection)
         {
             WriteEmbeddedXmlCollection(pair.Value as EmbeddedXmlCollection);
             continue;
         }
         if (pair.Value is MultiText)
         {
             WriteCustomMultiTextField(pair.Key, pair.Value as MultiText);
             continue;
         }
         if (pair.Value is OptionRef)
         {
             WriteOptionRef(pair.Key, pair.Value as OptionRef);
             continue;
         }
         if (pair.Value is OptionRefCollection)
         {
             WriteOptionRefCollection(pair.Key, pair.Value as OptionRefCollection);
             continue;
         }
         if (pair.Value is LexRelationCollection)
         {
             WriteRelationCollection(pair.Key, pair.Value as LexRelationCollection);
             continue;
         }
         if (pair.Value is FlagState)
         {
             WriteFlagState(pair.Key, pair.Value as FlagState);
             continue;
         }
         PictureRef pictureRef = pair.Value as PictureRef;
         if (pictureRef != null)
         {
             WriteIllustrationElement(pictureRef);
             continue;
         }
         throw new ApplicationException(
                   string.Format(
                       "The LIFT exporter was surprised to find a property '{0}' of type: {1}",
                       pair.Key,
                       pair.Value.GetType()));
     }
 }
Ejemplo n.º 14
0
        public LexExampleSentence(PalasoDataObject parent) : base(parent)
        {
            var sentence = GetOrCreateProperty <MultiText>(WellKnownProperties.ExampleSentence);

            sentence.Parent = this;
            var translation = GetOrCreateProperty <MultiText>(WellKnownProperties.Translation);

            translation.Parent = this;
            WireUpEvents();
        }
Ejemplo n.º 15
0
        private static LexRelation AddRelation(PalasoDataObject source,
                                               string fieldName,
                                               string targetId)
        {
            LexRelationCollection relationColection =
                source.GetOrCreateProperty <LexRelationCollection>(fieldName);

            LexRelation relation = new LexRelation(fieldName, targetId, source);

            relationColection.Relations.Add(relation);
            return(relation);
        }
Ejemplo n.º 16
0
        public void Note_HasTrait_TraitRoundTripped()
        {
#if notyet
            TestTraitRoundTripped("//entry/note",
                                  (e, traits) =>
            {
                PalasoDataObject note = _builder.MergeInNote(e, "color",
                                                             new LiftMultiText("v", "hello world"), traits);
                traits.ForEach(t => _builder.MergeInTrait(note, t));
            });
#endif
        }
Ejemplo n.º 17
0
        protected Control MakeCheckBoxWidget(PalasoDataObject target, Field field)
        {
            FlagState boxState = target.GetOrCreateProperty <FlagState>(field.FieldName);

            CheckBoxControl control = new CheckBoxControl(boxState.Value,
                                                          field.DisplayName,
                                                          field.FieldName);
            SimpleBinding <bool> binding = new SimpleBinding <bool>(boxState, control);

            binding.CurrentItemChanged += _detailList.OnBinding_ChangeOfWhichItemIsInFocus;
            return(control);
        }
Ejemplo n.º 18
0
        internal override int AddWidgets(PalasoDataObject wsdo, int insertAtRow)
        {
            LexExampleSentence example = (LexExampleSentence)wsdo;

            FirstRow = insertAtRow;

            DetailList.SuspendLayout();
            int rowCount = 0;

            try
            {
                Field field =
                    ActiveViewTemplate.GetField(Field.FieldNames.ExampleSentence.ToString());
                if (field != null && field.GetDoShow(example.Sentence, ShowNormallyHiddenFields))
                {
                    Control control = MakeBoundControl(example.Sentence, field);
                    DetailList.AddWidgetRow(
                        StringCatalog.Get("~Example",
                                          "This is the field containing an example sentence of a sense of a word."),
                        false,
                        control,
                        insertAtRow,
                        false);
                    ++rowCount;
                    insertAtRow = DetailList.GetRow(control);
                }

                field = ActiveViewTemplate.GetField(Field.FieldNames.ExampleTranslation.ToString());
                if (field != null && field.GetDoShow(example.Translation, ShowNormallyHiddenFields))
                {
                    Control entry = MakeBoundControl(example.Translation, field);
                    DetailList.AddWidgetRow(
                        StringCatalog.Get("~Translation",
                                          "This is the field for putting in a translation of an example sentence."),
                        false,
                        entry,
                        insertAtRow + rowCount,
                        false);
                    ++rowCount;
                }

                rowCount += AddCustomFields(example, insertAtRow + rowCount);
            }
            catch (ConfigurationException e)
            {
                ErrorReport.NotifyUserOfProblem(e.Message);
            }

            DetailList.ResumeLayout(false);
            LastRow = insertAtRow + rowCount - 1;               // want index of last row owned, not a limit value
            return(rowCount);
        }
Ejemplo n.º 19
0
        public void MergeInNote_NoteHasTypeOtherThanGeneral_AllGoesToRoundTripResidue()
        {
            LexEntry e = MakeSimpleEntry();

            _builder.MergeInNote(e, "red", MakeBasicLiftMultiText(), "<pretendXmlOfNote/>");
            MultiText mt = e.GetProperty <MultiText>(PalasoDataObject.WellKnownProperties.Note);

            Assert.IsNull(mt);
            var residue = e.GetProperty <EmbeddedXmlCollection>(PalasoDataObject.GetEmbeddedXmlNameForProperty(PalasoDataObject.WellKnownProperties.Note));

            Assert.AreEqual(1, residue.Values.Count);
            Assert.AreEqual("<pretendXmlOfNote/>", residue.Values[0]);
        }
Ejemplo n.º 20
0
 private void WriteWellKnownCustomMultiText(PalasoDataObject item,
                                            string property,
                                            ICollection <string> propertiesAlreadyOutput)
 {
     if (ShouldOutputProperty(property))
     {
         MultiText m = item.GetProperty <MultiText>(property);
         if (WriteMultiWithWrapperIfNonEmpty(property, property, m))
         {
             propertiesAlreadyOutput.Add(property);
         }
     }
 }
Ejemplo n.º 21
0
        private RelationController(PalasoDataObject relationParent,
                                   LexRelationType relationType,
                                   Field field,
                                   LexEntryRepository lexEntryRepository,
                                   EventHandler <CurrentItemEventArgs> focus)
        {
            _relationParent     = relationParent;
            _relationType       = relationType;
            _field              = field;
            _lexEntryRepository = lexEntryRepository;
            _focusDelegate      = focus;

            MakeControl();
        }
Ejemplo n.º 22
0
        protected int MakeGhostWidget <T>(PalasoDataObject parent,
                                          IList <T> list,
                                          string fieldName,
                                          string label,
                                          string propertyName,
                                          bool isHeading,
                                          int row) where T : PalasoDataObject, new()
        {
            Field field = ActiveViewTemplate.GetField(fieldName);

            if (field != null && field.Enabled &&
                field.Visibility == CommonEnumerations.VisibilitySetting.Visible)
            {
                DetailList.SuspendLayout();
                MultiTextControl m = new MultiTextControl(field.WritingSystemIds,
                                                          new MultiText(),
                                                          fieldName + "_ghost",
                                                          false,
                                                          BasilProject.Project.WritingSystems,
                                                          field.Visibility,
                                                          field.IsSpellCheckingEnabled, false, _serviceProvider);
                if (_columnWidths != null && _columnWidths.Length == 3)
                {
                    m.Width = _columnWidths[1];
                }

                Control refWidget = DetailList.AddWidgetRow(label,
                                                            isHeading,
                                                            m,
                                                            row,
                                                            true);

                foreach (IControlThatKnowsWritingSystem box in m.TextBoxes)
                {
                    var tb = box as IWeSayTextBox;
                    if (tb != null)
                    {
                        GhostBinding <T> g = MakeGhostBinding(parent, list, propertyName, box.WritingSystem, tb);
                        g.ReferenceControl = refWidget;
                    }
                }
                DetailList.ResumeLayout(false);
                return(1);
            }
            else
            {
                return(0);                //didn't add a row
            }
        }
Ejemplo n.º 23
0
        protected Control MakeOptionWidget(PalasoDataObject target, Field field)
        {
            OptionRef   optionRefTarget = target.GetOrCreateProperty <OptionRef>(field.FieldName);
            OptionsList list            = WeSayWordsProject.Project.GetOptionsList(field, false);
            IWritingSystemDefinition preferredWritingSystem = _viewTemplate.GetDefaultWritingSystemForField(field.FieldName);
            SingleOptionControl      control = new SingleOptionControl(optionRefTarget,
                                                                       list,
                                                                       field.FieldName,
                                                                       preferredWritingSystem,
                                                                       WeSayWordsProject.Project.ServiceLocator);
            SimpleBinding <string> binding = new SimpleBinding <string>(optionRefTarget, control);

            binding.CurrentItemChanged += _detailList.OnBinding_ChangeOfWhichItemIsInFocus;
            return(control);
        }
Ejemplo n.º 24
0
        public int AddGhost(PalasoDataObject parent, IList <LexSense> list, bool isHeading, int insertAtRow)
        {
            string label = GetLabelForMeaning(list.Count);

#if GlossMeaning
            return(MakeGhostWidget <LexSense>(list, insertAtRow, Field.FieldNames.SenseGloss.ToString(), label, "Gloss", isHeading, insertAtRow));
#else
            return(MakeGhostWidget <LexSense>(parent,
                                              list,
                                              LexSense.WellKnownProperties.Definition,
                                              label,
                                              "Definition",
                                              isHeading,
                                              insertAtRow));
#endif
        }
Ejemplo n.º 25
0
        protected override Control MakePictureWidget(PalasoDataObject target, Field field, DetailList detailList)
        {
            PictureRef pictureRef = target.GetOrCreateProperty <PictureRef>(field.FieldName);

            PictureControl control = _serviceProvider.GetService(typeof(PictureControl)) as PictureControl;

            control.SearchTermProvider = new SenseSearchTermProvider(target as LexSense);
            if (!String.IsNullOrEmpty(pictureRef.Value))
            {
                control.Value = pictureRef.Value;
            }
            SimpleBinding <string> binding = new SimpleBinding <string>(pictureRef, control);

            binding.CurrentItemChanged += detailList.OnBinding_ChangeOfWhichItemIsInFocus;
            return(control);
        }
Ejemplo n.º 26
0
        protected GhostBinding <T> MakeGhostBinding <T>(PalasoDataObject parent, IList <T> list,
                                                        string ghostPropertyName,
                                                        IWritingSystemDefinition writingSystem,
                                                        IWeSayTextBox entry)
            where T : PalasoDataObject, new()
        {
            GhostBinding <T> binding = new GhostBinding <T>(parent,
                                                            list,
                                                            ghostPropertyName,
                                                            writingSystem,
                                                            entry);

            binding.LayoutNeededAfterMadeReal += OnGhostBindingLayoutNeeded;
            binding.CurrentItemChanged        += _detailList.OnBinding_ChangeOfWhichItemIsInFocus;
            return(binding);
        }
Ejemplo n.º 27
0
 private bool IsMissingLexSenseField(PalasoDataObject sense)
 {
     if (!Field.IsBuiltInViaCode)
     {
         return(IsMissingCustomField(sense));
     }
     //                if(this._field.FieldName == LexSense.WellKnownProperties.Gloss)
     //                {
     //                    return IsMissingWritingSystem(sense.Gloss);
     //                }
     //                else
     {
         Debug.Fail("unknown FieldName");
         return(false);
     }
 }
Ejemplo n.º 28
0
        public void MergeInNote_NoType_AfterFirstTheyGoesToRoundTripResidue()
        {
            LexEntry e = MakeSimpleEntry();

            _builder.MergeInNote(e, string.Empty, MakeBasicLiftMultiText("first"), "pretend xml one");
            _builder.MergeInNote(e, string.Empty, MakeBasicLiftMultiText("second"), "<pretend xml two/>");
            _builder.MergeInNote(e, string.Empty, MakeBasicLiftMultiText("third"), "<pretend xml three/>");

            MultiText mt = e.GetProperty <MultiText>(PalasoDataObject.WellKnownProperties.Note);

            Assert.AreEqual("first", mt["ws-one"]);

            var residue = e.GetProperty <EmbeddedXmlCollection>(PalasoDataObject.GetEmbeddedXmlNameForProperty(PalasoDataObject.WellKnownProperties.Note));

            Assert.AreEqual(2, residue.Values.Count);
            Assert.AreEqual("<pretend xml two/>", residue.Values[0]);
            Assert.AreEqual("<pretend xml three/>", residue.Values[1]);
        }
Ejemplo n.º 29
0
        public static Control CreateWidget(PalasoDataObject relationParent,
                                           LexRelationType relationType,
                                           Field field,
                                           LexEntryRepository lexEntryRepository,
                                           EventHandler <CurrentItemEventArgs> focus)
        {
            if (field.WritingSystemIds.Count == 0)
            {
                throw new ConfigurationException("The field {0} has no input systems enabled.", field.FieldName);
            }
            var controller = new RelationController(relationParent,
                                                    relationType,
                                                    field,
                                                    lexEntryRepository,
                                                    focus);

            return(controller.Control);
        }
Ejemplo n.º 30
0
        private static string RenderGhostedField(PalasoDataObject parent,
                                                 string property,
                                                 CurrentItemEventArgs currentItem,
                                                 int?number)
        {
            string rtf = string.Empty;

            if (currentItem != null && property == currentItem.PropertyName && parent == currentItem.Parent)
            {
                //REVIEW: is a ws switch needed for a blank? rtf += SwitchToWritingSystem(WritingSystems.AnalysisWritingSystemDefault.Id);
                if (number != null)
                {
                    rtf += number.ToString();
                }
                rtf += RenderBlankPosition();
            }
            return(rtf);
        }
		private static void AssertPropertyHasExpectedMultiText(PalasoDataObject dataObject,
															   string name)
		{
			//must match what is created by MakeBasicLiftMultiText()
			MultiText mt = dataObject.GetProperty<MultiText>(name);
			Assert.AreEqual(2, mt.Forms.Length);
			Assert.AreEqual("dos", mt["ws-two"]);
		}
Ejemplo n.º 32
0
		public TestClass(PalasoDataObject parent): base(parent) {}
Ejemplo n.º 33
0
		public static bool TryMergeProperties(PalasoDataObject targetItem, PalasoDataObject incomingItem, string[] traitsWithMultiplicity, string itemDescriptionForMessage, IProgress progress)
		{
			var knownMergableOptionCollectionTraits = new[] { LexSense.WellKnownProperties.SemanticDomainDdp4 };
			if (traitsWithMultiplicity == null)
			{
				traitsWithMultiplicity = new string[0];
			}

			foreach (var incomingProperty in incomingItem.Properties)
			{
				if (targetItem.Properties.Any(p => p.Key == incomingProperty.Key))
				{
					var targetProperty = targetItem.Properties.First(p => p.Key == incomingProperty.Key);

					if (incomingProperty.Value is MultiText && targetProperty.Value is MultiText &&
						((MultiText)incomingProperty.Value).CanBeUnifiedWith(((MultiText)targetProperty.Value)))
					{
						continue;
					}

				   //NB: Some of the complexity here is that we can't really tell from here if what the multiplicity is of the <trait>, unless we
					//recognize the trait (e.d. semantic domains) or we see that one side has > 1 values already.

					 if (incomingProperty.Value is OptionRefCollection && targetProperty.Value is OptionRefCollection)
					{
						var targetCollection = ((OptionRefCollection)targetProperty.Value);
						var incomingCollection = ((OptionRefCollection)incomingProperty.Value);
						var clearlyHasMultiplicityGreaterThan1 = (incomingCollection.Count > 1 || targetCollection.Count > 1);
						var atLeastOneSideIsEmpty = (incomingCollection.Count == 0 || targetCollection.Count == 0);
						if (knownMergableOptionCollectionTraits.Contains(targetProperty.Key)
							|| traitsWithMultiplicity.Contains(targetProperty.Key)
							|| clearlyHasMultiplicityGreaterThan1
							|| atLeastOneSideIsEmpty)
						{
							var mergeSuccess = targetCollection.MergeByKey(
								(OptionRefCollection) incomingProperty.Value);
							if (mergeSuccess)
								continue;
							else
							{
								progress.WriteMessageWithColor("gray",
															   "Attempting to merge " + itemDescriptionForMessage +
															   ", but could not due to inability to merge contents of the property '{0}' (possibly due to incompatible embedded xml).",
															   targetProperty.Key, targetProperty.Value,
															   incomingProperty.Value);
								return false;
							}
						}
						else
							//at this point, we know that both sides have a count of 1, a common thing for a <trait> with multiplicity of 1
							if (((OptionRef) incomingCollection.Members[0]).Key == ((OptionRef) targetCollection.Members[0]).Key &&
								((OptionRef) incomingCollection.Members[0]).Value == ((OptionRef) targetCollection.Members[0]).Value)
							{
								continue; //same, single value
							}
					}

					if (incomingProperty.Value is OptionRef && targetProperty.Value is OptionRef &&
						(((OptionRef)incomingProperty.Value).Value == ((OptionRef)targetProperty.Value).Value))
					{
						continue;
					}

					if (targetProperty.Value != incomingProperty.Value)
					{
						progress.WriteMessageWithColor("gray","Attempting to merge "+itemDescriptionForMessage+", but could not because of the property '{0}' ('{1}' vs. '{2}')", targetProperty.Key, targetProperty.Value, incomingProperty.Value);
						return false; //clashing properties
					}
				}
			}

			//at this point, we're committed

			//I (JH) once saw this foreach break saying the collection was modified, so I'm makinkg this safeProperties thing
			var safeProperties = new List<KeyValuePair<string, IPalasoDataObjectProperty>>(incomingItem.Properties.ToArray());
			foreach (var pair in safeProperties)
			{
				var match = targetItem.Properties.FirstOrDefault(p => p.Key == pair.Key);

				if (match.Key != default(KeyValuePair<string, object>).Key &&
					pair.Value is MultiText && match.Value is MultiText &&
					((MultiText)pair.Value).CanBeUnifiedWith(((MultiText)match.Value)))
				{
					((MultiText)match.Value).MergeIn(((MultiText)pair.Value));
				}
				else
				{
					targetItem.MergeProperty(pair);
				}
			}
			return true;
		}