Exemple #1
0
        public void RefColPropertiesAreChangedToRefseq()
        {
            var rt = new XElement(SharedConstants.RtTag,
                                  new XAttribute(SharedConstants.Class, "CmPossibility"),
                                  new XAttribute(SharedConstants.GuidStr, "c1ed6dc8-e382-11de-8a39-0800200c9a66"),
                                  new XElement("Restrictions",
                                               BaseDomainServices.CreateObjSurElement("0039739a-7fcf-4838-8b75-566b8815a29f", "r"),
                                               BaseDomainServices.CreateObjSurElement("00b560a2-9af0-4185-bbeb-c0eb3c5e3769", "r")));
            var classData = new Dictionary <string, SortedDictionary <string, byte[]> >();
            var data      = new SortedDictionary <string, byte[]>
            {
                { "c1ed6dc8-e382-11de-8a39-0800200c9a66", SharedConstants.Utf8.GetBytes(rt.ToString()) }
            };

            classData.Add("CmPossibility", data);
            var guidToClassMapping = new Dictionary <string, string> {
                { "c1ed6dc8-e382-11de-8a39-0800200c9a66", "CmPossibility" }
            };

            CmObjectNestingService.NestObject(false, rt,
                                              classData,
                                              guidToClassMapping);
            var result = rt.ToString();

            Assert.IsTrue(result.Contains(SharedConstants.Refcol));
        }
Exemple #2
0
        internal static void PushHumptyOffTheWall(IProgress progress, bool writeVerbose, string mainFilePathname)
        {
            Guard.AgainstNull(progress, "progress");
            FileWriterService.CheckFilename(mainFilePathname);

            var rootDirectoryName = Path.GetDirectoryName(mainFilePathname);

            // NB: This is strictly an ordered list of method calls.
            // Don't even 'think' of changing any of them.
            CheckForUserCancelRequested(progress);
            DeleteOldFiles(rootDirectoryName);
            CheckForUserCancelRequested(progress);
            WriteVersionFile(mainFilePathname);
            // Outer Dict has the class name for its key and a sorted (by guid) dictionary as its value.
            // The inner dictionary has a caseless guid as the key and the byte array as the value.
            // (Only has current concrete classes.)
            var classData        = GenerateBasicClassData();
            var wellUsedElements = new Dictionary <string, XElement>
            {
                { SharedConstants.LangProject, null },
                { SharedConstants.LexDb, null }
            };
            var guidToClassMapping = WriteOrCacheProperties(mainFilePathname, classData, wellUsedElements);

            CheckForUserCancelRequested(progress);
            BaseDomainServices.PushHumptyOffTheWall(progress, writeVerbose, rootDirectoryName, wellUsedElements, classData, guidToClassMapping);

#if DEBUG
            // Enable ONLY for testing a round trip.
            // FLExProjectUnifier.PutHumptyTogetherAgain(progress, writeVerbose, mainFilePathname);
#endif
        }
Exemple #3
0
        public void OneItemInCollectionRemains()
        {
            var collData = new XElement("CollectionProperty", BaseDomainServices.CreateObjSurElement("c1ecf889-e382-11de-8a39-0800200c9a66"));

            DataSortingService.SortCollectionProperties(collData);
            Assert.AreEqual("CollectionProperty", collData.Name.LocalName);
            Assert.AreEqual(1, collData.Elements().Count());
            Assert.AreEqual("c1ecf889-e382-11de-8a39-0800200c9a66", collData.Element(SharedConstants.Objsur).Attribute(SharedConstants.GuidStr).Value);
        }
        /// <summary>
        /// Flatten an owned object and add an appropriate objsur to the specified property of the owning object.
        /// </summary>
        internal static void FlattenOwnedObject(string pathname,
                                                SortedDictionary <string, XElement> sortedData,
                                                XElement element, string ownerguid, XContainer owningElement, string propertyName)
        {
            FlattenObjectCore(pathname, sortedData, element, ownerguid);
            // We MUST create the objsur AFTER flattening the object, which may pathologically change its guid.
            var guid = element.Attribute(SharedConstants.GuidStr).Value.ToLowerInvariant();

            BaseDomainServices.RestoreObjsurElement(owningElement, propertyName, BaseDomainServices.CreateObjSurElement(guid));
        }
        internal static void FlattenContext(
            SortedDictionary <string, XElement> highLevelData,
            SortedDictionary <string, XElement> sortedData,
            string linguisticsBaseDir)
        {
            var phonologyDir = Path.Combine(linguisticsBaseDir, SharedConstants.Phonology);

            if (!Directory.Exists(phonologyDir))
            {
                return;
            }

            var langProjElement = highLevelData[SharedConstants.LangProject];
            var currentPathname = Path.Combine(phonologyDir, SharedConstants.PhonologyFeaturesFilename);

            if (File.Exists(currentPathname))
            {
                var phoneFeatSysDoc = XDocument.Load(currentPathname);
                BaseDomainServices.RestoreElement(
                    currentPathname,
                    sortedData,
                    langProjElement, "PhFeatureSystem",
                    phoneFeatSysDoc.Root.Element("FsFeatureSystem"));                     // Owned elment.
            }

            currentPathname = Path.Combine(phonologyDir, SharedConstants.PhonologicalDataFilename);
            if (!File.Exists(currentPathname))
            {
                return;
            }

            var phonDataDoc     = XDocument.Load(currentPathname);
            var phonDataElement = phonDataDoc.Root.Element("PhPhonData");

            BaseDomainServices.RestoreElement(
                currentPathname,
                sortedData,
                langProjElement, "PhonologicalData",
                phonDataElement);                 // Owned elment.

            // Optional PhonRuleFeats list.
            currentPathname = Path.Combine(phonologyDir, SharedConstants.PhonRuleFeaturesFilename);
            if (!File.Exists(currentPathname))
            {
                return;
            }

            var phonRuleFeatsListDoc = XDocument.Load(currentPathname);

            BaseDomainServices.RestoreElement(
                currentPathname,
                sortedData,
                phonDataElement, "PhonRuleFeats",
                phonRuleFeatsListDoc.Root.Element(SharedConstants.CmPossibilityList));                 // Owned elment.
        }
Exemple #6
0
        public void CollectionPropertyIsSorted()
        {
            var collData = new XElement("CollectionProperty",
                                        BaseDomainServices.CreateObjSurElement("c1ecf88b-e382-11de-8a39-0800200c9a66"),
                                        BaseDomainServices.CreateObjSurElement("c1ecf88a-e382-11de-8a39-0800200c9a66"));

            DataSortingService.SortCollectionProperties(collData);
            Assert.AreEqual("CollectionProperty", collData.Name.LocalName);
            Assert.AreEqual(2, collData.Elements().Count());
            Assert.AreEqual("c1ecf88a-e382-11de-8a39-0800200c9a66", collData.Elements().ElementAt(0).Attribute(SharedConstants.GuidStr).Value);
            Assert.AreEqual("c1ecf88b-e382-11de-8a39-0800200c9a66", collData.Elements().ElementAt(1).Attribute(SharedConstants.GuidStr).Value);
        }
        internal static void RemoveBoundedContextData(string pathRoot)
        {
            var generalBaseDir = Path.Combine(pathRoot, SharedConstants.General);

            BaseDomainServices.RemoveBoundedContextDataCore(generalBaseDir);
            var oldLintPathname = Path.Combine(generalBaseDir, "FLExProject.lint");

            if (File.Exists(oldLintPathname + ".ChorusNotes"))
            {
                File.Delete(oldLintPathname + ".ChorusNotes");
            }
        }
Exemple #8
0
        internal static void NestContext(XElement stylesProperty,
                                         string baseDirectory,
                                         IDictionary <string, SortedDictionary <string, byte[]> > classData,
                                         Dictionary <string, string> guidToClassMapping)
        {
            var stylesDir = baseDirectory;             // Just use main folder. // Path.Combine(baseDirectory, SharedConstants.Styles);

            if (!Directory.Exists(stylesDir))
            {
                Directory.CreateDirectory(stylesDir);
            }

            BaseDomainServices.NestStylesPropertyElement(classData, guidToClassMapping, stylesProperty, Path.Combine(stylesDir, StyleFilename));
        }
