コード例 #1
0
        /// <summary>
        /// The weather list is used, so convert it to a custom (unowned) list, create a new
        /// custom field for RnGenericRec elements, and convert any Weather elements to that
        /// new custom field.
        /// </summary>
        private void ConvertWeatherToCustomListAndField(IDomainObjectDTORepository repoDTO)
        {
            // Change the Weather list to being unowned.
            DomainObjectDTO dtoLP = null;

            foreach (var dto in repoDTO.AllInstancesWithSubclasses("LangProject"))
            {
                dtoLP = dto;
                break;
            }
            string sWeatherListGuid = RemoveWeatherConditionsElement(dtoLP).ToLowerInvariant();

            repoDTO.Update(dtoLP);
            DomainObjectDTO dtoWeatherList = null;

            foreach (var dto in repoDTO.AllInstancesWithSubclasses("CmPossibilityList"))
            {
                if (dto.Guid.ToLowerInvariant() == sWeatherListGuid)
                {
                    dtoWeatherList = dto;
                    break;
                }
            }
            dtoWeatherList.Xml = RemoveOwnerGuid(dtoWeatherList.Xml);
            repoDTO.Update(dtoWeatherList);

            // Create the custom field.
            string fieldName = "Weather";

            while (repoDTO.IsFieldNameUsed("RnGenericRec", fieldName))
            {
                fieldName = fieldName + "A";
            }
            repoDTO.CreateCustomField("RnGenericRec", fieldName, SIL.CoreImpl.CellarPropertyType.ReferenceCollection,
                                      CmPossibilityTags.kClassId, "originally a standard part of Data Notebook records",
                                      WritingSystemServices.kwsAnals, new Guid(sWeatherListGuid));

            string customStart = String.Format("<Custom name=\"{0}\">", fieldName);

            // Remove any empty Weather elements in the RnGenericRec objects, and convert
            // nonempty ones to custom elements.
            foreach (var dto in repoDTO.AllInstancesWithSubclasses("RnGenericRec"))
            {
                string sXml = dto.Xml;
                int    idx  = sXml.IndexOf("<Weather");
                if (idx > 0)
                {
                    string sXmlT = RemoveEmptyWeather(sXml, idx);
                    if (sXmlT == sXml)
                    {
                        sXmlT = sXml.Replace("<Weather>", customStart);
                        sXmlT = sXmlT.Replace("</Weather>", "</Custom>");
                    }
                    dto.Xml = sXmlT;
                    repoDTO.Update(dto);
                }
            }
        }
コード例 #2
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Changes all StFootnotes to ScrFootnotes
        /// </summary>
        /// <param name="domainObjectDtoRepository">
        /// Repository of all CmObject DTOs available for one migration step.
        /// </param>
        /// <remarks>
        /// The method must add/remove/update the DTOs to the repository,
        /// as it adds/removes objects as part of it work.
        ///
        /// Implementors of this interface should ensure the Repository's
        /// starting model version number is correct for the step.
        /// Implementors must also increment the Repository's model version number
        /// at the end of its migration work.
        ///
        /// The method also should normally modify the xml string(s)
        /// of relevant DTOs, since that string will be used by the main
        /// data migration calling client (ie. BEP).
        /// </remarks>
        /// ------------------------------------------------------------------------------------
        public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
        {
            DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000002);

            var footnotesToChangeClasses = new List <DomainObjectDTO>();

            foreach (var footnote in domainObjectDtoRepository.AllInstancesSansSubclasses("StFootnote"))
            {
                XElement footnoteEl = XElement.Parse(footnote.Xml);
                footnoteEl.Attribute("class").Value = "ScrFootnote";

                // Add the empty ScrFootnote element to the ScrFootnote
                footnoteEl.Add(new XElement("ScrFootnote"));

                // Update the object XML
                footnote.Xml       = footnoteEl.ToString();
                footnote.Classname = "ScrFootnote";
                footnotesToChangeClasses.Add(footnote);
            }

            // Udate the repository
            var startingStructure = new ClassStructureInfo("StText", "StFootnote");
            var endingStructure   = new ClassStructureInfo("StFootnote", "ScrFootnote");

            foreach (var changedPara in footnotesToChangeClasses)
            {
                domainObjectDtoRepository.Update(changedPara,
                                                 startingStructure,
                                                 endingStructure);
            }

            DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
        }
コード例 #3
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Changes all StFootnotes to ScrFootnotes
		/// </summary>
		/// <param name="domainObjectDtoRepository">
		/// Repository of all CmObject DTOs available for one migration step.
		/// </param>
		/// <remarks>
		/// The method must add/remove/update the DTOs to the repository,
		/// as it adds/removes objects as part of it work.
		///
		/// Implementors of this interface should ensure the Repository's
		/// starting model version number is correct for the step.
		/// Implementors must also increment the Repository's model version number
		/// at the end of its migration work.
		///
		/// The method also should normally modify the xml string(s)
		/// of relevant DTOs, since that string will be used by the main
		/// data migration calling client (ie. BEP).
		/// </remarks>
		/// ------------------------------------------------------------------------------------
		public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
		{
			DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000002);

			var footnotesToChangeClasses = new List<DomainObjectDTO>();
			foreach (var footnote in domainObjectDtoRepository.AllInstancesSansSubclasses("StFootnote"))
			{
				XElement footnoteEl = XElement.Parse(footnote.Xml);
				footnoteEl.Attribute("class").Value = "ScrFootnote";

				// Add the empty ScrFootnote element to the ScrFootnote
				footnoteEl.Add(new XElement("ScrFootnote"));

				// Update the object XML
				footnote.Xml = footnoteEl.ToString();
				footnote.Classname = "ScrFootnote";
				footnotesToChangeClasses.Add(footnote);
			}

			// Udate the repository
			var startingStructure = new ClassStructureInfo("StText", "StFootnote");
			var endingStructure = new ClassStructureInfo("StFootnote", "ScrFootnote");
			foreach (var changedPara in footnotesToChangeClasses)
				domainObjectDtoRepository.Update(changedPara,
					startingStructure,
					endingStructure);

			DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
		}
コード例 #4
0
        /// <summary>
        /// Given that the element has been changed to represent the desired new state of some DTO,
        /// save the change. This overload finds the DTO from the guid attribute on the element.
        /// </summary>
        private void UpdateDto(IDomainObjectDTORepository domainObjectDtoRepository, XElement element)
        {
            DomainObjectDTO dto = domainObjectDtoRepository.GetDTO(element.Attribute("guid").Value);

            dto.Xml = element.ToString();
            domainObjectDtoRepository.Update(dto);
        }
コード例 #5
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Perform one increment migration step.
		///
		/// In this case, the migration is not related to a model change,
		/// but is a simple data change that removes the class elements in the xml.
		/// The end resujlt xml will have the top-level 'rt' element and zero, or more,
		/// property level elements.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
		{
			DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000014);

			// No. We need to convert all instances, even if they are no longer part of the model.
			// DM19, for example, removes LgWritingSystem instances and the class form the model,
			// but it tries to access the data as if it had been properly processed by DM15,
			// *but* this code would leave out LgWritingSystem instnaces form being processed here.
			//foreach (var dto in domainObjectDtoRepository.AllInstancesWithSubclasses("CmObject"))
			foreach (var dto in domainObjectDtoRepository.AllInstances())
			{
				var rtElement = XElement.Parse(dto.Xml);
				// Removes all current child nodes (class level),
				// and replaces them with the old property nodes (if any).
#if !__MonoCS__
				rtElement.ReplaceNodes(rtElement.Elements().Elements());
				dto.Xml = rtElement.ToString();
#else // FWNX-165: work around mono bug https://bugzilla.novell.com/show_bug.cgi?id=592435
				var copy = new XElement(rtElement);
				copy.ReplaceNodes(rtElement.Elements().Elements());
				dto.Xml = copy.ToString();
#endif
				domainObjectDtoRepository.Update(dto);
			}

			DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
		}
コード例 #6
0
		public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
		{
			DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000050);

			var newGuidValue = Guid.NewGuid().ToString().ToLowerInvariant();
			const string className = "LangProject";
			var lpDto = domainObjectDtoRepository.AllInstancesSansSubclasses(className).First();
			var ownedDtos = domainObjectDtoRepository.GetDirectlyOwnedDTOs(lpDto.Guid).ToList();
			var data = lpDto.Xml;
			domainObjectDtoRepository.Remove(lpDto); // It is pretty hard to change an immutable Guid identifier in BEP-land, so nuke it, and make a new one.

			var lpElement = XElement.Parse(data);
			lpElement.Attribute("guid").Value = newGuidValue;
			var newLpDto = new DomainObjectDTO(newGuidValue, className, lpElement.ToString());
			domainObjectDtoRepository.Add(newLpDto);

			// Change ownerguid attr for each owned item to new guid.
			foreach (var ownedDto in ownedDtos)
			{
				var ownedElement = XElement.Parse(ownedDto.Xml);
				ownedElement.Attribute("ownerguid").Value = newGuidValue;
				ownedDto.Xml = ownedElement.ToString();
				domainObjectDtoRepository.Update(ownedDto);
			}

			DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
		}
コード例 #7
0
        public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
        {
            DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000050);

            var          newGuidValue = Guid.NewGuid().ToString().ToLowerInvariant();
            const string className    = "LangProject";
            var          lpDto        = domainObjectDtoRepository.AllInstancesSansSubclasses(className).First();
            var          ownedDtos    = domainObjectDtoRepository.GetDirectlyOwnedDTOs(lpDto.Guid).ToList();
            var          data         = lpDto.Xml;

            domainObjectDtoRepository.Remove(lpDto);             // It is pretty hard to change an immutable Guid identifier in BEP-land, so nuke it, and make a new one.

            var lpElement = XElement.Parse(data);

            lpElement.Attribute("guid").Value = newGuidValue;
            var newLpDto = new DomainObjectDTO(newGuidValue, className, lpElement.ToString());

            domainObjectDtoRepository.Add(newLpDto);

            // Change ownerguid attr for each owned item to new guid.
            foreach (var ownedDto in ownedDtos)
            {
                var ownedElement = XElement.Parse(ownedDto.Xml);
                ownedElement.Attribute("ownerguid").Value = newGuidValue;
                ownedDto.Xml = ownedElement.ToString();
                domainObjectDtoRepository.Update(ownedDto);
            }

            DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
        }
コード例 #8
0
		/// <summary>
		/// The Weather list is never used, so delete it (and remove any empty Weather elements
		/// from the RnGenericRec elements).
		/// </summary>
		private void DeleteWeatherListAndField(IDomainObjectDTORepository repoDTO)
		{
			// Remove the Weather list.
			DomainObjectDTO dtoLP = GetDtoLangProj(repoDTO);
			string sWeatherListGuid = RemoveWeatherConditionsElement(dtoLP).ToLowerInvariant();
			repoDTO.Update(dtoLP);
			DomainObjectDTO dtoDeadList = null;
			foreach (var dto in repoDTO.AllInstancesWithSubclasses("CmPossibilityList"))
			{
				if (dto.Guid.ToLowerInvariant() == sWeatherListGuid)
				{
					dtoDeadList = dto;
					break;
				}
			}
			List<DomainObjectDTO> rgdtoDead = new List<DomainObjectDTO>();
			GatherDeadObjects(repoDTO, dtoDeadList, rgdtoDead);
			foreach (var dto in rgdtoDead)
				repoDTO.Remove(dto);

			// Remove any empty Weather elements in the RnGenericRec objects.
			foreach (var dto in repoDTO.AllInstancesWithSubclasses("RnGenericRec"))
			{
				string sXml = dto.Xml;
				int idx = sXml.IndexOf("<Weather");
				if (idx > 0)
				{
					dto.Xml = RemoveEmptyWeather(sXml, idx);
					repoDTO.Update(dto);
				}
			}
		}
コード例 #9
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Changes all StTxtParas that are owned by Scripture to be ScrTxtParas
		/// </summary>
		/// <param name="domainObjectDtoRepository">
		/// Repository of all CmObject DTOs available for one migration step.
		/// </param>
		/// <remarks>
		/// The method must add/remove/update the DTOs to the repository,
		/// as it adds/removes objects as part of it work.
		///
		/// Implementors of this interface should ensure the Repository's
		/// starting model version number is correct for the step.
		/// Implementors must also increment the Repository's model version number
		/// at the end of its migration work.
		///
		/// The method also should normally modify the xml string(s)
		/// of relevant DTOs, since that string will be used by the main
		/// data migration calling client (ie. BEP).
		/// </remarks>
		/// ------------------------------------------------------------------------------------
		public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
		{
			DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000001);

			var parasToChangeClasses = new List<DomainObjectDTO>();
			foreach (var stTxtPara in domainObjectDtoRepository.AllInstancesSansSubclasses("StTxtPara"))
			{
				var paraOwner = domainObjectDtoRepository.GetOwningDTO(stTxtPara);
				if (paraOwner.Classname != "StText" && paraOwner.Classname != "StFootnote")
				{
					continue; // Paragraph is not owned by an StText or StFootnote (shouldn't ever happen)
				}

				var textOwner = domainObjectDtoRepository.GetOwningDTO(paraOwner);
				if (textOwner.Classname != "ScrBook" && textOwner.Classname != "ScrSection")
				{
					continue; // StText is not part of Scripture, don't change.
				}
				// Its one of the paragraphs that we care about. We just need to change the
				// class in the xml to be a ScrTxtPara and change the objectsByClass map.
				DataMigrationServices.ChangeToSubClass(stTxtPara, "StTxtPara", "ScrTxtPara");
				parasToChangeClasses.Add(stTxtPara);
			}

			// Udate the repository
			var startingStructure = new ClassStructureInfo("StPara", "StTxtPara");
			var endingStructure = new ClassStructureInfo("StTxtPara", "ScrTxtPara");
			foreach (var changedPara in parasToChangeClasses)
				domainObjectDtoRepository.Update(changedPara,
					startingStructure,
					endingStructure);

			DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
		}