Exemple #9
0
        private static void DeleteOldFiles(string pathRoot)
        {
            // Wipe out custom props file, as it will be re-created, even if it only has the root element in it.
            var customPropPathname = Path.Combine(pathRoot, SharedConstants.CustomPropertiesFilename);

            if (File.Exists(customPropPathname))
            {
                File.Delete(customPropPathname);
            }
            // Delete ModelVersion file, but it gets rewritten soon.
            var modelVersionPathname = Path.Combine(pathRoot, SharedConstants.ModelVersionFilename);

            if (File.Exists(modelVersionPathname))
            {
                File.Delete(modelVersionPathname);
            }

            // Deletes all files in new locations, except the current ChorusNotes files.
            BaseDomainServices.RemoveDomainData(pathRoot);
        }
Exemple #10
0
 public void RefColElementsRestoredToObjsurElements()
 {
     using (var tempFile = new TempFile())
     {
         var sortedData         = new SortedDictionary <string, XElement>();
         var possibilityElement = new XElement("CmPossibility",
                                               new XAttribute(SharedConstants.GuidStr, "c1ed6dc8-e382-11de-8a39-0800200c9a66"),
                                               new XElement("Restrictions",
                                                            new XElement(SharedConstants.Refcol,
                                                                         BaseDomainServices.CreateAttributes("0039739a-7fcf-4838-8b75-566b8815a29f", "r"),
                                                                         new XElement(SharedConstants.Refcol,
                                                                                      BaseDomainServices.CreateAttributes("00b560a2-9af0-4185-bbeb-c0eb3c5e3769", "r")))));
         CmObjectFlatteningService.FlattenOwnerlessObject(
             tempFile.Path,
             sortedData,
             possibilityElement);
         var restored = sortedData["c1ed6dc8-e382-11de-8a39-0800200c9a66"];
         Assert.IsTrue(restored.ToString().Contains(SharedConstants.Objsur));
     }
 }
        internal static void RemoveBoundedContextData(string pathRoot)
        {
            var linguisticsBaseDir = Path.Combine(pathRoot, SharedConstants.Linguistics);

            BaseDomainServices.RemoveBoundedContextDataCore(linguisticsBaseDir);

            // Remove ChorusNotes files for old lexicon file and old WFI file.
            // Lexicon.lexdb
            var lexiconDir       = Path.Combine(linguisticsBaseDir, SharedConstants.Lexicon);
            var oldNotesPathname = Path.Combine(lexiconDir, "Lexicon.lexdb.ChorusNotes");

            if (File.Exists(oldNotesPathname))
            {
                File.Delete(oldNotesPathname);
            }
            // WordformInventory.inventory
            var inventoryDir = Path.Combine(linguisticsBaseDir, SharedConstants.WordformInventoryRootFolder);

            oldNotesPathname = Path.Combine(inventoryDir, "WordformInventory.inventoryChorusNotes");
            if (File.Exists(oldNotesPathname))
            {
                File.Delete(oldNotesPathname);
            }
        }
Exemple #12
0
        private void AddOwnedObjects()
        {
            // Add two entries, the first one having a nested entry.
            var rtGuid = _rt.Attribute(SharedConstants.GuidStr).Value;
            var data   = new SortedDictionary <string, byte[]>();
            var entry1 = new XElement(SharedConstants.RtTag,
                                      new XAttribute(SharedConstants.Class, "ReversalIndexEntry"),
                                      new XAttribute(SharedConstants.GuidStr, "0039739a-7fcf-4838-8b75-566b8815a29f"),
                                      new XAttribute(SharedConstants.OwnerGuid, rtGuid));

            data.Add("0039739a-7fcf-4838-8b75-566b8815a29f", SharedConstants.Utf8.GetBytes(entry1.ToString()));
            _guidToClassMapping.Add("0039739a-7fcf-4838-8b75-566b8815a29f", "ReversalIndexEntry");
            var subentry1 = new XElement(SharedConstants.RtTag,
                                         new XAttribute(SharedConstants.Class, "ReversalIndexEntry"),
                                         new XAttribute(SharedConstants.GuidStr, "14a6b4bc-1bb3-4c67-b70c-5a195e411e27"),
                                         new XAttribute(SharedConstants.OwnerGuid, "0039739a-7fcf-4838-8b75-566b8815a29f"));

            data.Add("14a6b4bc-1bb3-4c67-b70c-5a195e411e27", SharedConstants.Utf8.GetBytes(subentry1.ToString()));
            _guidToClassMapping.Add("14a6b4bc-1bb3-4c67-b70c-5a195e411e27", "ReversalIndexEntry");
            var entry2 = new XElement(SharedConstants.RtTag,
                                      new XAttribute(SharedConstants.Class, "ReversalIndexEntry"),
                                      new XAttribute(SharedConstants.GuidStr, "00b560a2-9af0-4185-bbeb-c0eb3c5e3769"),
                                      new XAttribute(SharedConstants.OwnerGuid, rtGuid));

            data.Add("00b560a2-9af0-4185-bbeb-c0eb3c5e3769", SharedConstants.Utf8.GetBytes(entry2.ToString()));
            _guidToClassMapping.Add("00b560a2-9af0-4185-bbeb-c0eb3c5e3769", "ReversalIndexEntry");
            _classData.Add("ReversalIndexEntry", data);
            var entriesElement = new XElement("Entries",
                                              BaseDomainServices.CreateObjSurElement("0039739a-7fcf-4838-8b75-566b8815a29f"),
                                              BaseDomainServices.CreateObjSurElement("00b560a2-9af0-4185-bbeb-c0eb3c5e3769"));

            _rt.Add(entriesElement);
            entriesElement = new XElement("Subentries",
                                          BaseDomainServices.CreateObjSurElement("14a6b4bc-1bb3-4c67-b70c-5a195e411e27"));
            entry1.Add(entriesElement);

            // Add the POS list, with two possibilities (own-seq prop).
            const string posListGuid = "fb5e83e5-6576-455d-aba0-0b7a722b9b5d";
            var          posList     = new XElement(SharedConstants.RtTag,
                                                    new XAttribute(SharedConstants.Class, SharedConstants.CmPossibilityList),
                                                    new XAttribute(SharedConstants.GuidStr, posListGuid),
                                                    new XAttribute(SharedConstants.OwnerGuid, rtGuid));
            var pos1 = new XElement(SharedConstants.RtTag,
                                    new XAttribute(SharedConstants.Class, "PartOfSpeech"),
                                    new XAttribute(SharedConstants.GuidStr, "c1ed6dc6-e382-11de-8a39-0800200c9a66"),
                                    new XAttribute(SharedConstants.OwnerGuid, posListGuid),
                                    new XElement("DateCreated", new XAttribute(SharedConstants.Val, "created")));
            var pos2 = new XElement(SharedConstants.RtTag,
                                    new XAttribute(SharedConstants.Class, "PartOfSpeech"),
                                    new XAttribute(SharedConstants.GuidStr, "c1ed6dc7-e382-11de-8a39-0800200c9a66"),
                                    new XAttribute(SharedConstants.OwnerGuid, posListGuid),
                                    new XElement("DateCreated", new XAttribute(SharedConstants.Val, "created")));

            entriesElement = new XElement("Possibilities",
                                          BaseDomainServices.CreateObjSurElement("c1ed6dc6-e382-11de-8a39-0800200c9a66"),
                                          BaseDomainServices.CreateObjSurElement("c1ed6dc7-e382-11de-8a39-0800200c9a66"));
            _guidToClassMapping.Add("c1ed6dc6-e382-11de-8a39-0800200c9a66", "PartOfSpeech");
            _guidToClassMapping.Add("c1ed6dc7-e382-11de-8a39-0800200c9a66", "PartOfSpeech");
            data = new SortedDictionary <string, byte[]>
            {
                { "c1ed6dc6-e382-11de-8a39-0800200c9a66", SharedConstants.Utf8.GetBytes(pos1.ToString()) },
                { "c1ed6dc7-e382-11de-8a39-0800200c9a66", SharedConstants.Utf8.GetBytes(pos2.ToString()) }
            };
            _classData.Add("PartOfSpeech", data);
            posList.Add(entriesElement);

            entriesElement = new XElement("PartsOfSpeech",
                                          BaseDomainServices.CreateObjSurElement(posListGuid));
            _guidToClassMapping.Add(posListGuid, SharedConstants.CmPossibilityList);
            data = new SortedDictionary <string, byte[]>
            {
                { posListGuid, SharedConstants.Utf8.GetBytes(posList.ToString()) }
            };
            _classData.Add(SharedConstants.CmPossibilityList, data);
            _rt.Add(entriesElement);
        }
Exemple #13
0
        internal static void NestContext(string linguisticsBaseDir,
                                         IDictionary <string, XElement> wellUsedElements,
                                         IDictionary <string, SortedDictionary <string, byte[]> > classData,
                                         Dictionary <string, string> guidToClassMapping)
        {
            var textCorpusBaseDir = Path.Combine(linguisticsBaseDir, SharedConstants.TextCorpus);

            if (!Directory.Exists(textCorpusBaseDir))
            {
                Directory.CreateDirectory(textCorpusBaseDir);
            }

            var langProjElement = wellUsedElements[SharedConstants.LangProject];

            // Write Genre list (owning atomic CmPossibilityList)
            FileWriterService.WriteNestedListFileIfItExists(classData, guidToClassMapping,
                                                            langProjElement, SharedConstants.GenreList,
                                                            Path.Combine(textCorpusBaseDir, SharedConstants.GenreListFilename));

            // Write text markup tags list (owning atomic CmPossibilityList)
            FileWriterService.WriteNestedListFileIfItExists(classData, guidToClassMapping,
                                                            langProjElement, SharedConstants.TextMarkupTags,
                                                            Path.Combine(textCorpusBaseDir, SharedConstants.TextMarkupTagsListFilename));

            // Handle the LP TranslationTags prop (OA-CmPossibilityList), if it exists.
            FileWriterService.WriteNestedListFileIfItExists(classData, guidToClassMapping,
                                                            langProjElement, SharedConstants.TranslationTags,
                                                            Path.Combine(textCorpusBaseDir, SharedConstants.TranslationTagsListFilename));

            var texts = classData["Text"];

            if (texts.Count == 0)
            {
                return;                 // No texts to process.
            }
            if (MetadataCache.MdCache.ModelVersion < 7000059)
            {
                // Backwards compatible code.
                var textGuidsInLangProj = BaseDomainServices.GetGuids(langProjElement, "Texts");
                if (textGuidsInLangProj.Count == 0)
                {
                    return;                     //  None owned by lang project. (Some can be owned by RnGenericRec.)
                }
                foreach (var textGuid in textGuidsInLangProj)
                {
                    var rootElement = new XElement("TextInCorpus");
                    var textElement = Utilities.CreateFromBytes(texts[textGuid]);
                    rootElement.Add(textElement);
                    CmObjectNestingService.NestObject(
                        false,
                        textElement,
                        classData,
                        guidToClassMapping);
                    FileWriterService.WriteNestedFile(
                        Path.Combine(textCorpusBaseDir, "Text_" + textGuid.ToLowerInvariant() + "." + SharedConstants.TextInCorpus),
                        rootElement);
                }
                // Remove child objsur nodes from owning LangProg
                langProjElement.Element("Texts").RemoveNodes();
            }
            else
            {
                foreach (var textGuid in texts.Keys.ToArray())                 // Needs a copy, since the dictionary is changed.
                {
                    var rootElement = new XElement("TextInCorpus");
                    var textElement = Utilities.CreateFromBytes(texts[textGuid]);
                    rootElement.Add(textElement);
                    CmObjectNestingService.NestObject(
                        false,
                        textElement,
                        classData,
                        guidToClassMapping);
                    FileWriterService.WriteNestedFile(
                        Path.Combine(textCorpusBaseDir, "Text_" + textGuid.ToLowerInvariant() + "." + SharedConstants.TextInCorpus),
                        rootElement);
                }
            }
        }
Exemple #14
0
        internal static void NestContext(string generalBaseDir,
                                         IDictionary <string, XElement> wellUsedElements,
                                         IDictionary <string, SortedDictionary <string, byte[]> > classData,
                                         Dictionary <string, string> guidToClassMapping)
        {
            var langProjElement = wellUsedElements[SharedConstants.LangProject];

            // LP AnnotationDefs (OA-CmPossibilityList). AnnotationDefs.list]
            FileWriterService.WriteNestedListFileIfItExists(classData,
                                                            guidToClassMapping,
                                                            langProjElement, SharedConstants.AnnotationDefs,
                                                            Path.Combine(generalBaseDir, SharedConstants.AnnotationDefsListFilename));

            // LP Styles (OC-StStyle) is used by everyone, but Scripture, so they go here.
            BaseDomainServices.NestStylesPropertyElement(
                classData,
                guidToClassMapping,
                langProjElement.Element(SharedConstants.Styles),
                Path.Combine(generalBaseDir, SharedConstants.FLExStylesFilename));

            // LP Filters (OC) can go into one filters file here. (FLExFilters.filter: new ext)
            var owningPropElement = langProjElement.Element(SharedConstants.Filters);

            if (owningPropElement != null && owningPropElement.HasElements)
            {
                var root = new XElement(SharedConstants.Filters);
                foreach (var filterObjSurElement in owningPropElement.Elements().ToList())
                {
                    var filterGuid    = filterObjSurElement.Attribute(SharedConstants.GuidStr).Value.ToLowerInvariant();
                    var className     = guidToClassMapping[filterGuid];
                    var filterElement = Utilities.CreateFromBytes(classData[className][filterGuid]);
                    CmObjectNestingService.NestObject(false, filterElement, classData, guidToClassMapping);
                    root.Add(filterElement);
                }
                FileWriterService.WriteNestedFile(Path.Combine(generalBaseDir, SharedConstants.FLExFiltersFilename), root);
                owningPropElement.RemoveNodes();
            }

            // LP Annotations (OC). Who still uses them? If all else fails, or they are used by several BCs, then store them in one file here.
            // [FLExAnnotations.annotation: new ext]
            // OJO! Sig is "CmAnnotation", which is abtract class, so handle like in Discourse-land.
            owningPropElement = langProjElement.Element(SharedConstants.Annotations);
            if (owningPropElement != null && owningPropElement.HasElements)
            {
                var root = new XElement(SharedConstants.Annotations);
                foreach (var annotationObjSurElement in owningPropElement.Elements().ToList())
                {
                    var annotationGuid    = annotationObjSurElement.Attribute(SharedConstants.GuidStr).Value.ToLowerInvariant();
                    var className         = guidToClassMapping[annotationGuid];
                    var annotationElement = Utilities.CreateFromBytes(classData[className][annotationGuid]);
                    CmObjectNestingService.NestObject(false, annotationElement, classData, guidToClassMapping);
                    BaseDomainServices.ReplaceElementNameWithAndAddClassAttribute(SharedConstants.CmAnnotation, annotationElement);
                    root.Add(annotationElement);
                }
                FileWriterService.WriteNestedFile(Path.Combine(generalBaseDir, SharedConstants.FLExAnnotationsFilename), root);
                owningPropElement.RemoveNodes();
            }

            // Some CmPicture instances may not be owned.
            var rootElement     = new XElement(SharedConstants.Pictures);
            var unownedPictures = classData[SharedConstants.CmPicture].Values.Where(listElement => XmlUtils.GetAttributes(listElement, new HashSet <string> {
                SharedConstants.OwnerGuid
            })[SharedConstants.OwnerGuid] == null).ToList();

            foreach (var unownedPictureBytes in unownedPictures)
            {
                var element = Utilities.CreateFromBytes(unownedPictureBytes);
                CmObjectNestingService.NestObject(
                    false,
                    element,
                    classData,
                    guidToClassMapping);
                rootElement.Add(element);
            }
            FileWriterService.WriteNestedFile(Path.Combine(generalBaseDir, SharedConstants.FLExUnownedPicturesFilename), rootElement);

            // No VirtualOrdering instances are owned.
            if (MetadataCache.MdCache.ModelVersion > MetadataCache.StartingModelVersion)
            {
                rootElement = new XElement(SharedConstants.VirtualOrderings);
                foreach (var element in classData[SharedConstants.VirtualOrdering].Values.ToArray().Select(virtualOrderingBytes => Utilities.CreateFromBytes(virtualOrderingBytes)))
                {
                    CmObjectNestingService.NestObject(
                        false,
                        element,
                        classData,
                        guidToClassMapping);
                    rootElement.Add(element);
                }
                FileWriterService.WriteNestedFile(Path.Combine(generalBaseDir, SharedConstants.FLExVirtualOrderingFilename), rootElement);
            }

            // Yippee!! Write LP here. :-) [LanguageProject.langproj; new ext]
            CmObjectNestingService.NestObject(false,
                                              langProjElement,
                                              classData,
                                              guidToClassMapping);
            FileWriterService.WriteNestedFile(Path.Combine(generalBaseDir, SharedConstants.LanguageProjectFilename), new XElement(SharedConstants.LanguageProject, langProjElement));
        }