コード例 #10
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Perform one increment migration step.
        ///
        /// In this case, the migration is not related to a model change,
        /// but is a simple data change that removes the class elements in the xml.
        /// The end resujlt xml will have the top-level 'rt' element and zero, or more,
        /// property level elements.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
        {
            DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000014);

            // No. We need to convert all instances, even if they are no longer part of the model.
            // DM19, for example, removes LgWritingSystem instances and the class form the model,
            // but it tries to access the data as if it had been properly processed by DM15,
            // *but* this code would leave out LgWritingSystem instnaces form being processed here.
            //foreach (var dto in domainObjectDtoRepository.AllInstancesWithSubclasses("CmObject"))
            foreach (var dto in domainObjectDtoRepository.AllInstances())
            {
                var rtElement = XElement.Parse(dto.Xml);
                // Removes all current child nodes (class level),
                // and replaces them with the old property nodes (if any).
#if !__MonoCS__
                rtElement.ReplaceNodes(rtElement.Elements().Elements());
                dto.Xml = rtElement.ToString();
#else // FWNX-165: work around mono bug https://bugzilla.novell.com/show_bug.cgi?id=592435
                var copy = new XElement(rtElement);
                copy.ReplaceNodes(rtElement.Elements().Elements());
                dto.Xml = copy.ToString();
#endif
                domainObjectDtoRepository.Update(dto);
            }

            DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
        }
コード例 #11
0
		/// <summary>
		/// Rest the xml in the DTO and register the DTO as udated with the repository.
		/// Use this overload only if the class name is NOT changing.
		/// </summary>
		/// <remarks>
		/// There is no validation of the xml, other than making sure it is not null,
		/// or an emty string.
		/// </remarks>
		internal static void UpdateDTO(IDomainObjectDTORepository dtoRepos,
			DomainObjectDTO dirtball, byte[] newXmlBytes)
		{
			if (dtoRepos == null) throw new ArgumentNullException("dtoRepos");
			if (dirtball == null) throw new ArgumentNullException("dirtball");
			if (newXmlBytes == null || newXmlBytes.Length == 0) throw new ArgumentNullException("newXmlBytes");

			dirtball.XmlBytes = newXmlBytes;
			dtoRepos.Update(dirtball);
		}
コード例 #12
0
		/// <summary>
		/// Rest the xml in the DTO and register the DTO as udated with the repository.
		/// Use this overload only if the class name is NOT changing.
		/// </summary>
		/// <remarks>
		/// There is no validation of the xml, other than making sure it is not null,
		/// or an emty string.
		/// </remarks>
		internal static void UpdateDTO(IDomainObjectDTORepository dtoRepos,
			DomainObjectDTO dirtball, string newXmlValue)
		{
			if (dtoRepos == null) throw new ArgumentNullException("dtoRepos");
			if (dirtball == null) throw new ArgumentNullException("dirtball");
			if (String.IsNullOrEmpty(newXmlValue)) throw new ArgumentNullException("newXmlValue");

			dirtball.Xml = newXmlValue;
			dtoRepos.Update(dirtball);
		}
コード例 #13
0
		public void PerformMigration(IDomainObjectDTORepository repoDto)
		{
			DataMigrationServices.CheckVersionNumber(repoDto, 7000041);

			var dtoLexDb = repoDto.AllInstancesSansSubclasses("LexDb").First();
			var xeLexDb = XElement.Parse(dtoLexDb.Xml);
			var guidComplexTypes = GetGuidValue(xeLexDb, "ComplexEntryTypes/objsur");
			var guidVariantTypes = GetGuidValue(xeLexDb, "VariantEntryTypes/objsur");
			BuildStandardMaps(guidComplexTypes, guidVariantTypes);
			var extraTypes = new List<LexTypeInfo>();
			var unprotectedTypes = new List<LexTypeInfo>();
			foreach (var dto in repoDto.AllInstancesSansSubclasses("LexEntryType"))
			{
				var xeType = XElement.Parse(dto.Xml);
				// ReSharper disable PossibleNullReferenceException
				var guid = xeType.Attribute("guid").Value;
				// ReSharper restore PossibleNullReferenceException
				string name;
				if (m_mapGuidName.TryGetValue(guid, out name))
				{
					m_mapGuidName.Remove(guid);
					m_mapNameGuid.Remove(name);
					var xeProt = xeType.XPathSelectElement("IsProtected");
					if (xeProt == null)
					{
						unprotectedTypes.Add(new LexTypeInfo(dto, xeType));
					}
					else
					{
						var xaVal = xeProt.Attribute("val");
						if (xaVal == null || xaVal.Value.ToLowerInvariant() != "true")
							unprotectedTypes.Add(new LexTypeInfo(dto, xeType));
					}
				}
				else
				{
					extraTypes.Add(new LexTypeInfo(dto, xeType));
				}
			}
			foreach (var info in unprotectedTypes)
			{
				var xeProt = info.XmlElement.XPathSelectElement("IsProtected");
				if (xeProt != null)
					xeProt.Remove();
				info.XmlElement.Add(new XElement("IsProtected", new XAttribute("val", "true")));
				info.DTO.Xml = info.XmlElement.ToString();
				repoDto.Update(info.DTO);
			}
			if (m_mapGuidName.Count > 0)
				FixOrAddMissingTypes(repoDto, extraTypes);
			FixOwnershipOfSubtypes(repoDto);
			DataMigrationServices.IncrementVersionNumber(repoDto);
		}
コード例 #14
0
        public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
        {
            DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000065);

            // Cache all basic data properties for each class in the mdc.
            var mdc = domainObjectDtoRepository.MDC;
            var cachedBasicProperties = CacheBasicProperties(mdc);

            foreach (var kvp in cachedBasicProperties)
            {
                var className = kvp.Key;
                if (mdc.GetAbstract(mdc.GetClassId(className)))
                {
                    continue;                     // Won't find any of those as dtos.
                }
                var basicProps = kvp.Value;
                foreach (var dto in domainObjectDtoRepository.AllInstancesSansSubclasses(className))
                {
                    var rootElementChanged = false;
                    var rootElement        = XElement.Parse(dto.Xml);
                    foreach (var basicPropertyInfo in basicProps)
                    {
                        if (basicPropertyInfo.m_isCustom)
                        {
                            var customPropElement = rootElement.Elements("Custom").FirstOrDefault(element => element.Attribute("name").Value == basicPropertyInfo.m_propertyName);
                            if (customPropElement == null)
                            {
                                CreateCustomProperty(rootElement, basicPropertyInfo);
                                rootElementChanged = true;
                            }
                        }
                        else
                        {
                            var basicPropertyElement = rootElement.Element(basicPropertyInfo.m_propertyName);
                            if (basicPropertyElement == null && !SkipTheseBasicPropertyNames.Contains(basicPropertyInfo.m_propertyName) && !basicPropertyInfo.m_isVirtual)
                            {
                                CreateBasicProperty(rootElement, basicPropertyInfo);
                                rootElementChanged = true;
                            }
                        }
                    }
                    if (!rootElementChanged)
                    {
                        continue;
                    }

                    dto.Xml = rootElement.ToString();
                    domainObjectDtoRepository.Update(dto);
                }
            }

            DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
        }
コード例 #15
0
/// <summary>
        /// Change any RnGenericRecord whose status is oldStatus to be newStatus.
        /// </summary>
        private void ReassignStatuses(IDomainObjectDTORepository domainObjectDtoRepository, string oldStatus, string newStatus)
        {
            // We need to go through tha collection because we need to change all status 'Appproved' to 'Confirmed'
            foreach (var RnRecDto in domainObjectDtoRepository.AllInstancesSansSubclasses("RnGenericRec").ToArray())
            {
                var rnElement = XElement.Parse(RnRecDto.Xml);
                if (!UpdateStatusInElement(rnElement, oldStatus, newStatus))
                {
                    continue;
                }
                RnRecDto.Xml = rnElement.ToString();
                domainObjectDtoRepository.Update(RnRecDto);
            }
        }
コード例 #16
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Perform one increment migration step.
        /// </summary>
        /// <param name="domainObjectDtoRepository">
        /// Repository of all CmObject DTOs available for one migration step.
        /// </param>
        /// <remarks>
        /// The method must add/remove/update the DTOs to the repository,
        /// as it adds/removes objects as part of it work.
        ///
        /// Implementors of this interface should ensure the Repository's
        /// starting model version number is correct for the step.
        /// Implementors must also increment the Repository's model version number
        /// at the end of its migration work.
        ///
        /// The method also should normally modify the xml string(s)
        /// of relevant DTOs, since that string will be used by the main
        /// data migration calling client (ie. BEP).
        /// </remarks>
        /// ------------------------------------------------------------------------------------
        public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
        {
            DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000061);

            // Step 1.
            foreach (var resourceDto in domainObjectDtoRepository.AllInstancesSansSubclasses("CmResource"))
            {
                var resourceElement     = XElement.Parse(resourceDto.Xml);
                var resourceNameElement = resourceElement.Element("Name");
                if (resourceNameElement == null)
                {
                    continue;
                }
                var uniElement = resourceNameElement.Element("Uni");
                if (uniElement == null)
                {
                    continue;
                }
                string oldVersion;
                switch (uniElement.Value)
                {
                case "TeStyles":
                    oldVersion = "700176e1-4f42-4abd-8fb5-3c586670085d";
                    break;

                case "FlexStyles":
                    oldVersion = "13c213b9-e409-41fc-8782-7ca0ee983b2c";
                    break;

                default:
                    continue;
                }
                var versionElement = resourceElement.Element("Version");
                if (versionElement == null)
                {
                    resourceElement.Add(new XElement("Version", new XAttribute("val", oldVersion)));
                }
                else
                {
                    versionElement.Attribute("val").Value = oldVersion;
                }
                resourceDto.Xml = resourceElement.ToString();
                domainObjectDtoRepository.Update(resourceDto);
            }

            // Step 2.
            DataMigrationServices.Delint(domainObjectDtoRepository);

            DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
        }
コード例 #17
0
        /// <summary>
        /// The Weather list is never used, so delete it (and remove any empty Weather elements
        /// from the RnGenericRec elements).
        /// </summary>
        private void DeleteWeatherListAndField(IDomainObjectDTORepository repoDTO)
        {
            // Remove the Weather list.
            DomainObjectDTO dtoLP            = GetDtoLangProj(repoDTO);
            string          sWeatherListGuid = RemoveWeatherConditionsElement(dtoLP).ToLowerInvariant();

            repoDTO.Update(dtoLP);
            DomainObjectDTO dtoDeadList = null;

            foreach (var dto in repoDTO.AllInstancesWithSubclasses("CmPossibilityList"))
            {
                if (dto.Guid.ToLowerInvariant() == sWeatherListGuid)
                {
                    dtoDeadList = dto;
                    break;
                }
            }
            List <DomainObjectDTO> rgdtoDead = new List <DomainObjectDTO>();

            GatherDeadObjects(repoDTO, dtoDeadList, rgdtoDead);
            foreach (var dto in rgdtoDead)
            {
                repoDTO.Remove(dto);
            }

            // Remove any empty Weather elements in the RnGenericRec objects.
            foreach (var dto in repoDTO.AllInstancesWithSubclasses("RnGenericRec"))
            {
                string sXml = dto.Xml;
                int    idx  = sXml.IndexOf("<Weather");
                if (idx > 0)
                {
                    dto.Xml = RemoveEmptyWeather(sXml, idx);
                    repoDTO.Update(dto);
                }
            }
        }
コード例 #18
0
		public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
		{
			DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000065);

			// Cache all basic data properties for each class in the mdc.
			var mdc = domainObjectDtoRepository.MDC;
			var cachedBasicProperties = CacheBasicProperties(mdc);
			foreach (var kvp in cachedBasicProperties)
			{
				var className = kvp.Key;
				if (mdc.GetAbstract(mdc.GetClassId(className)))
					continue; // Won't find any of those as dtos.

				var basicProps = kvp.Value;
				foreach (var dto in domainObjectDtoRepository.AllInstancesSansSubclasses(className))
				{
					var rootElementChanged = false;
					var rootElement = XElement.Parse(dto.Xml);
					foreach (var basicPropertyInfo in basicProps)
					{
						if (basicPropertyInfo.m_isCustom)
						{
							var customPropElement = rootElement.Elements("Custom").FirstOrDefault(element => element.Attribute("name").Value == basicPropertyInfo.m_propertyName);
							if (customPropElement == null)
							{
								CreateCustomProperty(rootElement, basicPropertyInfo);
								rootElementChanged = true;
							}
						}
						else
						{
							var basicPropertyElement = rootElement.Element(basicPropertyInfo.m_propertyName);
							if (basicPropertyElement == null && !SkipTheseBasicPropertyNames.Contains(basicPropertyInfo.m_propertyName) && !basicPropertyInfo.m_isVirtual)
							{
								CreateBasicProperty(rootElement, basicPropertyInfo);
								rootElementChanged = true;
							}
						}
					}
					if (!rootElementChanged)
						continue;

					dto.Xml = rootElement.ToString();
					domainObjectDtoRepository.Update(dto);
				}
			}

			DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
		}
コード例 #19
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Changes Chart 'missing' markers from invalid ConstChartWordGroup references to
        /// ConstChartTag objects with null Tag property.
        /// </summary>
        /// <param name="domainObjectDtoRepository">Repository of all CmObject DTOs available for
        /// one migration step.</param>
        /// ------------------------------------------------------------------------------------
        public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
        {
            DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000012);

            // 1) Select the ConstChartWordGroup class objects.
            // 2) Convert any with null BeginSegment reference to ConstChartTag objects with null Tag reference.
            var objsToChangeClasses = new List <DomainObjectDTO>();

            foreach (var cellPartDto in domainObjectDtoRepository.AllInstancesSansSubclasses("ConstChartWordGroup"))
            {
                var rtElement = XElement.Parse(cellPartDto.Xml);

                // Only migrate the ones that have no BeginSegment
                var wordGrp = rtElement.Element("ConstChartWordGroup");
                if (wordGrp.Element("BeginSegment") != null)
                {
                    continue;                     // Don't migrate this one, it has a BeginSegment reference!
                }
                // change its class value
                rtElement.Attribute("class").Value = "ConstChartTag";

                // Add the empty ConstChartTag element
                rtElement.Add(new XElement("ConstChartTag"));

                // Remove the old WordGroup element
                RemoveField(cellPartDto, rtElement, "ConstChartWordGroup");

                // Update the object XML
                cellPartDto.Xml       = rtElement.ToString();
                cellPartDto.Classname = "ConstChartTag";
                objsToChangeClasses.Add(cellPartDto);
            }

            // Update the repository
            var startingStructure = new ClassStructureInfo("ConstituentChartCellPart", "ConstChartWordGroup");
            var endingStructure   = new ClassStructureInfo("ConstituentChartCellPart", "ConstChartTag");

            foreach (var changedCellPart in objsToChangeClasses)
            {
                domainObjectDtoRepository.Update(changedCellPart,
                                                 startingStructure,
                                                 endingStructure);
            }

            DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
        }