Exemple #15
0
        internal static void FlattenContext(
            SortedDictionary <string, XElement> highLevelData,
            SortedDictionary <string, XElement> sortedData,
            string generalBaseDir)
        {
            var langProjPathname = Path.Combine(generalBaseDir, SharedConstants.LanguageProjectFilename);
            var langProjDoc      = XDocument.Load(langProjPathname);
            var langProjElement  = langProjDoc.Root.Element(SharedConstants.LangProject);

            // Add LP to highLevelData.
            highLevelData.Add(SharedConstants.LangProject, langProjElement);
            // Flatten it.
            CmObjectFlatteningService.FlattenOwnerlessObject(
                langProjPathname,
                sortedData,
                langProjElement);

            // Add stuff LP owns that is here, then flatten it.
            // LP AnnotationDefs (OA-CmPossibilityList).
            var currentPathname = Path.Combine(generalBaseDir, SharedConstants.AnnotationDefsListFilename);

            if (File.Exists(currentPathname))
            {
                // Flatten it here to get the right pathname into the method.
                BaseDomainServices.RestoreElement(
                    currentPathname,
                    sortedData,
                    langProjElement,
                    SharedConstants.AnnotationDefs,
                    XDocument.Load(currentPathname).Root.Element(SharedConstants.CmPossibilityList));
            }

            // LP Styles (OC-StStyle)
            var langProjGuid   = langProjElement.Attribute(SharedConstants.GuidStr).Value.ToLowerInvariant();
            var sortedElements = new SortedDictionary <string, XElement>(StringComparer.OrdinalIgnoreCase);

            currentPathname = Path.Combine(generalBaseDir, SharedConstants.FLExStylesFilename);
            XDocument doc;

            if (File.Exists(currentPathname))
            {
                doc = XDocument.Load(currentPathname);
                foreach (var styleElement in doc.Root.Elements(SharedConstants.StStyle))
                {
                    // Put style back into LP's Styles element.
                    CmObjectFlatteningService.FlattenOwnedObject(
                        currentPathname,
                        sortedData,
                        styleElement,
                        langProjGuid, sortedElements);                         // Restore 'ownerguid' to style.
                }
                // Restore LP Styles property in sorted order.
                var langProjOwningProp = langProjElement.Element(SharedConstants.Styles);
                foreach (var sortedTextObjSurElement in sortedElements.Values)
                {
                    langProjOwningProp.Add(sortedTextObjSurElement);
                }
            }

            // LP Filters (OC-CmFilter)
            currentPathname = Path.Combine(generalBaseDir, SharedConstants.FLExFiltersFilename);
            if (File.Exists(currentPathname))
            {
                sortedElements = new SortedDictionary <string, XElement>(StringComparer.OrdinalIgnoreCase);
                doc            = XDocument.Load(currentPathname);
                foreach (var filterElement in doc.Root.Elements("CmFilter"))
                {
                    // Put CmFilter back into LP's Filters element.
                    CmObjectFlatteningService.FlattenOwnedObject(
                        currentPathname,
                        sortedData,
                        filterElement,
                        langProjGuid, sortedElements);                         // Restore 'ownerguid' to style.
                }
                // Restore LP Filters property in sorted order.
                var langProjOwningProp = langProjElement.Element(SharedConstants.Filters);
                foreach (var sortedTextObjSurElement in sortedElements.Values)
                {
                    langProjOwningProp.Add(sortedTextObjSurElement);
                }
            }

            // LP Annotations (OC-CmAnnotation). [Odd elements like in Discourse.]
            currentPathname = Path.Combine(generalBaseDir, SharedConstants.FLExAnnotationsFilename);
            if (File.Exists(currentPathname))
            {
                sortedElements = new SortedDictionary <string, XElement>(StringComparer.OrdinalIgnoreCase);
                doc            = XDocument.Load(currentPathname);
                foreach (var annotationElement in doc.Root.Elements(SharedConstants.CmAnnotation))
                {
                    // Put CmAnnotation back into LP's Annotations element.
                    var classAttr = annotationElement.Attribute(SharedConstants.Class);
                    annotationElement.Name = classAttr.Value;
                    classAttr.Remove();
                    CmObjectFlatteningService.FlattenOwnedObject(
                        currentPathname,
                        sortedData,
                        annotationElement,
                        langProjGuid, sortedElements);                         // Restore 'ownerguid' to style.
                }
                // Restore LP Annotations property in sorted order.
                var owningProp = langProjElement.Element(SharedConstants.Annotations);
                foreach (var sortedTextObjSurElement in sortedElements.Values)
                {
                    owningProp.Add(sortedTextObjSurElement);
                }
            }

            // No VirtualOrdering instances are owned.
            if (MetadataCache.MdCache.ModelVersion > MetadataCache.StartingModelVersion)
            {
                currentPathname = Path.Combine(generalBaseDir, SharedConstants.FLExVirtualOrderingFilename);
                doc             = XDocument.Load(currentPathname);
                foreach (var orderingElement in doc.Root.Elements(SharedConstants.VirtualOrdering))
                {
                    CmObjectFlatteningService.FlattenOwnerlessObject(
                        currentPathname,
                        sortedData,
                        orderingElement);
                }
            }

            // Some CmPicture instances may not be owned.
            currentPathname = Path.Combine(generalBaseDir, SharedConstants.FLExUnownedPicturesFilename);
            doc             = XDocument.Load(currentPathname);
            foreach (var pictureElement in doc.Root.Elements(SharedConstants.CmPicture))
            {
                CmObjectFlatteningService.FlattenOwnerlessObject(
                    currentPathname,
                    sortedData,
                    pictureElement);
            }
        }
Exemple #16
0
        internal static void PutHumptyTogetherAgain(IProgress progress, bool writeVerbose, string mainFilePathname)
        {
            Guard.AgainstNull(progress, "progress");
            FileWriterService.CheckPathname(mainFilePathname);

            using (var tempFile = new TempFile())
            {
                using (var writer = XmlWriter.Create(tempFile.Path, new XmlWriterSettings                 // NB: These are the FW bundle of settings, not the canonical settings.
                {
                    OmitXmlDeclaration = false,
                    CheckCharacters = true,
                    ConformanceLevel = ConformanceLevel.Document,
                    Encoding = new UTF8Encoding(false),
                    Indent = true,
                    IndentChars = (""),
                    NewLineOnAttributes = false
                }))
                {
                    var pathRoot = Path.GetDirectoryName(mainFilePathname);
                    // NB: The method calls are strictly ordered.
                    // Don't even think of changing them.
                    if (writeVerbose)
                    {
                        progress.WriteVerbose("Processing data model version number....");
                    }
                    else
                    {
                        progress.WriteMessage("Processing data model version number....");
                    }
                    UpgradeToVersion(writer, pathRoot);
                    if (writeVerbose)
                    {
                        progress.WriteVerbose("Processing custom properties....");
                    }
                    else
                    {
                        progress.WriteMessage("Processing custom properties....");
                    }
                    WriteOptionalCustomProperties(writer, pathRoot);

                    var sortedData = BaseDomainServices.PutHumptyTogetherAgain(progress, writeVerbose, pathRoot);

                    if (writeVerbose)
                    {
                        progress.WriteVerbose("Writing temporary fwdata file....");
                    }
                    else
                    {
                        progress.WriteMessage("Writing temporary fwdata file....");
                    }
                    foreach (var rtElement in sortedData.Values)
                    {
                        FileWriterService.WriteElement(writer, rtElement);
                    }
                    writer.WriteEndElement();
                }
                //Thread.Sleep(2000); In case it blows (access denied) up again on Sue's computer.
                if (writeVerbose)
                {
                    progress.WriteVerbose("Copying temporary fwdata file to main file....");
                }
                else
                {
                    progress.WriteMessage("Copying temporary fwdata file to main file....");
                }
                File.Copy(tempFile.Path, mainFilePathname, true);
            }

            SplitFileAgainIfNeeded(progress, writeVerbose, mainFilePathname);
        }
        internal static void FlattenContext(
            SortedDictionary <string, XElement> highLevelData,
            SortedDictionary <string, XElement> sortedData,
            string anthropologyBaseDir)
        {
            var langProjElement = highLevelData[SharedConstants.LangProject];
            var currentPathname = Path.Combine(anthropologyBaseDir, SharedConstants.DataNotebookFilename);
            var doc             = XDocument.Load(currentPathname);
            var root            = doc.Root;
            var dnMainElement   = root.Element(SharedConstants.Header).Element("RnResearchNbk");

            // Add the record elements (except the possible dummy one) into dnMainElement.
            var sortedRecords = new SortedDictionary <string, XElement>(StringComparer.OrdinalIgnoreCase);

            foreach (var recordElement in root.Elements("RnGenericRec")
                     .Where(element => element.Attribute(SharedConstants.GuidStr).Value.ToLowerInvariant() != SharedConstants.EmptyGuid))
            {
                // Add it to Records property of dnMainElement, BUT in sorted order, below, and then flatten dnMainElement.
                sortedRecords.Add(recordElement.Attribute(SharedConstants.GuidStr).Value.ToLowerInvariant(), recordElement);
            }

            if (sortedRecords.Count > 0)
            {
                var recordsElementOwningProp = dnMainElement.Element("Records")
                                               ?? CmObjectFlatteningService.AddNewPropertyElement(dnMainElement, "Records");
                foreach (var sortedChartElement in sortedRecords.Values)
                {
                    recordsElementOwningProp.Add(sortedChartElement);
                }
            }

            // Put the RecTypes list back into place in dnMainElement, before dnMainElement is restored.
            // But only as an <objsur> element.
            var recTypesPathname = Path.Combine(anthropologyBaseDir, "RecTypes." + SharedConstants.List);

            if (File.Exists(recTypesPathname))
            {
                var listDoc = XDocument.Load(recTypesPathname);
                BaseDomainServices.RestoreElement(recTypesPathname, sortedData,
                                                  dnMainElement, "RecTypes",
                                                  listDoc.Root.Element(SharedConstants.CmPossibilityList));
            }

            BaseDomainServices.RestoreElement(currentPathname, sortedData,
                                              langProjElement, "ResearchNotebook",
                                              dnMainElement);

            // Put the lists back where they belong in LangProj.
            foreach (var listPathname in Directory.GetFiles(anthropologyBaseDir, "*." + SharedConstants.List))
            {
                var listDoc      = XDocument.Load(listPathname);
                var listRoot     = listDoc.Root;
                var listRootName = listRoot.Name.LocalName;
                if (listRootName == "RecTypes")
                {
                    continue;
                }
                BaseDomainServices.RestoreElement(listPathname,
                                                  sortedData,
                                                  langProjElement,
                                                  listRootName,
                                                  listRoot.Element(SharedConstants.CmPossibilityList));
            }
        }
        internal static void NestContext(string linguisticsBaseDir,
                                         IDictionary <string, XElement> wellUsedElements,
                                         IDictionary <string, SortedDictionary <string, byte[]> > classData,
                                         Dictionary <string, string> guidToClassMapping)
        {
            var discourseDir = Path.Combine(linguisticsBaseDir, SharedConstants.DiscourseRootFolder);

            if (!Directory.Exists(discourseDir))
            {
                Directory.CreateDirectory(discourseDir);
            }

            var sortedInstanceData = classData["DsDiscourseData"];

            if (sortedInstanceData.Count == 0)
            {
                return;
            }

            // 'discourseElement' is owned by LangProj in DsDiscourseData prop (OA).
            var discourseElement = Utilities.CreateFromBytes(sortedInstanceData.Values.First());

            // Nest the entire object, and then pull out the owned stuff, and relocate them, as needed.
            CmObjectNestingService.NestObject(
                false,
                discourseElement,
                classData,
                guidToClassMapping);

            var listElement = discourseElement.Element(SharedConstants.ConstChartTempl);

            if (listElement != null)
            {
                // NB: Write list file, but only if discourseElement has the list.
                FileWriterService.WriteNestedFile(Path.Combine(discourseDir, SharedConstants.ConstChartTemplFilename), listElement);
                listElement.RemoveNodes();
            }

            listElement = discourseElement.Element(SharedConstants.ChartMarkers);
            if (listElement != null)
            {
                // NB: Write list file, but only if discourseElement has the list.
                FileWriterService.WriteNestedFile(Path.Combine(discourseDir, SharedConstants.ChartMarkersFilename), listElement);
                listElement.RemoveNodes();
            }

            // <owning num="2" id="Charts" card="col" sig="DsChart"> [Abstract. Owns nothing special, but is subclass of CmMajorObject.]
            //		Disposition: Write in main discourse file as the repeating series of objects, BUT use the abstract class for the repeating element, since Gordon sees new subclasses of it coming along.

            // NB: We will just let the normal nesting code work over discourseElement,
            // which will put in the actual subclass name as the element tag.
            // So, we'll just intercept them out of the owning prop elemtent (if any exist), and patch them up here.
            // NB: If there are no such charts, then do the usual of making one with the empty guid for its Id.
            var root   = new XElement(SharedConstants.DiscourseRootFolder);
            var header = new XElement(SharedConstants.Header);

            root.Add(header);
            header.Add(discourseElement);
            // Remove child objsur node from owning LangProg
            var langProjElement = wellUsedElements[SharedConstants.LangProject];

            langProjElement.Element("DiscourseData").RemoveNodes();

            var chartElements = discourseElement.Element("Charts");

            if (chartElements != null && chartElements.HasElements)
            {
                foreach (var chartElement in chartElements.Elements())
                {
                    BaseDomainServices.ReplaceElementNameWithAndAddClassAttribute(SharedConstants.DsChart, chartElement);
                    // It is already nested.
                    root.Add(chartElement);
                }
                chartElements.RemoveNodes();
            }

            FileWriterService.WriteNestedFile(Path.Combine(discourseDir, SharedConstants.DiscourseChartFilename), root);
        }
        internal static void FlattenContext(
            SortedDictionary <string, XElement> highLevelData,
            SortedDictionary <string, XElement> sortedData,
            string scriptureBaseDir)
        {
            if (!Directory.Exists(scriptureBaseDir))
            {
                return;
            }

            // scriptureBaseDir is root/Scripture.
            var pathname = Path.Combine(scriptureBaseDir, SharedConstants.ScriptureTransFilename);

            if (!File.Exists(pathname))
            {
                return;                 // Nobody home.
            }
            var doc        = XDocument.Load(pathname);
            var scrElement = doc.Element(SharedConstants.TranslatedScripture).Elements().First();

            // Put the NoteCategories list back in the right place.
            pathname = Path.Combine(scriptureBaseDir, SharedConstants.NoteCategoriesListFilename);
            if (File.Exists(pathname))
            {
                doc = XDocument.Load(pathname);
                BaseDomainServices.RestoreElement(pathname, sortedData, scrElement, SharedConstants.NoteCategories, doc.Root.Element(SharedConstants.CmPossibilityList));
            }

            // Owned by LangProj in TranslatedScripture prop.
            var langProjElement = highLevelData[SharedConstants.LangProject];

            CmObjectFlatteningService.FlattenOwnedObject(
                pathname,
                sortedData,
                scrElement,
                langProjElement.Attribute(SharedConstants.GuidStr).Value.ToLowerInvariant(),
                langProjElement, SharedConstants.TranslatedScripture);                 // Restore 'ownerguid' to scrElement.

            // Put the <objsur> elements back into BookAnnotations and ScriptureBooks property elements.
            // There will always be 66 ScrBookAnnotations instances and they need go in canonical book order.
            // There may (or may not) be ScrBook instances, but they all go in canonical book order in ScriptureBooks, if present.
            var booksDir    = Path.Combine(scriptureBaseDir, SharedConstants.Books);
            var sortedFiles = new SortedList <int, string>(66);

            foreach (var pathnameForAnn in Directory.GetFiles(booksDir, "*." + SharedConstants.bookannotations))
            {
                sortedFiles.Add(Int32.Parse(Path.GetFileNameWithoutExtension(pathnameForAnn)), pathnameForAnn);
            }
            var scrElementGuid         = scrElement.Attribute(SharedConstants.GuidStr).Value.ToLowerInvariant();
            var scriptureBooksProperty = scrElement.Element(SharedConstants.ScriptureBooks);

            foreach (var sortedPathnameKvp in sortedFiles)
            {
                var sortedDoc = XDocument.Load(sortedPathnameKvp.Value);
                var element   = sortedDoc.Root.Element(SharedConstants.ScrBookAnnotations);
                CmObjectFlatteningService.FlattenOwnedObject(
                    sortedPathnameKvp.Value,
                    sortedData,
                    element,
                    scrElementGuid, scrElement, SharedConstants.BookAnnotations);                     // Restore 'ownerguid' to annotation.

                // Deal with optional ScrBook
                var bookPathname = sortedPathnameKvp.Value.Replace(SharedConstants.bookannotations, SharedConstants.book);
                if (!File.Exists(bookPathname))
                {
                    continue;
                }

                if (scriptureBooksProperty == null)
                {
                    scriptureBooksProperty = new XElement(SharedConstants.ScriptureBooks);
                    scrElement.Add(scriptureBooksProperty);
                    // Make sure new property is sorted in correct place.
                    DataSortingService.SortMainRtElement(scrElement);
                }
                // Add book <objsur> element to scrElement's ScriptureBooks element.
                sortedDoc = XDocument.Load(bookPathname);
                element   = sortedDoc.Root.Element(SharedConstants.ScrBook);
                CmObjectFlatteningService.FlattenOwnedObject(
                    bookPathname,
                    sortedData,
                    element,
                    scrElementGuid, scrElement, SharedConstants.ScriptureBooks);                     // Restore 'ownerguid' to book.
            }

            highLevelData.Add(scrElement.Attribute(SharedConstants.Class).Value, scrElement);
        }
        internal static void FlattenContext(
            SortedDictionary <string, XElement> highLevelData,
            SortedDictionary <string, XElement> sortedData,
            string linguisticsBaseDir)
        {
            var reversalDir = Path.Combine(linguisticsBaseDir, ReversalRootFolder);

            if (!Directory.Exists(reversalDir))
            {
                return;
            }

            var lexDb          = highLevelData[SharedConstants.LexDb];
            var sortedRevs     = new SortedDictionary <string, XElement>(StringComparer.OrdinalIgnoreCase);
            var unlovedFolders = new HashSet <string>();

            foreach (var revIndexDirectoryName in Directory.GetDirectories(reversalDir))
            {
                var dirInfo          = new DirectoryInfo(revIndexDirectoryName);
                var ws               = dirInfo.Name;
                var reversalPathname = Path.Combine(revIndexDirectoryName, ws + "." + SharedConstants.Reversal);
                if (!File.Exists(reversalPathname))
                {
                    // If a reversal is deleted but there were ChorusNotes associated with it the directory might be
                    // here without any reversal files inside it.
                    unlovedFolders.Add(revIndexDirectoryName);
                    continue;
                }

                var reversalDoc = XDocument.Load(reversalPathname);

                // Put entries back into index's Entries element.
                var root          = reversalDoc.Element("Reversal");
                var header        = root.Element(SharedConstants.Header);
                var revIdxElement = header.Element("ReversalIndex");

                // Restore POS list, if it exists.
                var catPathname = Path.Combine(revIndexDirectoryName, ws + "-" + SharedConstants.PartsOfSpeechFilename);
                if (File.Exists(catPathname))
                {
                    var catListDoc = XDocument.Load(catPathname);
                    BaseDomainServices.RestoreElement(
                        catPathname,
                        sortedData,
                        revIdxElement, SharedConstants.PartsOfSpeech,
                        catListDoc.Root.Element(SharedConstants.CmPossibilityList));                         // Owned elment.
                }

                // Put all records back in ReversalIndex, before sort and restore.
                // EXCEPT, if there is only one of them and it is guid.Empty, then skip it
                var sortedRecords = new SortedDictionary <string, XElement>(StringComparer.OrdinalIgnoreCase);
                foreach (var recordElement in root.Elements("ReversalIndexEntry")
                         .Where(element => element.Attribute(SharedConstants.GuidStr).Value.ToLowerInvariant() != SharedConstants.EmptyGuid))
                {
                    // Add it to Records property of revIdxElement, BUT in sorted order, below, and then flatten dnMainElement.
                    sortedRecords.Add(recordElement.Attribute(SharedConstants.GuidStr).Value.ToLowerInvariant(), recordElement);
                }

                if (sortedRecords.Count > 0)
                {
                    var recordsElementOwningProp = revIdxElement.Element("Entries")
                                                   ?? CmObjectFlatteningService.AddNewPropertyElement(revIdxElement, "Entries");

                    foreach (var sortedChartElement in sortedRecords.Values)
                    {
                        recordsElementOwningProp.Add(sortedChartElement);
                    }
                }
                CmObjectFlatteningService.FlattenOwnedObject(reversalPathname, sortedData, revIdxElement,
                                                             lexDb.Attribute(SharedConstants.GuidStr).Value.ToLowerInvariant(), sortedRevs); // Restore 'ownerguid' to indices.
            }

            foreach (var unlovedFolder in unlovedFolders)
            {
                Directory.Delete(unlovedFolder, true);
            }

            // Restore lexDb ReversalIndexes property in sorted order.
            if (sortedRevs.Count == 0)
            {
                return;
            }

            var reversalsOwningProp = lexDb.Element("ReversalIndexes") ?? CmObjectFlatteningService.AddNewPropertyElement(lexDb, "ReversalIndexes");

            foreach (var sortedRev in sortedRevs.Values)
            {
                reversalsOwningProp.Add(sortedRev);
            }
        }
        internal static void FlattenContext(
            SortedDictionary <string, XElement> highLevelData,
            SortedDictionary <string, XElement> sortedData,
            string linguisticsBaseDir)
        {
            var discourseDir = Path.Combine(linguisticsBaseDir, SharedConstants.DiscourseRootFolder);

            if (!Directory.Exists(discourseDir))
            {
                return;
            }
            var chartPathname = Path.Combine(discourseDir, SharedConstants.DiscourseChartFilename);

            if (!File.Exists(chartPathname))
            {
                return;
            }

            // The charts need to be sorted in guid order, before being added back into the owning prop element.
            var doc              = XDocument.Load(chartPathname);
            var root             = doc.Root;
            var discourseElement = root.Element(SharedConstants.Header).Element("DsDiscourseData");

            // Add lists back into discourseElement.
            foreach (var listPathname in Directory.GetFiles(discourseDir, "*." + SharedConstants.List))
            {
                var listDoc      = XDocument.Load(listPathname);
                var listFilename = Path.GetFileName(listPathname);
                var listElement  = listDoc.Root.Element(SharedConstants.CmPossibilityList);
                switch (listFilename)
                {
                case SharedConstants.ChartMarkersFilename:
                    discourseElement.Element(SharedConstants.ChartMarkers).Add(listElement);
                    break;

                case SharedConstants.ConstChartTemplFilename:
                    discourseElement.Element(SharedConstants.ConstChartTempl).Add(listElement);
                    break;
                }
            }
            // Add the chart elements (except the possible dummy one) into discourseElement.
            var sortedCharts = new SortedDictionary <string, XElement>(StringComparer.OrdinalIgnoreCase);

            foreach (var chartElement in root.Elements(SharedConstants.DsChart)
                     .Where(element => element.Attribute(SharedConstants.GuidStr).Value.ToLowerInvariant() != SharedConstants.EmptyGuid))
            {
                // No. Add it to discourseElement, BUT in sorted order, below, and then flatten discourseElement.
                // Restore the right main element name from the class attribute.
                var classAttr = chartElement.Attribute(SharedConstants.Class);
                chartElement.Name = classAttr.Value;
                classAttr.Remove();
                sortedCharts.Add(chartElement.Attribute(SharedConstants.GuidStr).Value.ToLowerInvariant(), chartElement);
            }

            if (sortedCharts.Count > 0)
            {
                var discourseElementOwningProp = discourseElement.Element("Charts")
                                                 ?? CmObjectFlatteningService.AddNewPropertyElement(discourseElement, "Charts");
                foreach (var sortedChartElement in sortedCharts.Values)
                {
                    discourseElementOwningProp.Add(sortedChartElement);
                }
            }
            var langProjElement = highLevelData[SharedConstants.LangProject];

            BaseDomainServices.RestoreElement(
                chartPathname,
                sortedData,
                langProjElement,
                "DiscourseData",
                discourseElement);
        }
        internal static void NestContext(string linguisticsBaseDir,
                                         IDictionary <string, XElement> wellUsedElements,
                                         IDictionary <string, SortedDictionary <string, byte[]> > classData,
                                         Dictionary <string, string> guidToClassMapping)
        {
            var morphAndSynDir = Path.Combine(linguisticsBaseDir, SharedConstants.MorphologyAndSyntax);

            if (!Directory.Exists(morphAndSynDir))
            {
                Directory.CreateDirectory(morphAndSynDir);
            }

            var lexDb = wellUsedElements[SharedConstants.LexDb];

            if (lexDb != null)
            {
                // Write out LexDb's "MorphTypes" list, as per AndyB (7 Feb 2012).
                FileWriterService.WriteNestedListFileIfItExists(classData, guidToClassMapping,
                                                                lexDb, SharedConstants.MorphTypes,
                                                                Path.Combine(morphAndSynDir, SharedConstants.MorphTypesListFilename));
            }
            var langProjElement = wellUsedElements[SharedConstants.LangProject];
            // 1. Nest: LP's MorphologicalData(MoMorphData OA) (Also does MoMorphData's ProdRestrict(CmPossibilityList)
            //		Remove objsur node from LP.
            var morphologicalDataPropElement = langProjElement.Element("MorphologicalData");

            morphologicalDataPropElement.RemoveNodes();
            var morphDataElement = Utilities.CreateFromBytes(classData["MoMorphData"].Values.First());

            CmObjectNestingService.NestObject(
                false,
                morphDataElement,
                classData,
                guidToClassMapping);
            // Hold off writing it until its list is written.

            // 2. Nest: LP's MsFeatureSystem(FsFeatureSystem OA)
            //		Remove objsur node from LP.
            var morphFeatureSystemPropElement = langProjElement.Element("MsFeatureSystem");
            var morphFeatureSystemElement     = Utilities.CreateFromBytes(classData["FsFeatureSystem"][morphFeatureSystemPropElement.Element(SharedConstants.Objsur).Attribute(SharedConstants.GuidStr).Value]);

            morphFeatureSystemPropElement.RemoveNodes();
            CmObjectNestingService.NestObject(
                false,
                morphFeatureSystemElement,
                classData,
                guidToClassMapping);
            FileWriterService.WriteNestedFile(Path.Combine(morphAndSynDir, SharedConstants.MorphAndSynFeaturesFilename), new XElement(SharedConstants.FeatureSystem, morphFeatureSystemElement));

            // 3. Nest: LP's PartsOfSpeech(CmPossibilityList OA)
            //		Remove objsur node from LP.
            FileWriterService.WriteNestedListFileIfItExists(classData, guidToClassMapping,
                                                            langProjElement, SharedConstants.PartsOfSpeech,
                                                            Path.Combine(morphAndSynDir, SharedConstants.PartsOfSpeechFilename));

            // 4. Nest: LP's AnalyzingAgents(CmAgent OC) (use some new extension and a fixed name)
            //		Remove objsur node(s) from LP.
            var agents      = classData["CmAgent"];
            var rootElement = new XElement(SharedConstants.AnalyzingAgents);

            foreach (var agentGuid in BaseDomainServices.GetGuids(langProjElement, SharedConstants.AnalyzingAgents))
            {
                var agentElement = Utilities.CreateFromBytes(agents[agentGuid]);
                rootElement.Add(agentElement);
                CmObjectNestingService.NestObject(
                    false,
                    agentElement,
                    classData,
                    guidToClassMapping);
            }
            FileWriterService.WriteNestedFile(Path.Combine(morphAndSynDir, SharedConstants.AnalyzingAgentsFilename), rootElement);
            langProjElement.Element(SharedConstants.AnalyzingAgents).RemoveNodes();

            // A. Write: MoMorphData's ProdRestrict(CmPossibilityList OA) and write in its own .list file.
            //		Remove ProdRestrict node child in MoMorphData
            var prodRestrictPropElement = morphDataElement.Element("ProdRestrict");

            if (prodRestrictPropElement != null && prodRestrictPropElement.HasElements)
            {
                // NB: Write file, but only if morphDataElement has the list.
                FileWriterService.WriteNestedFile(Path.Combine(morphAndSynDir, "ProdRestrict." + SharedConstants.List), prodRestrictPropElement);
                prodRestrictPropElement.RemoveNodes();
            }

            // B. Write: LP's MorphologicalData(MoMorphData OA) in a new extension (morphdata)
            FileWriterService.WriteNestedFile(Path.Combine(morphAndSynDir, SharedConstants.MorphAndSynDataFilename), new XElement(SharedConstants.MorphAndSynData, morphDataElement));
        }
        internal static void FlattenContext(
            SortedDictionary <string, XElement> highLevelData,
            SortedDictionary <string, XElement> sortedData,
            string linguisticsBaseDir)
        {
            var morphAndSynDir = Path.Combine(linguisticsBaseDir, SharedConstants.MorphologyAndSyntax);

            if (!Directory.Exists(morphAndSynDir))
            {
                return;
            }

            var langProjElement = highLevelData[SharedConstants.LangProject];
            var lexDb           = highLevelData[SharedConstants.LexDb];
            var currentPathname = Path.Combine(morphAndSynDir, SharedConstants.MorphTypesListFilename);

            if (lexDb != null && File.Exists(currentPathname))
            {
                // Restore MorphTypes list to LexDb.
                var morphTypesDoc = XDocument.Load(currentPathname);
                BaseDomainServices.RestoreElement(
                    currentPathname,
                    sortedData,
                    lexDb, SharedConstants.MorphTypes,
                    morphTypesDoc.Root.Element(SharedConstants.CmPossibilityList));                     // Owned elment.
            }
            var langProjGuid = langProjElement.Attribute(SharedConstants.GuidStr).Value.ToLowerInvariant();

            currentPathname = Path.Combine(morphAndSynDir, SharedConstants.MorphAndSynFeaturesFilename);
            if (File.Exists(currentPathname))
            {
                var mAndSFeatSysDoc = XDocument.Load(currentPathname);
                BaseDomainServices.RestoreElement(
                    currentPathname,
                    sortedData,
                    langProjElement, "MsFeatureSystem",
                    mAndSFeatSysDoc.Root.Element("FsFeatureSystem"));                     // Owned elment.
            }

            currentPathname = Path.Combine(morphAndSynDir, SharedConstants.PartsOfSpeechFilename);
            if (File.Exists(currentPathname))
            {
                var posDoc = XDocument.Load(currentPathname);
                BaseDomainServices.RestoreElement(
                    currentPathname,
                    sortedData,
                    langProjElement, SharedConstants.PartsOfSpeech,
                    posDoc.Root.Element(SharedConstants.CmPossibilityList));                     // Owned elment.
            }

            currentPathname = Path.Combine(morphAndSynDir, SharedConstants.AnalyzingAgentsFilename);
            // Put Agents back into LP.
            var sortedAgents = new SortedDictionary <string, XElement>(StringComparer.OrdinalIgnoreCase);
            var agentDoc     = XDocument.Load(currentPathname);

            foreach (var agentElement in agentDoc.Root.Elements())
            {
                CmObjectFlatteningService.FlattenOwnedObject(
                    currentPathname,
                    sortedData,
                    agentElement,
                    langProjGuid, sortedAgents);                     // Restore 'ownerguid' to agent.
            }
            // Restore LP AnalyzingAgents property in sorted order.
            if (sortedAgents.Count > 0)
            {
                var langProjOwningProp = langProjElement.Element(SharedConstants.AnalyzingAgents);
                foreach (var sortedTextObjSurElement in sortedAgents.Values)
                {
                    langProjOwningProp.Add(sortedTextObjSurElement);
                }
            }

            currentPathname = Path.Combine(morphAndSynDir, SharedConstants.MorphAndSynDataFilename);
            if (File.Exists(currentPathname))
            {
                var mAndSDataDoc     = XDocument.Load(currentPathname);
                var morphDataElement = mAndSDataDoc.Root.Element("MoMorphData");
                BaseDomainServices.RestoreElement(
                    currentPathname,
                    sortedData,
                    langProjElement,
                    "MorphologicalData",
                    morphDataElement);

                currentPathname = Path.Combine(morphAndSynDir, "ProdRestrict." + SharedConstants.List);
                if (File.Exists(currentPathname))
                {
                    var prodRestrictDoc         = XDocument.Load(currentPathname);
                    var prodRestrictListElement = prodRestrictDoc.Root.Element(SharedConstants.CmPossibilityList);
                    BaseDomainServices.RestoreElement(
                        currentPathname,
                        sortedData,
                        morphDataElement, "ProdRestrict", prodRestrictListElement);
                }
            }
        }
        private static void FlattenObjectCore(
            string pathname,
            SortedDictionary <string, XElement> sortedData,
            XElement element, string ownerguid)
        {
            if (string.IsNullOrEmpty(pathname))
            {
                throw new ArgumentNullException("pathname");
            }
            if (sortedData == null)
            {
                throw new ArgumentNullException("sortedData");
            }
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            // No, since unowned stuff will feed a null.
            //if (string.IsNullOrEmpty(ownerguid)) throw new ArgumentNullException(SharedConstants.OwnerGuid);
            if (ownerguid != null && ownerguid == string.Empty)
            {
                throw new ArgumentException(Resources.kOwnerGuidEmpty, SharedConstants.OwnerGuid);
            }

            string className;
            bool   isOwnSeqNode;
            var    elementGuid = CheckForDuplicateElementMethod.CheckForDuplicateGuid(pathname, sortedData, element, out isOwnSeqNode, out className);

            sortedData.Add(elementGuid, element);

            // The name of 'element' is the class of CmObject, or 'ownseq', or....
            element.Name = SharedConstants.RtTag;
            if (!isOwnSeqNode)
            {
                element.Add(new XAttribute(SharedConstants.Class, className));
            }
            //if (element.Attribute(SharedConstants.OwnerGuid) == null)
            if (ownerguid != null)             // && element.Attribute(SharedConstants.OwnerGuid) == null)
            {
                element.Add(new XAttribute(SharedConstants.OwnerGuid, ownerguid));
            }

            // Re-sort those attributes.
            var sortedAttrs = new SortedDictionary <string, XAttribute>();

            foreach (var attribute in element.Attributes())
            {
                sortedAttrs.Add(attribute.Name.LocalName, attribute);
            }
            element.Attributes().Remove();
            element.Add(sortedAttrs.Values);

            // Restore any ref seq props to have 'objsur' elements.
            var mdc             = MetadataCache.MdCache;
            var propCache       = mdc.PropertyCache[className];
            var refSeqPropNames = propCache["AllReferenceSequence"];
            // Restore any ref col props to have 'objsur' elements.
            var refColPropNames     = propCache["AllReferenceCollection"];
            var owningPropsForClass = propCache["AllOwning"];

            if (owningPropsForClass.Count == 0 && refSeqPropNames.Count == 0 && refColPropNames.Count == 0)
            {
                return;                 // Nothing special to be done for normal properties.
            }
            foreach (var propertyElement in element.Elements().ToArray())
            {
                var isCustomProperty = propertyElement.Name.LocalName == SharedConstants.Custom;
                var propName         = isCustomProperty ? propertyElement.Attribute(SharedConstants.Name).Value : propertyElement.Name.LocalName;
                if (!owningPropsForClass.Contains(propName))
                {
                    if (refSeqPropNames.Contains(propName))
                    {
                        foreach (var refSeqNode in propertyElement.Elements(SharedConstants.Refseq))
                        {
                            refSeqNode.Name = SharedConstants.Objsur;
                        }
                    }
                    else if (refColPropNames.Contains(propName))
                    {
                        foreach (var refColNode in propertyElement.Elements(SharedConstants.Refcol))
                        {
                            refColNode.Name = SharedConstants.Objsur;
                        }
                    }
                    continue;
                }
                if (!propertyElement.HasElements)
                {
                    continue;
                }

                foreach (var ownedElement in propertyElement.Elements().ToArray())
                {
                    if (ownedElement.Name.LocalName == SharedConstants.Objsur)
                    {
                        break;
                    }
                    // Do before the removal call, so we know the parent, and thus, the property name.
                    if (isCustomProperty)
                    {
                        var owningPropertyElement = (element.Elements().Where(customNode => customNode.Name.LocalName == SharedConstants.Custom && customNode.Attribute(SharedConstants.Name) != null && customNode.Attribute(SharedConstants.Name).Value == propertyElement.Attribute(SharedConstants.Name).Value)).First();
                        ownedElement.Remove();
                        FlattenObjectCore(pathname, sortedData, ownedElement, elementGuid);                         // BEFORE we make the objsur!
                        BaseDomainServices.RestoreObjsurElement(owningPropertyElement, ownedElement);
                    }
                    else
                    {
                        var propertyName = ownedElement.Parent.Name.LocalName;
                        ownedElement.Remove();
                        // Move down the nested set of owned objects, and do the same.
                        FlattenOwnedObject(pathname, sortedData, ownedElement, elementGuid, element, propertyName);
                    }
                }
            }
        }