コード例 #20
0
        private static void RemoveDanglingReferences(
            IDomainObjectDTORepository dtoRepos,
            IEnumerable <DomainObjectDTO> allDtos)
        {
            foreach (var currentDto in allDtos)
            {
                // Fetch the referred (regular reference or owning reference) to object guids.
                var referredToGuids = ExtractReferencedObjects(currentDto);

                // See if it is a dangling ref, where target object has been deleted.
                foreach (var targetGuid in referredToGuids)
                {
                    DomainObjectDTO referencedDto;
                    if (dtoRepos.TryGetValue(targetGuid, out referencedDto))
                    {
                        continue;
                    }

                    // targetGuid is a dangling reference.
                    // Remove the <objsur> element from referring object (kvp Key).
                    // The <objsur> will have its 'guid' attribute set to 'targetGuid'.
                    // This will work for owned as well as standard referenced objects.
                    var targetGuidAsString = targetGuid.ToLower();
                    var referringDto       = dtoRepos.GetDTO(currentDto.Guid);
                    var referringElement   = XElement.Parse(referringDto.Xml);
                    var emptyPropElements  = new List <XElement>();
                    foreach (var danglingRef in (referringElement.Descendants("objsur").Where(
                                                     objSurrElement => objSurrElement.Attribute("guid").Value.ToLower() == targetGuidAsString)).ToList())
                    {
                        var propElement = danglingRef.Parent;
                        danglingRef.Remove();
                        if (!propElement.HasAttributes && !propElement.HasElements)
                        {
                            emptyPropElements.Add(propElement);
                        }
                    }
                    foreach (var emptyPropElement in emptyPropElements)
                    {
                        emptyPropElement.Remove();                         // Remove now empty property element.
                    }
                    // Reset the xml.
                    referringDto.Xml = referringElement.ToString();
                    dtoRepos.Update(referringDto);
                }
            }
        }
コード例 #21
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Perform one increment migration step.
		/// </summary>
		/// <param name="domainObjectDtoRepository">
		/// Repository of all CmObject DTOs available for one migration step.
		/// </param>
		/// <remarks>
		/// The method must add/remove/update the DTOs to the repository,
		/// as it adds/removes objects as part of it work.
		///
		/// Implementors of this interface should ensure the Repository's
		/// starting model version number is correct for the step.
		/// Implementors must also increment the Repository's model version number
		/// at the end of its migration work.
		///
		/// The method also should normally modify the xml string(s)
		/// of relevant DTOs, since that string will be used by the main
		/// data migration calling client (ie. BEP).
		/// </remarks>
		/// ------------------------------------------------------------------------------------
		public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
		{
			DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000061);

			// Step 1.
			foreach (var resourceDto in domainObjectDtoRepository.AllInstancesSansSubclasses("CmResource"))
			{
				var resourceElement = XElement.Parse(resourceDto.Xml);
				var resourceNameElement = resourceElement.Element("Name");
				if (resourceNameElement == null)
					continue;
				var uniElement = resourceNameElement.Element("Uni");
				if (uniElement == null)
					continue;
				string oldVersion;
				switch (uniElement.Value)
				{
					case "TeStyles":
						oldVersion = "700176e1-4f42-4abd-8fb5-3c586670085d";
						break;
					case "FlexStyles":
						oldVersion = "13c213b9-e409-41fc-8782-7ca0ee983b2c";
						break;
					default:
						continue;
				}
				var versionElement = resourceElement.Element("Version");
				if (versionElement == null)
				{
					resourceElement.Add(new XElement("Version", new XAttribute("val", oldVersion)));
				}
				else
				{
					versionElement.Attribute("val").Value = oldVersion;
				}
				resourceDto.Xml = resourceElement.ToString();
				domainObjectDtoRepository.Update(resourceDto);
			}

			// Step 2.
			DataMigrationServices.Delint(domainObjectDtoRepository);

			DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
		}
コード例 #22
0
        /// <summary>
        /// Rest the xml in the DTO and register the DTO as udated with the repository.
        /// Use this overload only if the class name is NOT changing.
        /// </summary>
        /// <remarks>
        /// There is no validation of the xml, other than making sure it is not null,
        /// or an emty string.
        /// </remarks>
        internal static void UpdateDTO(IDomainObjectDTORepository dtoRepos,
                                       DomainObjectDTO dirtball, byte[] newXmlBytes)
        {
            if (dtoRepos == null)
            {
                throw new ArgumentNullException("dtoRepos");
            }
            if (dirtball == null)
            {
                throw new ArgumentNullException("dirtball");
            }
            if (newXmlBytes == null || newXmlBytes.Length == 0)
            {
                throw new ArgumentNullException("newXmlBytes");
            }

            dirtball.XmlBytes = newXmlBytes;
            dtoRepos.Update(dirtball);
        }
コード例 #23
0
        /// <summary>
        /// Rest the xml in the DTO and register the DTO as udated with the repository.
        /// Use this overload only if the class name is NOT changing.
        /// </summary>
        /// <remarks>
        /// There is no validation of the xml, other than making sure it is not null,
        /// or an emty string.
        /// </remarks>
        internal static void UpdateDTO(IDomainObjectDTORepository dtoRepos,
                                       DomainObjectDTO dirtball, string newXmlValue)
        {
            if (dtoRepos == null)
            {
                throw new ArgumentNullException("dtoRepos");
            }
            if (dirtball == null)
            {
                throw new ArgumentNullException("dirtball");
            }
            if (String.IsNullOrEmpty(newXmlValue))
            {
                throw new ArgumentNullException("newXmlValue");
            }

            dirtball.Xml = newXmlValue;
            dtoRepos.Update(dirtball);
        }
コード例 #24
0
        /// <summary>
        /// Creates a LexEntryType with all the basic properties filled in for the xml (necessary for S/R) and adds it to the dto
        /// </summary>
        private static void CreateLexEntryType(IDomainObjectDTORepository repoDto, string entryTypeGuid, string entryTypeListGuid,
                                               string abbr, string name, string reverseAbbr, DateTime createTime)
        {
            var entryTypeDto = DataMigrationServices.CreatePossibility(repoDto, entryTypeListGuid, entryTypeGuid, name, abbr, createTime, "LexEntryType");
            var letElement   = XElement.Parse(entryTypeDto.Xml);
            //// Add the Reverse Abbreviation
            var sb = new StringBuilder();

            sb.Append("<ReverseAbbr>");
            sb.AppendFormat("<AUni ws=\"en\">{0}</AUni>", reverseAbbr);
            sb.Append("</ReverseAbbr>");
            var reverseAbbrElement = XElement.Parse(sb.ToString());
            var abbrevElement      = letElement.Element("Abbreviation");

            // ReSharper disable once PossibleNullReferenceException -- CreatePossibility always adds an Abbreviation Element
            abbrevElement.AddAfterSelf(reverseAbbrElement);
            entryTypeDto.Xml = letElement.ToString();
            repoDto.Update(entryTypeDto);
        }
コード例 #25
0
		/// <summary>
		/// Remove all attributes from the "Uni"> element.
		/// </summary>
		/// <param name="domainObjectDtoRepository"></param>
		public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
		{
			DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000066);

			foreach (var dto in domainObjectDtoRepository.AllInstances())
			{
				var element = XElement.Parse(dto.Xml);
				var uniElementsWithAttrs = element.Elements().Elements("Uni").Where(uniElement => uniElement.HasAttributes).ToList();
				if (uniElementsWithAttrs.Count == 0)
					continue;
				foreach (var uniElementWithAttrs in uniElementsWithAttrs)
				{
					uniElementWithAttrs.Attributes().Remove();
					dto.Xml = element.ToString();
					domainObjectDtoRepository.Update(dto);
				}
			}

			DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
		}
コード例 #26
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Changes Chart 'missing' markers from invalid ConstChartWordGroup references to
		/// ConstChartTag objects with null Tag property.
		/// </summary>
		/// <param name="domainObjectDtoRepository">Repository of all CmObject DTOs available for
		/// one migration step.</param>
		/// ------------------------------------------------------------------------------------
		public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
		{
			DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000012);

			// 1) Select the ConstChartWordGroup class objects.
			// 2) Convert any with null BeginSegment reference to ConstChartTag objects with null Tag reference.
			var objsToChangeClasses = new List<DomainObjectDTO>();
			foreach (var cellPartDto in domainObjectDtoRepository.AllInstancesSansSubclasses("ConstChartWordGroup"))
			{
				var rtElement = XElement.Parse(cellPartDto.Xml);

				// Only migrate the ones that have no BeginSegment
				var wordGrp = rtElement.Element("ConstChartWordGroup");
				if (wordGrp.Element("BeginSegment") != null)
					continue; // Don't migrate this one, it has a BeginSegment reference!

				// change its class value
				rtElement.Attribute("class").Value = "ConstChartTag";

				// Add the empty ConstChartTag element
				rtElement.Add(new XElement("ConstChartTag"));

				// Remove the old WordGroup element
				RemoveField(cellPartDto, rtElement, "ConstChartWordGroup");

				// Update the object XML
				cellPartDto.Xml = rtElement.ToString();
				cellPartDto.Classname = "ConstChartTag";
				objsToChangeClasses.Add(cellPartDto);
			}

			// Update the repository
			var startingStructure = new ClassStructureInfo("ConstituentChartCellPart", "ConstChartWordGroup");
			var endingStructure = new ClassStructureInfo("ConstituentChartCellPart", "ConstChartTag");
			foreach (var changedCellPart in objsToChangeClasses)
				domainObjectDtoRepository.Update(changedCellPart,
					startingStructure,
					endingStructure);

			DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
		}
コード例 #27
0
		public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
		{
			DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000039);

			foreach (var dto in domainObjectDtoRepository.AllInstancesSansSubclasses("LexEntryRef"))
			{
				var xElt = XElement.Parse(dto.Xml);
				var primaryLexemes = xElt.Element("PrimaryLexemes");
				if (primaryLexemes == null || primaryLexemes.Elements().Count() == 0)
					continue;
				var newElt = new XElement("ShowComplexFormsIn");
				foreach (var child in primaryLexemes.Elements())
				{
					newElt.Add(new XElement(child)); // clone all the objsur elements.
				}
				xElt.Add(newElt);
				dto.Xml = xElt.ToString();
				domainObjectDtoRepository.Update(dto);
			}

			DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
		}
コード例 #28
0
        /// <summary>
        /// Remove all attributes from the "Uni"> element.
        /// </summary>
        /// <param name="domainObjectDtoRepository"></param>
        public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
        {
            DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000066);

            foreach (var dto in domainObjectDtoRepository.AllInstances())
            {
                var element = XElement.Parse(dto.Xml);
                var uniElementsWithAttrs = element.Elements().Elements("Uni").Where(uniElement => uniElement.HasAttributes).ToList();
                if (uniElementsWithAttrs.Count == 0)
                {
                    continue;
                }
                foreach (var uniElementWithAttrs in uniElementsWithAttrs)
                {
                    uniElementWithAttrs.Attributes().Remove();
                    dto.Xml = element.ToString();
                    domainObjectDtoRepository.Update(dto);
                }
            }

            DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
        }
コード例 #29
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Changes all StTxtParas that are owned by Scripture to be ScrTxtParas
        /// </summary>
        /// <param name="domainObjectDtoRepository">
        /// Repository of all CmObject DTOs available for one migration step.
        /// </param>
        /// <remarks>
        /// The method must add/remove/update the DTOs to the repository,
        /// as it adds/removes objects as part of it work.
        ///
        /// Implementors of this interface should ensure the Repository's
        /// starting model version number is correct for the step.
        /// Implementors must also increment the Repository's model version number
        /// at the end of its migration work.
        ///
        /// The method also should normally modify the xml string(s)
        /// of relevant DTOs, since that string will be used by the main
        /// data migration calling client (ie. BEP).
        /// </remarks>
        /// ------------------------------------------------------------------------------------
        public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
        {
            DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000001);

            var parasToChangeClasses = new List <DomainObjectDTO>();

            foreach (var stTxtPara in domainObjectDtoRepository.AllInstancesSansSubclasses("StTxtPara"))
            {
                var paraOwner = domainObjectDtoRepository.GetOwningDTO(stTxtPara);
                if (paraOwner.Classname != "StText" && paraOwner.Classname != "StFootnote")
                {
                    continue;                     // Paragraph is not owned by an StText or StFootnote (shouldn't ever happen)
                }

                var textOwner = domainObjectDtoRepository.GetOwningDTO(paraOwner);
                if (textOwner.Classname != "ScrBook" && textOwner.Classname != "ScrSection")
                {
                    continue;                     // StText is not part of Scripture, don't change.
                }
                // Its one of the paragraphs that we care about. We just need to change the
                // class in the xml to be a ScrTxtPara and change the objectsByClass map.
                DataMigrationServices.ChangeToSubClass(stTxtPara, "StTxtPara", "ScrTxtPara");
                parasToChangeClasses.Add(stTxtPara);
            }

            // Udate the repository
            var startingStructure = new ClassStructureInfo("StPara", "StTxtPara");
            var endingStructure   = new ClassStructureInfo("StTxtPara", "ScrTxtPara");

            foreach (var changedPara in parasToChangeClasses)
            {
                domainObjectDtoRepository.Update(changedPara,
                                                 startingStructure,
                                                 endingStructure);
            }

            DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
        }
コード例 #30
0
        public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
        {
            DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000039);

            foreach (var dto in domainObjectDtoRepository.AllInstancesSansSubclasses("LexEntryRef"))
            {
                var xElt           = XElement.Parse(dto.Xml);
                var primaryLexemes = xElt.Element("PrimaryLexemes");
                if (primaryLexemes == null || primaryLexemes.Elements().Count() == 0)
                {
                    continue;
                }
                var newElt = new XElement("ShowComplexFormsIn");
                foreach (var child in primaryLexemes.Elements())
                {
                    newElt.Add(new XElement(child));                     // clone all the objsur elements.
                }
                xElt.Add(newElt);
                dto.Xml = xElt.ToString();
                domainObjectDtoRepository.Update(dto);
            }

            DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
        }