Exemple #25
0
        internal static void FlattenContext(
            SortedDictionary <string, XElement> highLevelData,
            SortedDictionary <string, XElement> sortedData,
            string linguisticsBaseDir)
        {
            var textCorpusBaseDir = Path.Combine(linguisticsBaseDir, SharedConstants.TextCorpus);

            if (!Directory.Exists(textCorpusBaseDir))
            {
                return;
            }

            var langProjElement = highLevelData[SharedConstants.LangProject];
            var langProjGuid    = langProjElement.Attribute(SharedConstants.GuidStr).Value.ToLowerInvariant();

            // Put the Genre list back in the right place.
            var pathname = Path.Combine(textCorpusBaseDir, SharedConstants.GenreListFilename);
            var doc      = XDocument.Load(pathname);

            BaseDomainServices.RestoreElement(pathname, sortedData, langProjElement, SharedConstants.GenreList, doc.Root.Element(SharedConstants.CmPossibilityList));
            // Put the markup tags list back in the right place.
            pathname = Path.Combine(textCorpusBaseDir, SharedConstants.TextMarkupTagsListFilename);
            doc      = XDocument.Load(pathname);
            BaseDomainServices.RestoreElement(pathname, sortedData, langProjElement, SharedConstants.TextMarkupTags, doc.Root.Element(SharedConstants.CmPossibilityList));
            // Put the translation tags list back in the right place.
            pathname = Path.Combine(textCorpusBaseDir, SharedConstants.TranslationTagsListFilename);
            doc      = XDocument.Load(pathname);
            BaseDomainServices.RestoreElement(pathname, sortedData, langProjElement, SharedConstants.TranslationTags, doc.Root.Element(SharedConstants.CmPossibilityList));

            if (MetadataCache.MdCache.ModelVersion < 7000059)
            {
                // Backwards compatible code.
                // Put Texts back into LP.
                var sortedTexts = new SortedDictionary <string, XElement>(StringComparer.OrdinalIgnoreCase);
                foreach (var textPathname in Directory.GetFiles(textCorpusBaseDir, "*." + SharedConstants.TextInCorpus, SearchOption.TopDirectoryOnly))
                {
                    var textDoc = XDocument.Load(textPathname);
                    // Put texts back into index's Entries element.
                    var root        = textDoc.Root;
                    var textElement = root.Elements().First();
                    CmObjectFlatteningService.FlattenOwnedObject(
                        textPathname,
                        sortedData,
                        textElement,
                        langProjGuid, sortedTexts);                         // Restore 'ownerguid' to text.
                }
                // Restore LP Texts property in sorted order.
                if (sortedTexts.Count == 0)
                {
                    return;
                }
                var langProjOwningProp = langProjElement.Element("Texts");
                foreach (var sortedTextObjSurElement in sortedTexts.Values)
                {
                    langProjOwningProp.Add(sortedTextObjSurElement);
                }
            }
            else
            {
                // Put Texts (all unowned now) all in 'sortedData'.
                foreach (var textPathname in Directory.GetFiles(textCorpusBaseDir, "*." + SharedConstants.TextInCorpus, SearchOption.TopDirectoryOnly))
                {
                    var textDoc     = XDocument.Load(textPathname);
                    var root        = textDoc.Root;
                    var textElement = root.Elements().First();
                    CmObjectFlatteningService.FlattenOwnerlessObject(
                        textPathname,
                        sortedData,
                        textElement);
                }
            }
        }
Exemple #26
0
 internal static void RemoveBoundedContextData(string pathRoot)
 {
     BaseDomainServices.RemoveBoundedContextDataCore(Path.Combine(pathRoot, SharedConstants.Other));
 }