コード例 #31
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Changes the use of CmAgentEvaluation, so that instead of one evaluation per agent/target pair
        /// owned by Agent.Evauations and referring to the target, there are only two CmAgentEvaluations
        /// owned by each CmAgent in their Approves and Disapproves properties, and they are referred to
        /// by the new WfiAnalysis.Evaluations Reference Collection.
        ///
        /// Specifically, for each CmAgent,
        /// - Create two CmAgentEvaluations, one owned in Approves and one in Disapproves.
        /// - For each item in Evaluations, if Accepted, add the appropriate Approves evaluation to
        ///     the target of the evaluation, otherwise, add the appropriate Disapproves (if there is a target).
        /// - Delete the Evaluations.
        ///
        /// As a side effect, since all existing CmAgentEvaluations are deleted, obsolete properties are removed.
        /// </summary>
        /// <param name="domainObjectDtoRepository">Repository of all CmObject DTOs available for
        /// one migration step.</param>
        /// ------------------------------------------------------------------------------------
        public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
        {
            DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000013);

            // from guid of a WfiAnalysis to list of evaluations.
            var map = new Dictionary <string, List <string> >();

            foreach (var agentDto in domainObjectDtoRepository.AllInstancesSansSubclasses("CmAgent"))
            {
                var rtElement    = XElement.Parse(agentDto.Xml);
                var agentElement = rtElement.Elements("CmAgent").First();
                // Create two new CmAgentEvaluations.
                var newApprovesEval    = MakeEvaluation(agentDto.Guid, domainObjectDtoRepository, agentElement, "Approves");
                var newDisapprovesEval = MakeEvaluation(agentDto.Guid, domainObjectDtoRepository, agentElement, "Disapproves");
                var evaluations        = agentElement.Elements("Evaluations").FirstOrDefault();
                if (evaluations != null)
                {
                    foreach (var objsur in evaluations.Elements("objsur"))
                    {
                        var evalGuidAttr = objsur.Attribute("guid");
                        if (evalGuidAttr == null)
                        {
                            continue;
                        }

                        var evalGuid        = evalGuidAttr.Value;
                        var obsoleteEvalDto = domainObjectDtoRepository.GetDTO(evalGuid);
                        if (obsoleteEvalDto == null)
                        {
                            continue;                             // defensive (RandyR says there is no need to be defensive, since the repos will throw an exception, if the guid ois not found.)
                        }
                        var agentEvalElt = XElement.Parse(obsoleteEvalDto.Xml).Element("CmAgentEvaluation");
                        if (agentEvalElt == null)
                        {
                            continue;                             // paranoid! (Also, no need for paranoia, since the element *must* be present, or the object cannot be reconstituted.)
                        }
                        // Delete/Remove the old evaluation.
                        domainObjectDtoRepository.Remove(obsoleteEvalDto);

                        var  acceptedElt = agentEvalElt.Element("Accepted");
                        bool accepted    = false;
                        if (acceptedElt != null)
                        {
                            var attr = acceptedElt.Attribute("val");
                            if (attr != null)
                            {
                                accepted = attr.Value.ToLowerInvariant() == "true";
                            }
                        }

                        var targetElt = agentEvalElt.Element("Target");
                        if (targetElt == null)
                        {
                            continue;
                        }
                        var targetObjsur = targetElt.Element("objsur");
                        if (targetObjsur == null)
                        {
                            continue;                             // paranoid
                        }
                        var targetGuidAttr = targetObjsur.Attribute("guid");
                        if (targetGuidAttr == null)
                        {
                            continue;                             // paranoid
                        }
                        var           targetGuid = targetGuidAttr.Value;
                        List <String> evals;
                        if (!map.TryGetValue(targetGuid, out evals))
                        {
                            evals           = new List <string>();
                            map[targetGuid] = evals;
                        }

                        evals.Add(accepted ? newApprovesEval.Guid : newDisapprovesEval.Guid);
                    }
                    evaluations.Remove();
                }
                agentDto.Xml = rtElement.ToString();
                domainObjectDtoRepository.Update(agentDto);
            }
            foreach (var kvp in map)
            {
                var analysisDto   = domainObjectDtoRepository.GetDTO(kvp.Key);
                var analysisRtElt = XElement.Parse(analysisDto.Xml);
                var analysisElt   = analysisRtElt.Element("WfiAnalysis");
                if (analysisElt == null)
                {
                    continue;                     // Paranoid
                }
                var evals = new XElement("Evaluations");
                analysisElt.Add(evals);
                foreach (var eval in kvp.Value)
                {
                    evals.Add(new XElement("objsur", new XAttribute("t", "r"), new XAttribute("guid", eval)));
                }
                analysisDto.Xml = analysisRtElt.ToString();
                domainObjectDtoRepository.Update(analysisDto);
            }

            DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
        }
コード例 #32
0
		/// <summary>
		/// 1. Create the "Strong" style if it doesn't exist (FWR-741).
		/// 2. Convert direct formatting to styles (FWR-648).
		/// 3. Move the StStyle objects in LexDb.Styles to LangProject.Styles, deleting those
		///	   with the same name as one already in LangProject.Styles (FWR-1163).
		///	4. Delete the Styles field from LexDb (FWR-1163).
		///	5. Remove "External Link" and "Internal Link" styles - migrate use of these to
		///	   "Hyperlink" style (FWR-1163).
		///	6. Rename "Language Code" style to "Writing System Abbreviation" (FWR-1163).
		///	7. Ensure that built-in styles from LangProject.Styles are marked built-in.
		/// </summary>
		public void PerformMigration(IDomainObjectDTORepository repoDTO)
		{
			m_repoDTO = repoDTO;
			// Get the list of StStyle DTOs from the LexDb.Styles field, and delete the
			// LexDb.Styles field.
			string sClass = "LexDb";
			DomainObjectDTO dtoLexDb = GetFirstInstance(sClass);
			string sXmlLexDb = dtoLexDb.Xml;
			int idxStyles = sXmlLexDb.IndexOf("<Styles>");
			int idxStylesLim = sXmlLexDb.IndexOf("</Styles>") + 9;
			string sLexDbStyles = sXmlLexDb.Substring(idxStyles, idxStylesLim - idxStyles);
			List<DomainObjectDTO> stylesLexDb = new List<DomainObjectDTO>();
			foreach (string sGuid in GetGuidList(sLexDbStyles))
			{
				var dto = m_repoDTO.GetDTO(sGuid);
				stylesLexDb.Add(dto);
			}
			dtoLexDb.Xml = sXmlLexDb.Remove(idxStyles, idxStylesLim - idxStyles);
			m_repoDTO.Update(dtoLexDb);

			// Get the list of StStyle DTOs (and style names) from the LangProject.Styles field.
			m_dtoLangProj = GetFirstInstance("LangProject");
			string sXmlLangProj = m_dtoLangProj.Xml;
			idxStyles = sXmlLangProj.IndexOf("<Styles>");
			idxStylesLim = sXmlLangProj.IndexOf("</Styles>") + 9;
			m_sLangProjStyles = sXmlLangProj.Substring(idxStyles, idxStylesLim - idxStyles);
			string sLangProjStylesOrig = m_sLangProjStyles;
			int idxEnd = m_sLangProjStyles.Length - 9;
			List<string> styleNames = new List<string>();
			m_langProjStyles.Clear();
			m_mapStyleNameToGuid.Clear();
			DomainObjectDTO dtoHyperlink = null;
			DomainObjectDTO dtoExternalLink = null;
			DomainObjectDTO dtoInternalLink = null;
			DomainObjectDTO dtoLanguageCode = null;
			DomainObjectDTO dtoWrtSysAbbr = null;
			DomainObjectDTO dtoStrong = null;
			foreach (string sGuid in GetGuidList(m_sLangProjStyles))
			{
				var dto = m_repoDTO.GetDTO(sGuid);
				string sName = GetStyleName(dto.Xml);
				styleNames.Add(sName);
				m_langProjStyles.Add(dto);
				m_mapStyleNameToGuid.Add(sName, dto.Guid.ToLowerInvariant());
				switch (sName)
				{
					case "Hyperlink":
						dtoHyperlink = dto;
						break;
					case "External Link":
						dtoExternalLink = dto;
						break;
					case "Internal Link":
						dtoInternalLink = dto;
						break;
					case "Language Code":
						dtoLanguageCode = dto;
						break;
					case "Writing System Abbreviation":
						dtoWrtSysAbbr = dto;
						break;
					case "Strong":
						dtoStrong = dto;
						break;
				}
			}
			var mapLexDbStyleGuidName = new Dictionary<string, string>();
			// For each style in the ones we might delete we need to know the name of the style it is based on and its next style
			foreach (var dto in stylesLexDb)
			{
				var elt = XElement.Parse(dto.Xml);
				var name = elt.Element("Name").Element("Uni").Value;
				mapLexDbStyleGuidName[dto.Guid] = name;
			}
			Dictionary<string, string> mapStyleGuids = new Dictionary<string, string>();
			foreach (var dto in stylesLexDb)
			{
				string sXml = dto.Xml;
				string sName = GetStyleName(sXml);
				if (styleNames.Contains(sName))
				{
					var keeperGuid = m_mapStyleNameToGuid[sName];
					mapStyleGuids.Add(dto.Guid.ToLowerInvariant(), keeperGuid);
					// Duplicate between Notebook (LangProj) styles already in the dictionary,
					// and Lexicon (LexDb) ones being added. Discard the Lexicon style OBJECT, but keep its rules.
					var dtoKeeper = repoDTO.GetDTO(keeperGuid);
					var keeperElement = XElement.Parse(dtoKeeper.Xml);
					var dropElement = XElement.Parse(dto.Xml);
					var rules = dropElement.Element("Rules");
					if (rules != null)
					{
						var oldRules = keeperElement.Element("Rules");
						oldRules.ReplaceWith(rules);
					}
					UpdateStyleCrossReference(mapLexDbStyleGuidName, dropElement, keeperElement, "BasedOn");
					UpdateStyleCrossReference(mapLexDbStyleGuidName, dropElement, keeperElement, "Next");
					dtoKeeper.Xml = keeperElement.ToString();
					repoDTO.Update(dtoKeeper);
					m_repoDTO.Remove(dto);
				}
				else
				{
					// change the ownership links
					m_sLangProjStyles = m_sLangProjStyles.Insert(idxEnd, string.Format("<objsur guid=\"{0}\" t=\"o\"/>{1}", dto.Guid, Environment.NewLine));
					idxEnd = m_sLangProjStyles.Length - 9;
					SetOwnerGuid(dto, m_dtoLangProj.Guid);
					switch (sName)
					{
						case "Hyperlink":					dtoHyperlink = dto;		break;
						case "External Link":				dtoExternalLink = dto;	break;
						case "Internal Link":				dtoInternalLink = dto;	break;
						case "Language Code":				dtoLanguageCode = dto;	break;
						case "Writing System Abbreviation":	dtoWrtSysAbbr = dto;	break;
						case "Strong":						dtoStrong = dto;		break;
					}
					styleNames.Add(sName);
					m_langProjStyles.Add(dto);
					m_mapStyleNameToGuid.Add(sName, dto.Guid.ToLowerInvariant());
				}
			}
			// if "Hyperlink" does not exist, create it.
			if (dtoHyperlink == null)
			{
				dtoHyperlink = CreateCharStyle("Hyperlink",
					"<Prop forecolor=\"blue\" undercolor=\"blue\" underline=\"single\" />",
					ContextValues.Internal);
				m_langProjStyles.Add(dtoHyperlink);
				m_mapStyleNameToGuid.Add("Hyperlink", dtoHyperlink.Guid.ToLowerInvariant());
			}
			else
			{
				// ensure that the Hyperlink style has an "internal" context.
				string sXml = dtoHyperlink.Xml;
				int idx = sXml.IndexOf("<Context");
				if (idx > 0)
				{
					XElement xeHyper = XElement.Parse(sXml);
					foreach (XElement xe in xeHyper.Descendants("Context"))
					{
						int nVal;
						XAttribute xa = xe.Attribute("val");
						if (xa != null && Int32.TryParse(xa.Value, out nVal) && nVal != (int)ContextValues.Internal)
						{
							nVal = (int)ContextValues.Internal;
							xa.Value = nVal.ToString();
							dtoHyperlink.Xml = xeHyper.ToString();
							m_repoDTO.Update(dtoHyperlink);
							break;
						}
					}
				}
			}
			// delete "External Link" and "Internal Link", and prepare to replace links to
			// them with a link to "Hyperlink".
			if (dtoExternalLink != null)
			{
				mapStyleGuids.Add(dtoExternalLink.Guid.ToLowerInvariant(), dtoHyperlink.Guid.ToLowerInvariant());
				m_sLangProjStyles = DeleteStyle(m_sLangProjStyles, dtoExternalLink);
				m_mapStyleNameToGuid["External Link"] = dtoHyperlink.Guid.ToLowerInvariant();
			}
			if (dtoInternalLink != null)
			{
				mapStyleGuids.Add(dtoInternalLink.Guid.ToLowerInvariant(), dtoHyperlink.Guid.ToLowerInvariant());
				m_sLangProjStyles = DeleteStyle(m_sLangProjStyles, dtoInternalLink);
				m_mapStyleNameToGuid["Internal Link"] = dtoHyperlink.Guid.ToLowerInvariant();
			}
			if (dtoLanguageCode == null)
			{
				// If neither "Language Code" nor "Writing System Abbreviation" exist, create the
				// "Writing System Abbreviation" style.
				if (dtoWrtSysAbbr == null)
				{
					dtoWrtSysAbbr = CreateCharStyle("Writing System Abbreviation",
						"<Prop fontsize=\"8000\" fontsizeUnit=\"mpt\" forecolor=\"2f60ff\" />",
						ContextValues.General);
					m_langProjStyles.Add(dtoWrtSysAbbr);
					m_mapStyleNameToGuid.Add("Writing System Abbreviation", dtoWrtSysAbbr.Guid.ToLowerInvariant());
				}
				else
				{
					// We don't need to do anything.
				}
			}
			else
			{
				if (dtoWrtSysAbbr == null)
				{
					// Rename "Language Code" to "Writing System Abbreviation".
					string sXml = dtoLanguageCode.Xml;
					dtoLanguageCode.Xml = sXml.Replace("<Uni>Language Code</Uni>",
						"<Uni>Writing System Abbreviation</Uni>");
					m_repoDTO.Update(dtoLanguageCode);
					m_mapStyleNameToGuid.Add("Writing System Abbreviation", dtoLanguageCode.Guid.ToLowerInvariant());
				}
				else
				{
					// delete "Language Code", and prepare to replace links to it with a link to
					// "Writing System Abbreviation".
					mapStyleGuids.Add(dtoLanguageCode.Guid.ToLowerInvariant(), dtoWrtSysAbbr.Guid.ToLowerInvariant());
					m_sLangProjStyles = DeleteStyle(m_sLangProjStyles, dtoLanguageCode);
					m_mapStyleNameToGuid["Language Code"] = dtoWrtSysAbbr.Guid.ToLowerInvariant();
				}
			}
			// if "Strong" does not exist, create it.
			if (dtoStrong == null)
			{
				dtoStrong = CreateCharStyle("Strong", "<Prop bold=\"invert\" />", ContextValues.General);
				m_langProjStyles.Add(dtoStrong);
				m_mapStyleNameToGuid.Add("Strong", dtoStrong.Guid.ToLowerInvariant());
			}
			ChangeStyleReferences();
			UpdateStyleLinks(mapStyleGuids);
			ReplaceDirectFormattingWithStyles();
			EnsureBuiltinStylesAreMarkedBuiltin();

			if (m_sLangProjStyles != sLangProjStylesOrig)
			{
				sXmlLangProj = sXmlLangProj.Remove(idxStyles, idxStylesLim - idxStyles);
				m_dtoLangProj.Xml = sXmlLangProj.Insert(idxStyles, m_sLangProjStyles);
				m_repoDTO.Update(m_dtoLangProj);
			}

			DataMigrationServices.IncrementVersionNumber(m_repoDTO);
		}
コード例 #33
0
		public void PerformMigration(IDomainObjectDTORepository repoDto)
		{
			DataMigrationServices.CheckVersionNumber(repoDto, 7000060);

			// Step 1.A. & 3.
			//var unownedGonerCandidates = new List<DomainObjectDTO>();
			//unownedGonerCandidates.AddRange(repoDto.AllInstancesSansSubclasses("CmBaseAnnotation"));
			//unownedGonerCandidates.AddRange(repoDto.AllInstancesSansSubclasses("CmIndirectAnnotation"));
			//unownedGonerCandidates.AddRange(repoDto.AllInstancesSansSubclasses("StStyle"));
			//unownedGonerCandidates.AddRange(repoDto.AllInstancesSansSubclasses("StText"));
			//var unownedGoners = new List<DomainObjectDTO>();
			//foreach (var domainObjectDto in unownedGonerCandidates)
			//{
			//    DomainObjectDTO ownerDto;
			//    repoDto.TryGetOwner(domainObjectDto.Guid, out ownerDto);
			//    if (ownerDto != null)
			//        continue;
			//    unownedGoners.Add(domainObjectDto);
			//}
			//foreach (var unownedGoner in unownedGoners)
			//{
			//    DataMigrationServices.RemoveIncludingOwnedObjects(repoDto, unownedGoner, false);
			//}

			// Step 1.B.
			foreach (var resourceDto in repoDto.AllInstancesSansSubclasses("CmResource"))
			{
				var resourceElement = XElement.Parse(resourceDto.Xml);
				var resourceNameElement = resourceElement.Element("Name");
				if (resourceNameElement == null)
					continue;
				var uniElement = resourceNameElement.Element("Uni");
				if (uniElement == null)
					continue;
				string oldVersion;
				switch (uniElement.Value)
				{
					case "TeStyles":
						oldVersion = "700176e1-4f42-4abd-8fb5-3c586670085d";
						break;
					case "FlexStyles":
						oldVersion = "13c213b9-e409-41fc-8782-7ca0ee983b2c";
						break;
					default:
						continue;
				}
				var versionElement = resourceElement.Element("Version");
				if (versionElement == null)
				{
					resourceElement.Add(new XElement("Version", new XAttribute("val", oldVersion)));
				}
				else
				{
					versionElement.Attribute("val").Value = oldVersion;
				}
				resourceDto.Xml = resourceElement.ToString();
				repoDto.Update(resourceDto);
			}

			// Step 2.
			var mdc = repoDto.MDC;
			foreach (var clid in mdc.GetClassIds())
			{
				if (mdc.GetAbstract(clid))
					continue;

				var className = mdc.GetClassName(clid);
				foreach (var atomicPropId in mdc.GetFields(clid, true, (int)CellarPropertyTypeFilter.AllAtomic))
				{
					var propName = mdc.GetFieldName(atomicPropId);
					var isCustomProperty = mdc.IsCustom(atomicPropId);
					foreach (var dto in repoDto.AllInstancesSansSubclasses(className))
					{
						var element = XElement.Parse(dto.Xml);
						var propElement = isCustomProperty
											  ? (element.Elements("Custom").Where(customPropElement => customPropElement.Attribute("name").Value == propName)).FirstOrDefault()
											  : element.Element(propName);
						if (propElement == null || !propElement.HasElements)
							continue;

						var objsurElements = propElement.Elements("objsur").ToList();
						if (objsurElements.Count <= 1)
							continue;

						// Remove all but first one of them.
						propElement.RemoveNodes();
						propElement.Add(objsurElements[0]);
						dto.Xml = element.ToString();
						repoDto.Update(dto);
					}
				}
			}

			// Step 4.
			DataMigrationServices.Delint(repoDto);

			DataMigrationServices.IncrementVersionNumber(repoDto);
		}
コード例 #34
0
		/// <summary>
		/// Given that the element has been changed to represent the desired new state of some DTO,
		/// save the change. This overload finds the DTO from the guid attribute on the element.
		/// </summary>
		private void UpdateDto(IDomainObjectDTORepository domainObjectDtoRepository, XElement element)
		{
			DomainObjectDTO dto = domainObjectDtoRepository.GetDTO(element.Attribute("guid").Value);
			dto.Xml = element.ToString();
			domainObjectDtoRepository.Update(dto);
		}
コード例 #35
0
		/// <summary>
		/// Given that the element has been changed to represent the desired new state of the DTO,
		/// save the change.
		/// </summary>
		private void UpdateDto(IDomainObjectDTORepository domainObjectDtoRepository, DomainObjectDTO dto, XElement element)
		{
			dto.Xml = element.ToString();
			domainObjectDtoRepository.Update(dto);
		}
コード例 #36
0
/// <summary>
		/// Change any RnGenericRecord whose status is oldStatus to be newStatus.
		/// </summary>
		private void ReassignStatuses(IDomainObjectDTORepository domainObjectDtoRepository, string oldStatus, string newStatus)
		{
			// We need to go through tha collection because we need to change all status 'Appproved' to 'Confirmed'
			foreach (var RnRecDto in domainObjectDtoRepository.AllInstancesSansSubclasses("RnGenericRec").ToArray())
			{
				var rnElement = XElement.Parse(RnRecDto.Xml);
				if (!UpdateStatusInElement(rnElement, oldStatus, newStatus))
					continue;
				RnRecDto.Xml = rnElement.ToString();
				domainObjectDtoRepository.Update(RnRecDto);
			}
		}
コード例 #37
0
 /// <summary>
 /// Given that the element has been changed to represent the desired new state of the DTO,
 /// save the change.
 /// </summary>
 private void UpdateDto(IDomainObjectDTORepository domainObjectDtoRepository, DomainObjectDTO dto, XElement element)
 {
     dto.Xml = element.ToString();
     domainObjectDtoRepository.Update(dto);
 }
コード例 #38
0
		private static void RemoveDanglingReferences(
			IDomainObjectDTORepository dtoRepos,
			IEnumerable<DomainObjectDTO> allDtos)
		{
			foreach (var currentDto in allDtos)
			{
				 // Fetch the referred (regular reference or owning reference) to object guids.
			   var referredToGuids = ExtractReferencedObjects(currentDto);

				// See if it is a dangling ref, where target object has been deleted.
				foreach (var targetGuid in referredToGuids)
				{
					DomainObjectDTO referencedDto;
					if (dtoRepos.TryGetValue(targetGuid, out referencedDto))
						continue;

					// targetGuid is a dangling reference.
					// Remove the <objsur> element from referring object (kvp Key).
					// The <objsur> will have its 'guid' attribute set to 'targetGuid'.
					// This will work for owned as well as standard referenced objects.
					var targetGuidAsString = targetGuid.ToLower();
					var referringDto = dtoRepos.GetDTO(currentDto.Guid);
					var referringElement = XElement.Parse(referringDto.Xml);
					var emptyPropElements = new List<XElement>();
					foreach (var danglingRef in (referringElement.Descendants("objsur").Where(
						objSurrElement => objSurrElement.Attribute("guid").Value.ToLower() == targetGuidAsString)).ToList())
					{
						var propElement = danglingRef.Parent;
						danglingRef.Remove();
						if (!propElement.HasAttributes && !propElement.HasElements)
							emptyPropElements.Add(propElement);
					}
					foreach (var emptyPropElement in emptyPropElements)
						emptyPropElement.Remove(); // Remove now empty property element.
					// Reset the xml.
					referringDto.Xml = referringElement.ToString();
					dtoRepos.Update(referringDto);
				}
			}
		}
コード例 #39
0
		public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
		{
			DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000040);

			// (WRONG) The ExcludeAsHeadword element only appears when @val="true" and
			// it is to be replaced by DoNotShowMainEntryIn with a list of all publications.
			// NB: The above statement is simply not true (RBR).
			// FW 7 writes out all primitive data properties.
			// The FW 6-FW7 migrator doesn't add them,
			// but FW 7 writes them the next time an object gets changed.

			// Make the list of publications once
			var newElt = new XElement("DoNotShowMainEntryIn");

			IEnumerable<XElement> dtoPubList = null;
			// XPATH: rt[Name/AUni='Publications']/Possibilities/objsur
			foreach (var a_list in domainObjectDtoRepository.AllInstancesSansSubclasses("CmPossibilityList"))
			{
				var xList = XElement.Parse(a_list.Xml);
				if (xList.XPathSelectElement("Name[AUni='Publications']") == null) continue;
				dtoPubList = xList.XPathSelectElements("Possibilities/objsur");
				if (dtoPubList != null && dtoPubList.Count() > 0) break;
			}

			if (dtoPubList == null || dtoPubList.Count() == 0) // add the Publications list to the project
			{   // This list is owned by LexDb
				var ieDtoLexDb = domainObjectDtoRepository.AllInstancesSansSubclasses("LexDb");
				Debug.Assert(ieDtoLexDb != null && ieDtoLexDb.Count<DomainObjectDTO>() == 1, "Project has no LexDb Dto or more than one");
				var dtoLexDb = ieDtoLexDb.First<DomainObjectDTO>();
				var xNode = XElement.Parse(dtoLexDb.Xml);
				var ksguidLexDb = xNode.Attribute("guid").Value;
				var nowStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
				string xmlStrPub =
"<rt guid=\"" + ksguidPubList + "\" class=\"CmPossibilityList\" ownerguid=\"" + ksguidLexDb + "\"><Name><AUni ws=\"en\">Publications</AUni></Name><DateCreated val=\"" + nowStr + "\" /><DateModified val=\"" + nowStr + "\" /><Depth val=\"1\" /><PreventChoiceAboveLevel val=\"0\" /><IsSorted val=\"True\" /><IsClosed val=\"False\" /><PreventDuplicates val=\"False\" /><PreventNodeChoices val=\"False\" /><UseExtendedFields val=\"False\" /><DisplayOption val=\"0\" /><ItemClsid val=\"7\" /><IsVernacular val=\"False\" /><WsSelector val=\"0\" /><ListVersion val=\"00000000-0000-0000-0000-000000000000\" /><Possibilities><objsur guid=\"" + ksguidMainDictionary + "\" t=\"o\" /></Possibilities></rt>";
				var dtoPub = new DomainObjectDTO(ksguidPubList, "CmPossibilityList", xmlStrPub);

				string xmlStrMD = "<rt guid=\"" + ksguidMainDictionary + "\" class=\"CmPossibility\" ownerguid=\"" + ksguidPubList + "\"><Name><AUni ws=\"en\">Main Dictionary</AUni></Name><Abbreviation><AUni ws=\"en\">Main</AUni></Abbreviation><SortSpec val=\"0\" /><DateCreated val=\"" + nowStr + "\" /><DateModified val=\"" + nowStr + "\" /><ForeColor val=\"0\" /><BackColor val=\"0\" /><UnderColor val=\"0\" /><UnderStyle val=\"0\" /><Hidden val=\"False\" /><IsProtected val=\"True\" /></rt>";
				var dtoMD = new DomainObjectDTO(ksguidMainDictionary, "CmPossibility", xmlStrMD);

				domainObjectDtoRepository.Add(dtoMD);
				domainObjectDtoRepository.Add(dtoPub);

				// Make xLexDb own dtoPub
				var xPts = xNode.Element("PublicationTypes");
				if (xPts == null)
				{   // add one to LexDb
					xPts = new XElement("PublicationTypes");
					xPts.Add(DataMigrationServices.CreateOwningObjSurElement(ksguidPubList));
					xNode.Add(xPts);
				}
				Debug.Assert(xPts != null, "LexDb has no PublicatonTypes and won't accept new ones.");
				dtoLexDb.Xml = xNode.ToString();
				domainObjectDtoRepository.Update(dtoLexDb);
				newElt.Add(DataMigrationServices.CreateReferenceObjSurElement(ksguidMainDictionary));
			}
			else
			{   // already had a publications list - add all to DoNotShowMainEntryIn
				foreach (var xElt in dtoPubList)
				{   // change the t attr to "r" reference instead of "o" own.
					var xPubRef = new XElement(xElt);
					xPubRef.SetAttributeValue("t", "r");
					newElt.Add(xPubRef);
				}
			}
			foreach (var dto in domainObjectDtoRepository.AllInstancesSansSubclasses("LexEntry"))
			{
				// (WRONG) The ExcludeAsHeadword element only appears when @val="true" unless played with in a text editor
				// NB: The above statement is simply not true (RBR).
				// FW 7 writes out all primitive data properties.
				// The FW 6-FW7 migrator doesn't add them,
				// but FW 7 writes them the next time an object gets changed.
				var xElt = XElement.Parse(dto.Xml);
				var exHeadword = xElt.Element("ExcludeAsHeadword");
				if (exHeadword == null)
					continue;
				XAttribute XAval = exHeadword.Attribute("val");
				// It must be upper-case, since that is what is output.
				if (XAval.Value == "True")
				{	// Add all publications from the list to this property
					xElt.Add(new XElement(newElt));
				}
				exHeadword.Remove(); // exHeadword.Value may be True, False or invalid
				dto.Xml = xElt.ToString();
				domainObjectDtoRepository.Update(dto);
			}
			DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
		}
コード例 #40
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Changes the use of CmAgentEvaluation, so that instead of one evaluation per agent/target pair
		/// owned by Agent.Evauations and referring to the target, there are only two CmAgentEvaluations
		/// owned by each CmAgent in their Approves and Disapproves properties, and they are referred to
		/// by the new WfiAnalysis.Evaluations Reference Collection.
		///
		/// Specifically, for each CmAgent,
		/// - Create two CmAgentEvaluations, one owned in Approves and one in Disapproves.
		/// - For each item in Evaluations, if Accepted, add the appropriate Approves evaluation to
		///     the target of the evaluation, otherwise, add the appropriate Disapproves (if there is a target).
		/// - Delete the Evaluations.
		///
		/// As a side effect, since all existing CmAgentEvaluations are deleted, obsolete properties are removed.
		/// </summary>
		/// <param name="domainObjectDtoRepository">Repository of all CmObject DTOs available for
		/// one migration step.</param>
		/// ------------------------------------------------------------------------------------
		public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
		{
			DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000013);

			// from guid of a WfiAnalysis to list of evaluations.
			var map = new Dictionary<string, List<string>>();
			foreach (var agentDto in domainObjectDtoRepository.AllInstancesSansSubclasses("CmAgent"))
			{
				var rtElement = XElement.Parse(agentDto.Xml);
				var agentElement = rtElement.Elements("CmAgent").First();
				// Create two new CmAgentEvaluations.
				var newApprovesEval = MakeEvaluation(agentDto.Guid, domainObjectDtoRepository, agentElement, "Approves");
				var newDisapprovesEval = MakeEvaluation(agentDto.Guid, domainObjectDtoRepository, agentElement, "Disapproves");
				var evaluations = agentElement.Elements("Evaluations").FirstOrDefault();
				if (evaluations != null)
				{
					foreach (var objsur in evaluations.Elements("objsur"))
					{
						var evalGuidAttr = objsur.Attribute("guid");
						if (evalGuidAttr == null) continue;

						var evalGuid = evalGuidAttr.Value;
						var obsoleteEvalDto = domainObjectDtoRepository.GetDTO(evalGuid);
						if (obsoleteEvalDto == null)
							continue; // defensive (RandyR says there is no need to be defensive, since the repos will throw an exception, if the guid ois not found.)
						var agentEvalElt = XElement.Parse(obsoleteEvalDto.Xml).Element("CmAgentEvaluation");
						if (agentEvalElt == null)
							continue; // paranoid! (Also, no need for paranoia, since the element *must* be present, or the object cannot be reconstituted.)

						// Delete/Remove the old evaluation.
						domainObjectDtoRepository.Remove(obsoleteEvalDto);

						var acceptedElt = agentEvalElt.Element("Accepted");
						bool accepted = false;
						if (acceptedElt != null)
						{
							var attr = acceptedElt.Attribute("val");
							if (attr != null)
								accepted = attr.Value.ToLowerInvariant() == "true";
						}

						var targetElt = agentEvalElt.Element("Target");
						if (targetElt == null)
							continue;
						var targetObjsur = targetElt.Element("objsur");
						if (targetObjsur == null)
							continue; // paranoid
						var targetGuidAttr = targetObjsur.Attribute("guid");
						if (targetGuidAttr == null)
							continue; // paranoid
						var targetGuid = targetGuidAttr.Value;
						List<String> evals;
						if (!map.TryGetValue(targetGuid, out evals))
						{
							evals = new List<string>();
							map[targetGuid] = evals;
						}

						evals.Add(accepted ? newApprovesEval.Guid : newDisapprovesEval.Guid);
					}
					evaluations.Remove();
				}
				agentDto.Xml = rtElement.ToString();
				domainObjectDtoRepository.Update(agentDto);
			}
			foreach (var kvp in map)
			{
				var analysisDto = domainObjectDtoRepository.GetDTO(kvp.Key);
				var analysisRtElt = XElement.Parse(analysisDto.Xml);
				var analysisElt = analysisRtElt.Element("WfiAnalysis");
				if (analysisElt == null)
					continue; // Paranoid
				var evals = new XElement("Evaluations");
				analysisElt.Add(evals);
				foreach (var eval in kvp.Value)
				{
					evals.Add(new XElement("objsur", new XAttribute("t", "r"), new XAttribute("guid", eval)));
				}
				analysisDto.Xml = analysisRtElt.ToString();
				domainObjectDtoRepository.Update(analysisDto);
			}

			DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
		}
コード例 #41
0
        public void PerformMigration(IDomainObjectDTORepository domainObjectDtoRepository)
        {
            DataMigrationServices.CheckVersionNumber(domainObjectDtoRepository, 7000040);

            // (WRONG) The ExcludeAsHeadword element only appears when @val="true" and
            // it is to be replaced by DoNotShowMainEntryIn with a list of all publications.
            // NB: The above statement is simply not true (RBR).
            // FW 7 writes out all primitive data properties.
            // The FW 6-FW7 migrator doesn't add them,
            // but FW 7 writes them the next time an object gets changed.

            // Make the list of publications once
            var newElt = new XElement("DoNotShowMainEntryIn");

            IEnumerable <XElement> dtoPubList = null;

            // XPATH: rt[Name/AUni='Publications']/Possibilities/objsur
            foreach (var a_list in domainObjectDtoRepository.AllInstancesSansSubclasses("CmPossibilityList"))
            {
                var xList = XElement.Parse(a_list.Xml);
                if (xList.XPathSelectElement("Name[AUni='Publications']") == null)
                {
                    continue;
                }
                dtoPubList = xList.XPathSelectElements("Possibilities/objsur");
                if (dtoPubList != null && dtoPubList.Count() > 0)
                {
                    break;
                }
            }

            if (dtoPubList == null || dtoPubList.Count() == 0) // add the Publications list to the project
            {                                                  // This list is owned by LexDb
                var ieDtoLexDb = domainObjectDtoRepository.AllInstancesSansSubclasses("LexDb");
                Debug.Assert(ieDtoLexDb != null && ieDtoLexDb.Count <DomainObjectDTO>() == 1, "Project has no LexDb Dto or more than one");
                var    dtoLexDb    = ieDtoLexDb.First <DomainObjectDTO>();
                var    xNode       = XElement.Parse(dtoLexDb.Xml);
                var    ksguidLexDb = xNode.Attribute("guid").Value;
                var    nowStr      = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                string xmlStrPub   =
                    "<rt guid=\"" + ksguidPubList + "\" class=\"CmPossibilityList\" ownerguid=\"" + ksguidLexDb + "\"><Name><AUni ws=\"en\">Publications</AUni></Name><DateCreated val=\"" + nowStr + "\" /><DateModified val=\"" + nowStr + "\" /><Depth val=\"1\" /><PreventChoiceAboveLevel val=\"0\" /><IsSorted val=\"True\" /><IsClosed val=\"False\" /><PreventDuplicates val=\"False\" /><PreventNodeChoices val=\"False\" /><UseExtendedFields val=\"False\" /><DisplayOption val=\"0\" /><ItemClsid val=\"7\" /><IsVernacular val=\"False\" /><WsSelector val=\"0\" /><ListVersion val=\"00000000-0000-0000-0000-000000000000\" /><Possibilities><objsur guid=\"" + ksguidMainDictionary + "\" t=\"o\" /></Possibilities></rt>";
                var dtoPub = new DomainObjectDTO(ksguidPubList, "CmPossibilityList", xmlStrPub);

                string xmlStrMD = "<rt guid=\"" + ksguidMainDictionary + "\" class=\"CmPossibility\" ownerguid=\"" + ksguidPubList + "\"><Name><AUni ws=\"en\">Main Dictionary</AUni></Name><Abbreviation><AUni ws=\"en\">Main</AUni></Abbreviation><SortSpec val=\"0\" /><DateCreated val=\"" + nowStr + "\" /><DateModified val=\"" + nowStr + "\" /><ForeColor val=\"0\" /><BackColor val=\"0\" /><UnderColor val=\"0\" /><UnderStyle val=\"0\" /><Hidden val=\"False\" /><IsProtected val=\"True\" /></rt>";
                var    dtoMD    = new DomainObjectDTO(ksguidMainDictionary, "CmPossibility", xmlStrMD);

                domainObjectDtoRepository.Add(dtoMD);
                domainObjectDtoRepository.Add(dtoPub);

                // Make xLexDb own dtoPub
                var xPts = xNode.Element("PublicationTypes");
                if (xPts == null)
                {                   // add one to LexDb
                    xPts = new XElement("PublicationTypes");
                    xPts.Add(DataMigrationServices.CreateOwningObjSurElement(ksguidPubList));
                    xNode.Add(xPts);
                }
                Debug.Assert(xPts != null, "LexDb has no PublicatonTypes and won't accept new ones.");
                dtoLexDb.Xml = xNode.ToString();
                domainObjectDtoRepository.Update(dtoLexDb);
                newElt.Add(DataMigrationServices.CreateReferenceObjSurElement(ksguidMainDictionary));
            }
            else
            {               // already had a publications list - add all to DoNotShowMainEntryIn
                foreach (var xElt in dtoPubList)
                {           // change the t attr to "r" reference instead of "o" own.
                    var xPubRef = new XElement(xElt);
                    xPubRef.SetAttributeValue("t", "r");
                    newElt.Add(xPubRef);
                }
            }
            foreach (var dto in domainObjectDtoRepository.AllInstancesSansSubclasses("LexEntry"))
            {
                // (WRONG) The ExcludeAsHeadword element only appears when @val="true" unless played with in a text editor
                // NB: The above statement is simply not true (RBR).
                // FW 7 writes out all primitive data properties.
                // The FW 6-FW7 migrator doesn't add them,
                // but FW 7 writes them the next time an object gets changed.
                var xElt       = XElement.Parse(dto.Xml);
                var exHeadword = xElt.Element("ExcludeAsHeadword");
                if (exHeadword == null)
                {
                    continue;
                }
                XAttribute XAval = exHeadword.Attribute("val");
                // It must be upper-case, since that is what is output.
                if (XAval.Value == "True")
                {                       // Add all publications from the list to this property
                    xElt.Add(new XElement(newElt));
                }
                exHeadword.Remove();                 // exHeadword.Value may be True, False or invalid
                dto.Xml = xElt.ToString();
                domainObjectDtoRepository.Update(dto);
            }
            DataMigrationServices.IncrementVersionNumber(domainObjectDtoRepository);
        }
コード例 #42
0
		private void FixOwnershipOfSubtypes(IDomainObjectDTORepository repoDto)
		{
			var types = repoDto.AllInstancesWithSubclasses("LexEntryType");
			var cFixedFirst = 0;
			foreach (var dto in types)
			{
				var xml = dto.Xml;
				var fFixed = false;
				foreach (var badGuid in m_mapBadGoodGuids.Keys)
				{
					if (xml.Contains(badGuid))
					{
						var bad = String.Format("guid=\"{0}\"", badGuid);
						var good = String.Format("guid=\"{0}\"", m_mapBadGoodGuids[badGuid]);
						xml = xml.Replace(bad, good);
						var bad2 = String.Format("guid='{0}'", badGuid);
						var good2 = String.Format("guid='{0}'", m_mapBadGoodGuids[badGuid]);
						xml = xml.Replace(bad2, good2);	// probably pure paranoia...
						fFixed = true;
					}
				}
				if (fFixed)
				{
					dto.Xml = xml;
					repoDto.Update(dto);
					++cFixedFirst;
				}
				var cFixed = 0;
				foreach (var dtoSub in repoDto.GetDirectlyOwnedDTOs(dto.Guid))
				{
					DomainObjectDTO dtoOwner;
					if (!repoDto.TryGetOwner(dtoSub.Guid, out dtoOwner) || dtoOwner != dto)
					{
						// we have a broken ownership link -- fix it!
						var xeSub = XElement.Parse(dtoSub.Xml);
						var xaOwner = xeSub.Attribute("ownerguid");
						if (xaOwner == null)
							xeSub.Add(new XAttribute("ownerguid", dto.Guid));
						else
							xaOwner.Value = dto.Guid;
						dtoSub.Xml = xeSub.ToString();
						repoDto.Update(dtoSub);
						++cFixed;
					}
				}
			}
		}
コード例 #43
0
		private static List<KeyValuePair<byte[], XElement>> ProcessDiscourseData(IDomainObjectDTORepository dtoRepos,
			IDictionary<string, SortedList<int, byte[]>> paraToOldSegments,
			IEnumerable<byte[]> oldCCRs,
			IDictionary<string, byte[]> oldCCAs,
			IDictionary<Guid, Guid> ccaGuidMap) // Key is old CCA guid. Value is new CCA guid.
		{
			// Make a mapping between old CCA anns and new ConstChartWordGroup objects (both XElements),
			// which are the ones where the old ann had twfics in AppliesTo.
			// These will be fed into the code that converts the twfics,
			// so as to have access to the right conversion context
			// (i.e., be able to get at the Segment and start/end indices for the twfics).
			var halfBakedCcwgItems = new List<KeyValuePair<byte[], XElement>>();

			// Map between old CCR ann guid and new CCR guid, so code in here can keep track of them.
			// Key is the original CCR guid. Value is the new CCR guid.
			//var ccrRowsGuidMap = new Dictionary<string, string>();
			// Key is the new CCR guid. Value is the guid of its new owning chart.
			var ccrOwnerGuidMap = new Dictionary<Guid, Guid>();

			// Migrate the DsConstChart(s).
			foreach (var chartDto in dtoRepos.AllInstancesSansSubclasses("DsConstChart"))
			{
				var chartElement = XElement.Parse(chartDto.Xml);

				foreach (var objsurElement in chartElement.Element("DsConstChart").Elements("Rows").Elements("objsur"))
				{
					// Change to owning.
					objsurElement.Attribute("t").Value = "o";

					// Change the guid.
					var guidAttr = objsurElement.Attribute("guid");
					var newCCRGuid = ccaGuidMap[new Guid(guidAttr.Value)];
					// Remember the owner guid (Chart) for the new CCR guid.
					// Key is the new guid for the new CCR.
					// Value is the owning chart.
					ccrOwnerGuidMap.Add(newCCRGuid, new Guid(chartDto.Guid));
					guidAttr.Value = newCCRGuid.ToString().ToLowerInvariant();
				}

				// Tell dto repos of the modification of the chart.
				chartDto.Xml = chartElement.ToString();
				dtoRepos.Update(chartDto);
			}

			// Migrate the CCR and CCA annotations.
			foreach (var oldCCR in oldCCRs)
			{
				// Collect up the inner class-level elements.
				var cmAnnotationBounds = new ElementBounds(oldCCR, s_tagsCmAnnotation);
				// May be null.
				var oldCompDetailsBounds = new ElementBounds(oldCCR, s_tagsCompDetails,
					cmAnnotationBounds.BeginTagOffset, cmAnnotationBounds.EndTagOffset);
				var oldTextBounds = new ElementBounds(oldCCR, s_tagsText,
					cmAnnotationBounds.BeginTagOffset, cmAnnotationBounds.EndTagOffset);
				// oldCommentBounds is unused. Hopefully by design?!
				//var oldCommentBounds = new ElementBounds(oldCCR, s_tagsComment,
				//    cmAnnotationBounds.BeginTagOffset, cmAnnotationBounds.EndTagOffset);
				// May be null, or at least have no 'objsur' elements.
				var refsFromAppliesTo = GetAppliesToObjsurGuids(oldCCR);

				// Try to make a Notes element. It may be null.
				XElement notesElement = null;
				if (oldTextBounds.IsValid)
				{
					// Get the StText dto and element.
					var stTextGuid = GetObjsurGuid(oldCCR, oldTextBounds.BeginTagOffset, oldTextBounds.EndTagOffset);
					if (!String.IsNullOrEmpty(stTextGuid))
					{
						var stTextDto = dtoRepos.GetDTO(stTextGuid);
						var stTextBounds = new ElementBounds(stTextDto.XmlBytes, s_tagsStText);
						var paragraphsBounds = new ElementBounds(stTextDto.XmlBytes, s_tagsParagraphs,
							stTextBounds.BeginTagOffset, stTextBounds.EndTagOffset);
						// See if stTextElement has any paras (StTxtPara)
						if (paragraphsBounds.IsValid)
						{
							// Get the first para.
							var firstParaGuid = GetObjsurGuid(stTextDto.XmlBytes,
								paragraphsBounds.BeginTagOffset, paragraphsBounds.EndTagOffset);
							if (!String.IsNullOrEmpty(firstParaGuid))
							{
								var firstParaDto = dtoRepos.GetDTO(firstParaGuid);
								var stTxtParaBounds = new ElementBounds(firstParaDto.XmlBytes,
									s_tagsStTxtPara);
								var contentsBounds = new ElementBounds(firstParaDto.XmlBytes,
									s_tagsContents,
									stTxtParaBounds.BeginTagOffset, stTxtParaBounds.EndTagOffset);
								var strBounds = new ElementBounds(firstParaDto.XmlBytes, s_tagsStr,
									contentsBounds.BeginTagOffset, contentsBounds.EndTagOffset);
								// See if it has any Contents.
								if (strBounds.IsValid)
								{
									// Move the Contents into a new Notes element.
									notesElement = new XElement("Notes",
										XElement.Parse(Encoding.UTF8.GetString(firstParaDto.XmlBytes,
											strBounds.BeginTagOffset, strBounds.Length)));
								}
							}
						}
					}
				}

				// Deal with 'ClauseType' property.
				var clauseTypeElement = new XElement("ClauseType",
					new XAttribute("val", "0"));
				// Deal with 'ClauseType' property.
				var endParagraphElement = new XElement("EndParagraph",
					new XAttribute("val", "False"));
				// Deal with 'ClauseType' property.
				var endSentenceElement = new XElement("EndSentence",
					new XAttribute("val", "False"));
				// Deal with 'ClauseType' property.
				var startDependentClauseGroupElement = new XElement("StartDependentClauseGroup",
					new XAttribute("val", "False"));
				// Deal with 'ClauseType' property.
				var endDependentClauseGroupElement = new XElement("EndDependentClauseGroup",
					new XAttribute("val", "False"));
				// See if some optional stuff in 'oldCompDetailsElement' will change it.
				var uniBounds = new ElementBounds(oldCCR, s_tagsUni,
					oldCompDetailsBounds.BeginTagOffset, oldCompDetailsBounds.EndTagOffset);
				if (uniBounds.IsValid)
				{
					// Turn its pseudo-xml string content into a real XElement.
					// It's string won't have angle brackets, so turn the entities into '<' and '>'
					// <CompDetails><Uni>&lt;ccinfo endSent="true"/&gt;</Uni></CompDetails>
					var ichMin = uniBounds.BeginTagOffset + s_tagsUni.BeginTag.Length;
					var ichLim = uniBounds.EndTagOffset;
					var cch = ichLim - ichMin;
					var details = Encoding.UTF8.GetString(oldCCR, ichMin, cch);
					if (details.Contains("&"))
						details = XmlUtils.DecodeXmlAttribute(details);
					var compDetailsElement = XElement.Parse(details);
					var optionalAttr = compDetailsElement.Attribute("dependent");
					var foundOverride = false;
					if (optionalAttr != null && optionalAttr.Value.ToLower() == "true")
					{
						clauseTypeElement.Attribute("val").Value = "1";
						foundOverride = true;
					}
					optionalAttr = compDetailsElement.Attribute("song");
					if (!foundOverride && optionalAttr != null && optionalAttr.Value.ToLower() == "true")
					{
						clauseTypeElement.Attribute("val").Value = "2";
						foundOverride = true;
					}
					optionalAttr = compDetailsElement.Attribute("speech");
					if (!foundOverride && optionalAttr != null && optionalAttr.Value.ToLower() == "true")
					{
						clauseTypeElement.Attribute("val").Value = "3";
					}
					// No more ClauseType attrs.
					// Move on to the other four optional boolean attrs.
					optionalAttr = compDetailsElement.Attribute("endSent");
					if (optionalAttr != null && optionalAttr.Value.ToLower() == "true")
						endSentenceElement.Attribute("val").Value = "True";

					optionalAttr = compDetailsElement.Attribute("endPara");
					if (optionalAttr != null && optionalAttr.Value.ToLower() == "true")
						endParagraphElement.Attribute("val").Value = "True";

					optionalAttr = compDetailsElement.Attribute("firstDep");
					if (optionalAttr != null && optionalAttr.Value.ToLower() == "true")
						startDependentClauseGroupElement.Attribute("val").Value = "True";

					optionalAttr = compDetailsElement.Attribute("endDep");
					if (optionalAttr != null && optionalAttr.Value.ToLower() == "true")
						endDependentClauseGroupElement.Attribute("val").Value = "True";
				}

				// Required 'Label' prop, which comes from the old 'Comment'
				// May be null, or at least have no 'objsur' elements.
				var enAltBounds = GetEnglishCommentBounds(oldCCR,
					cmAnnotationBounds.BeginTagOffset, cmAnnotationBounds.EndTagOffset);
				var enAlt = Encoding.UTF8.GetString(oldCCR, enAltBounds.BeginTagOffset, enAltBounds.Length);
				var enAltElement = XElement.Parse(enAlt);
				// Convert it to "Str" element with no "ws" attr.
				enAltElement.Name = "Str";
				enAltElement.Attribute("ws").Remove();

				// Create new ConstChartRow class (XElement & DTO).
				var oldGuid = GetGuid(oldCCR);
				var newGuid = ccaGuidMap[new Guid(oldGuid)];
				var owningGuid = ccrOwnerGuidMap[newGuid];
				ccrOwnerGuidMap.Remove(newGuid);
				const string className = "ConstChartRow";
				var newCCRElement = new XElement("rt",
					new XAttribute("class", className),
					new XAttribute("guid", newGuid),
					new XAttribute("ownerguid", owningGuid),
					new XElement("CmObject"),
					new XElement(className,
						notesElement, // May be null.
						clauseTypeElement,
						endParagraphElement,
						endSentenceElement,
						startDependentClauseGroupElement,
						endDependentClauseGroupElement,
						new XElement("Label", enAltElement),
						AddCells(dtoRepos,
							paraToOldSegments,
							halfBakedCcwgItems, refsFromAppliesTo, oldCCAs, ccaGuidMap, newGuid.ToString().ToLowerInvariant())));

				// Add DTO to repos.
				dtoRepos.Add(new DomainObjectDTO(newGuid.ToString().ToLowerInvariant(), className, newCCRElement.ToString()));
			}

			return halfBakedCcwgItems;
		}
コード例 #44
0
		private void ChangeInvalidGuid(IDomainObjectDTORepository repoDto, LexTypeInfo info,
			string name, string guidStd)
		{
			var xaGuid = info.XmlElement.Attribute("guid");
			if (xaGuid == null)
				throw new Exception("The object does not have a guid -- this is impossible!");
			xaGuid.SetValue(guidStd);
			var guidBad = info.DTO.Guid;
			if (!m_mapBadGoodGuids.ContainsKey(guidBad))
				m_mapBadGoodGuids.Add(guidBad, guidStd);
			var className = info.DTO.Classname;
			repoDto.Remove(info.DTO);
			info.DTO = new DomainObjectDTO(guidStd, className, info.XmlElement.ToString());
			repoDto.Add(info.DTO);
			// Fix the owning reference (but only if it's one of the two lists, because otherwise
			// it might be contained in a LexTypeInfo that hasn't yet been processed).
			var bad = String.Format("guid=\"{0}\"", guidBad);
			var good = String.Format("guid=\"{0}\"", guidStd);
			var bad2 = String.Format("guid='{0}'", guidBad);	// probably pure paranoia...
			var good2 = String.Format("guid='{0}'", guidStd);
			DomainObjectDTO dtoOwner;
			if (repoDto.TryGetOwner(info.DTO.Guid, out dtoOwner) && dtoOwner.Classname == "CmPossibilityList")
			{
				dtoOwner.Xml = dtoOwner.Xml.Replace(bad, good).Replace(bad2, good2);
				repoDto.Update(dtoOwner);
			}
			// Fix any references from LexEntryRef objects.
			foreach (var dtoRef in repoDto.AllInstancesWithSubclasses("LexEntryRef"))
			{
				var xml = dtoRef.Xml;
				if (xml.Contains(guidBad))
				{
					dtoRef.Xml = xml.Replace(bad, good).Replace(bad2, good2);
					repoDto.Update(dtoRef);
				}
			}
			m_mapNameGuid.Remove(name);
			m_mapGuidName.Remove(guidStd);
		}
コード例 #45
0
		private void FixOrAddMissingTypes(IDomainObjectDTORepository repoDto, IEnumerable<LexTypeInfo> extraTypes)
		{
			foreach (var info in extraTypes)
			{
				var fChanged = false;
				foreach (var xeAUni in info.XmlElement.XPathSelectElements("Name/AUni"))
				{
					var xaWs = xeAUni.Attribute("ws");
					if (xaWs == null || xaWs.Value.ToLowerInvariant() != "en")
						continue;
					var name = xeAUni.Value;
					string guidStd;
					if (!m_mapNameGuid.TryGetValue(name, out guidStd))
						continue;
					// We need to change the guid of this dto from 'guid to 'guidStd
					ChangeInvalidGuid(repoDto, info, name, guidStd);
				}
				var xeProt = info.XmlElement.XPathSelectElement("IsProtected");
				if (xeProt == null)
				{
					info.XmlElement.Add(new XElement("IsProtected", new XAttribute("val", "true")));
					fChanged = true;
				}
				else
				{
					var xaVal = xeProt.Attribute("val");
					if (xaVal == null)
					{
						xeProt.Add(new XAttribute("val", "true"));
						fChanged = true;
					}
					else if (xaVal.Value.ToLowerInvariant() != "true")
					{
						xaVal.SetValue("true");
						fChanged = true;
					}
				}
				if (fChanged)
				{
					info.DTO.Xml = info.XmlElement.ToString();
					repoDto.Update(info.DTO);
				}
			}

			if (m_mapNameGuid.Count > 0)
			{
				BuildNewTypeMaps();
				var newTypes = new HashSet<DomainObjectDTO>();
				foreach (var guid in m_mapGuidName.Keys)
				{
					// We need to create this LexEntryType!
					var rgNewDtos = m_mapGuidNewDtos[guid];
					foreach (var info in rgNewDtos)
					{
						var dto = new DomainObjectDTO(info.Guid, info.ClassName, info.Xml);
						repoDto.Add(dto);
						if (info.ClassName == "LexEntryType")
							newTypes.Add(dto);

					}
				}
				foreach (var dto in newTypes)
				{
					var dtoOwner = repoDto.GetOwningDTO(dto);
					var xeOwner = XElement.Parse(dtoOwner.Xml);
					XElement xePoss = null;
					if (dtoOwner.Classname == "CmPossibilityList")
					{
						xePoss = xeOwner.Element("Possibilities");
						if (xePoss == null)
						{
							xePoss = new XElement("Possibilities");
							xeOwner.Add(xePoss);
						}
					}
					else if (dtoOwner.Classname == "LexEntryType")
					{
						xePoss = xeOwner.Element("SubPossibilities");
						if (xePoss == null)
						{
							xePoss = new XElement("SubPossibilities");
							xeOwner.Add(xePoss);
						}
					}
					if (xePoss != null)
					{
						var fNeeded = true;
						foreach (var objsur in xePoss.Elements("objsur"))
						{
							var xaGuid = objsur.Attribute("guid");
							if (xaGuid == null)
								throw new Exception("missing guid in an objsur element");
							if (xaGuid.Value.Equals(dto.Guid, StringComparison.OrdinalIgnoreCase))
							{
								fNeeded = false;
								break;
							}
						}
						if (fNeeded)
						{
							xePoss.Add(DataMigrationServices.CreateOwningObjSurElement(dto.Guid));
							dtoOwner.Xml = xeOwner.ToString();
							repoDto.Update(dtoOwner);
						}
					}
				}
			}
		}
コード例 #46
0
        public void PerformMigration(IDomainObjectDTORepository repoDto)
        {
            DataMigrationServices.CheckVersionNumber(repoDto, 7000060);

            // Step 1.A. & 3.
            //var unownedGonerCandidates = new List<DomainObjectDTO>();
            //unownedGonerCandidates.AddRange(repoDto.AllInstancesSansSubclasses("CmBaseAnnotation"));
            //unownedGonerCandidates.AddRange(repoDto.AllInstancesSansSubclasses("CmIndirectAnnotation"));
            //unownedGonerCandidates.AddRange(repoDto.AllInstancesSansSubclasses("StStyle"));
            //unownedGonerCandidates.AddRange(repoDto.AllInstancesSansSubclasses("StText"));
            //var unownedGoners = new List<DomainObjectDTO>();
            //foreach (var domainObjectDto in unownedGonerCandidates)
            //{
            //    DomainObjectDTO ownerDto;
            //    repoDto.TryGetOwner(domainObjectDto.Guid, out ownerDto);
            //    if (ownerDto != null)
            //        continue;
            //    unownedGoners.Add(domainObjectDto);
            //}
            //foreach (var unownedGoner in unownedGoners)
            //{
            //    DataMigrationServices.RemoveIncludingOwnedObjects(repoDto, unownedGoner, false);
            //}

            // Step 1.B.
            foreach (var resourceDto in repoDto.AllInstancesSansSubclasses("CmResource"))
            {
                var resourceElement     = XElement.Parse(resourceDto.Xml);
                var resourceNameElement = resourceElement.Element("Name");
                if (resourceNameElement == null)
                {
                    continue;
                }
                var uniElement = resourceNameElement.Element("Uni");
                if (uniElement == null)
                {
                    continue;
                }
                string oldVersion;
                switch (uniElement.Value)
                {
                case "TeStyles":
                    oldVersion = "700176e1-4f42-4abd-8fb5-3c586670085d";
                    break;

                case "FlexStyles":
                    oldVersion = "13c213b9-e409-41fc-8782-7ca0ee983b2c";
                    break;

                default:
                    continue;
                }
                var versionElement = resourceElement.Element("Version");
                if (versionElement == null)
                {
                    resourceElement.Add(new XElement("Version", new XAttribute("val", oldVersion)));
                }
                else
                {
                    versionElement.Attribute("val").Value = oldVersion;
                }
                resourceDto.Xml = resourceElement.ToString();
                repoDto.Update(resourceDto);
            }

            // Step 2.
            var mdc = repoDto.MDC;

            foreach (var clid in mdc.GetClassIds())
            {
                if (mdc.GetAbstract(clid))
                {
                    continue;
                }

                var className = mdc.GetClassName(clid);
                foreach (var atomicPropId in mdc.GetFields(clid, true, (int)CellarPropertyTypeFilter.AllAtomic))
                {
                    var propName         = mdc.GetFieldName(atomicPropId);
                    var isCustomProperty = mdc.IsCustom(atomicPropId);
                    foreach (var dto in repoDto.AllInstancesSansSubclasses(className))
                    {
                        var element     = XElement.Parse(dto.Xml);
                        var propElement = isCustomProperty
                                                                                          ? (element.Elements("Custom").Where(customPropElement => customPropElement.Attribute("name").Value == propName)).FirstOrDefault()
                                                                                          : element.Element(propName);
                        if (propElement == null || !propElement.HasElements)
                        {
                            continue;
                        }

                        var objsurElements = propElement.Elements("objsur").ToList();
                        if (objsurElements.Count <= 1)
                        {
                            continue;
                        }

                        // Remove all but first one of them.
                        propElement.RemoveNodes();
                        propElement.Add(objsurElements[0]);
                        dto.Xml = element.ToString();
                        repoDto.Update(dto);
                    }
                }
            }

            // Step 4.
            DataMigrationServices.Delint(repoDto);

            DataMigrationServices.IncrementVersionNumber(repoDto);
        }
コード例 #47
0
		/// <summary>
		/// The weather list is used, so convert it to a custom (unowned) list, create a new
		/// custom field for RnGenericRec elements, and convert any Weather elements to that
		/// new custom field.
		/// </summary>
		private void ConvertWeatherToCustomListAndField(IDomainObjectDTORepository repoDTO)
		{
			// Change the Weather list to being unowned.
			DomainObjectDTO dtoLP = null;
			foreach (var dto in repoDTO.AllInstancesWithSubclasses("LangProject"))
			{
				dtoLP = dto;
				break;
			}
			string sWeatherListGuid = RemoveWeatherConditionsElement(dtoLP).ToLowerInvariant();
			repoDTO.Update(dtoLP);
			DomainObjectDTO dtoWeatherList = null;
			foreach (var dto in repoDTO.AllInstancesWithSubclasses("CmPossibilityList"))
			{
				if (dto.Guid.ToLowerInvariant() == sWeatherListGuid)
				{
					dtoWeatherList = dto;
					break;
				}
			}
			dtoWeatherList.Xml = RemoveOwnerGuid(dtoWeatherList.Xml);
			repoDTO.Update(dtoWeatherList);

			// Create the custom field.
			string fieldName = "Weather";
			while (repoDTO.IsFieldNameUsed("RnGenericRec", fieldName))
				fieldName = fieldName + "A";
			repoDTO.CreateCustomField("RnGenericRec", fieldName, SIL.CoreImpl.CellarPropertyType.ReferenceCollection,
				CmPossibilityTags.kClassId, "originally a standard part of Data Notebook records",
				WritingSystemServices.kwsAnals, new Guid(sWeatherListGuid));

			string customStart = String.Format("<Custom name=\"{0}\">", fieldName);

			// Remove any empty Weather elements in the RnGenericRec objects, and convert
			// nonempty ones to custom elements.
			foreach (var dto in repoDTO.AllInstancesWithSubclasses("RnGenericRec"))
			{
				string sXml = dto.Xml;
				int idx = sXml.IndexOf("<Weather");
				if (idx > 0)
				{
					string sXmlT = RemoveEmptyWeather(sXml, idx);
					if (sXmlT == sXml)
					{
						sXmlT = sXml.Replace("<Weather>", customStart);
						sXmlT = sXmlT.Replace("</Weather>", "</Custom>");
					}
					dto.Xml = sXmlT;
					repoDTO.Update(dto);
				}
			}
		}
コード例 #48
0
		private static XElement AddSegmentAnalyses(
			IDomainObjectDTORepository dtoRepos,
			IEnumerable<KeyValuePair<byte[], XElement>> halfBakedCcwgItemsForCurrentPara,
			byte[] oldSegElement,
			IDictionary<int, byte[]> xficsForCurrentPara,
			ICollection<byte[]> oldTextTags,
			string newSegmentGuid,
			bool isLastOldSegment,
			DomainObjectDTO paraDto)
		{
			XElement retval = null;

			var oldSegBeginOffset = GetBeginOffset(oldSegElement);
			var oldSegEndOffset = GetEndOffset(oldSegElement);

			var xficsForCurrentOldSegment = new SortedList<int, byte[]>();
			var halfBakedCcwgsForCurrentOldSegment = new List<XElement>();
			if (xficsForCurrentPara != null)
			{
				foreach (var kvp in xficsForCurrentPara)
				{
					var xficGuid = GetGuid(kvp.Value);
					var beginOffset = kvp.Key;

					// Try to find a CCWG that has a matching instanceOfGuid.
					XElement halfBakedCcwg = null;
					foreach (var halfBakedKvp in halfBakedCcwgItemsForCurrentPara)
					{
						// NB: halfBakedKvp.Value.Element("ConstChartWordGroup").Element("BeginAnalysisIndex").Attribute("val").Value.ToLower()
						// This is the 'InstanceOf' guid of the xfic, not the xfic's guid.
						if (
							halfBakedKvp.Value.Element("ConstChartWordGroup").Element("BeginAnalysisIndex").Attribute(
								"val").Value.ToLower() != xficGuid)
							continue;

						// If there happen to be more than one CCWG pointing to the same xfic, only one gets 'finished'!
						halfBakedCcwg = halfBakedKvp.Value;
						break;
					}

					if (beginOffset >= oldSegBeginOffset && beginOffset < oldSegEndOffset)
					{
						xficsForCurrentOldSegment.Add(beginOffset, kvp.Value);
						if (halfBakedCcwg != null)
							halfBakedCcwgsForCurrentOldSegment.Add(halfBakedCcwg);
					}
					else if (isLastOldSegment)
					{
						if (halfBakedCcwg != null)
							halfBakedCcwgsForCurrentOldSegment.Add(halfBakedCcwg);
						xficsForCurrentOldSegment.Add(beginOffset, kvp.Value);
					}
				}
			}

			if (xficsForCurrentOldSegment.Count > 0)
			{
				foreach (var key in xficsForCurrentOldSegment.Keys)
					xficsForCurrentPara.Remove(key);

				// The one returned element is "Analyses" (or null, if no twfics/pfics).
				// It will have one, or more, 'objsur' type 'r' elements in it.
				// The 'Analyses' property is a seq,
				// which is why is xficsForCurrentOldSegment is sorted the BeginOffset of the contained twfics/pfics.

				// All xfics will have an 'InstanceOf' by now, even pfics.
				// The pfics had a new InstanceOf prop set earlier
				// (or were removed, if InstanceOf could not be set),
				// and twfics with no InstanceOf prop were filtered out earlier.
				retval = new XElement("Analyses",
					from xfix in xficsForCurrentOldSegment.Values
					select DataMigrationServices.CreateReferenceObjSurElement(GetInstanceOfGuid(xfix)));

				// Finish converting half-baked CCWG stuff.
				if (halfBakedCcwgsForCurrentOldSegment.Count > 0)
				{
					var allOldXficGuids = (from xfix in xficsForCurrentOldSegment.Values
										   select GetGuid(xfix).ToLower()).ToList();
					foreach (var halfBakedCcwg in halfBakedCcwgsForCurrentOldSegment)
					{
						// Fix up halfbaked CCWG items here.
						var innerElement = halfBakedCcwg.Element("ConstChartWordGroup");
						// NB: The guids temporarily stored in the begin/end index props are for
						// the xfic guid, but we want to look up the index of its InstanceOf property,
						// which will be what is actually in the new "Analyses" prop of the new Segment.
						var guidAttr = innerElement.Element("BeginAnalysisIndex").Attribute("val");
						guidAttr.Value = allOldXficGuids.IndexOf(guidAttr.Value.ToLower()).ToString();
						guidAttr = innerElement.Element("EndAnalysisIndex").Attribute("val");
						guidAttr.Value = allOldXficGuids.IndexOf(guidAttr.Value.ToLower()).ToString();
						// NB: The recently created CCWG has already been added to dto repos,
						// so the only remaining task is to update the xml on the CCWG dto.
						var dto = dtoRepos.GetDTO(GetGuid(halfBakedCcwg));
						dto.Xml = halfBakedCcwg.ToString();
					}
				}

				// Find and convert any any old Text Tag indirect annotations for this segment.
				// NB: xficsForCurrentOldSegment.Values may have pfics,
				// and we don't want those here.
				// oldTextTags is all old TextTag annotations for everything.
				// This variable holds the twfics (in BeginOffset order),
				// where pfics are removed from xficsForCurrentOldSegment.
				var twficBeginOffsetListForCurrentSegment = new List<int>();
				var twficGuidListForCurrentSegment = new List<string>();
				var twficElementListForCurrentSegment = new List<byte[]>();
				var twficMap = new Dictionary<string, byte[]>();
				foreach (var twficKvp in from xficKvp in xficsForCurrentOldSegment
										 where GetAnnotationTypeGuid(xficKvp.Value) == DataMigrationServices.kTwficAnnDefnGuid
										 select xficKvp)
				{
					twficBeginOffsetListForCurrentSegment.Add(twficKvp.Key);
					var twficGuid = GetGuid(twficKvp.Value);
					twficGuidListForCurrentSegment.Add(twficGuid);
					twficElementListForCurrentSegment.Add(twficKvp.Value);
					twficMap.Add(twficGuid, twficKvp.Value);
				}

				var textTagElementsForCurrentSegment = new List<byte[]>();
				foreach (var oldTextTagAnnElement in oldTextTags)
				{
					// Find the ones that are used in the current segment,
					// and add them to textTagElementsForCurrentSegment.

					var appliesToGuids = new List<string>();
					foreach (var guid in GetAppliesToObjsurGuids(oldTextTagAnnElement))
					{
						if (twficGuidListForCurrentSegment.Contains(guid))
							appliesToGuids.Add(guid);
					}
					if (appliesToGuids.Count() <= 0)
						continue;

					// Store them for a while.
					textTagElementsForCurrentSegment.Add(oldTextTagAnnElement);

					// Get the index of the First twfic in appliesToGuids collection (which may hold pfics)
					// and the index of the Last twfic in appliesToGuids collection (which may hold pfics).
					var beginIdx = 0;
					for (var i = 0; i < appliesToGuids.Count(); ++i)
					{
						var currentXfixGuid = appliesToGuids[i].ToLower();
						byte[] currentTwficElement;
						if (!twficMap.TryGetValue(currentXfixGuid, out currentTwficElement))
							continue;

						beginIdx = xficsForCurrentOldSegment.IndexOfValue(currentTwficElement);
						break;
					}
					var endIdx = 0;
					for (var i = appliesToGuids.Count() - 1; i > -1; --i)
					{
						var currentXfixGuid = appliesToGuids[i].ToLower();
						byte[] currentTwficElement;
						if (!twficMap.TryGetValue(currentXfixGuid, out currentTwficElement))
							continue;

						endIdx = xficsForCurrentOldSegment.IndexOfValue(currentTwficElement);
						break;
					}

					var owningStText = dtoRepos.GetOwningDTO(paraDto);
					var newTextTagGuid = Guid.NewGuid().ToString().ToLower();
					var newTextTagElement = new XElement("rt",
						new XAttribute("class", "TextTag"),
						new XAttribute("guid", newTextTagGuid),
						new XAttribute("ownerguid", owningStText.Guid.ToLower()),
						new XElement("CmObject"),
						new XElement("TextTag",
							new XElement("BeginSegment", DataMigrationServices.CreateReferenceObjSurElement(newSegmentGuid)),
							new XElement("EndSegment", DataMigrationServices.CreateReferenceObjSurElement(newSegmentGuid)),
							new XElement("BeginAnalysisIndex", new XAttribute("val", beginIdx)),
							new XElement("EndAnalysisIndex", new XAttribute("val", endIdx)),
							new XElement("Tag", DataMigrationServices.CreateReferenceObjSurElement(GetInstanceOfGuid(oldTextTagAnnElement)))));

					// Add new DTO to repos.
					var newTextTagDto = new DomainObjectDTO(newTextTagGuid, "TextTag", newTextTagElement.ToString());
					dtoRepos.Add(newTextTagDto);
					// Add new TextTag to owning prop on owner as objsur element.
					var owningStTextElement = XElement.Parse(owningStText.Xml);
					var innerStTextElement = owningStTextElement.Element("StText");
					var tagsPropElement = innerStTextElement.Element("Tags");
					if (tagsPropElement == null)
					{
						tagsPropElement = new XElement("Tags");
						innerStTextElement.Add(tagsPropElement);
					}
					tagsPropElement.Add(DataMigrationServices.CreateOwningObjSurElement(newTextTagGuid));
					// Tell repos of the modification.
					owningStText.Xml = owningStTextElement.ToString();
					dtoRepos.Update(owningStText);
				}
				// Remove current text tags from input list
				foreach (var currentTextTagElement in textTagElementsForCurrentSegment)
					oldTextTags.Remove(currentTextTagElement);
			}
			//else
			//{
			//    // No xfics at all, so make sure para is set to be tokenized again.
			//    // Done globally for each Para in ProcessParagraphs
			//    //MarkParaAsNeedingTokenization(dtoRepos, paraDto, paraElement);
			//}

			return retval;
		}