Exemplo n.º 1
0
        public Converter(string sourceFolderXml, string targetFolderYaml, string targetFolderJson, string targetFolderResx, bool checkBSDD = false)
        {
            CheckBSDD = checkBSDD;
            _bsdd     = new Bsdd();

            string propertySetVersionList  = string.Empty;
            string propertySetTemplateList = string.Empty;
            string propertyTypeList        = string.Empty;
            string propertyUnitList        = string.Empty;

            foreach (string sourceFile in Directory.EnumerateFiles(sourceFolderXml, "PSet*.xml").OrderBy(x => x).ToList())//.Where(x=>x.Contains("Pset_ConstructionResource")))
            {
                numberOfPsets++;
                PropertySetDef pSet = PropertySetDef.LoadFromFile(sourceFile);
                log.Info("--------------------------------------------------");
                log.Info($"Checking PSet {pSet.Name}");
                log.Info($"Opened PSet-File {sourceFile.Replace(sourceFolderXml + @"\", string.Empty)}");

                if (!propertySetVersionList.Contains(pSet.IfcVersion.version))
                {
                    propertySetVersionList += pSet.IfcVersion.version + ",";
                }
                if (!propertySetTemplateList.Contains(pSet.templatetype.ToString()))
                {
                    propertySetTemplateList += pSet.templatetype.ToString() + ",";
                }

                PropertySet propertySet = new PropertySet()
                {
                    name = pSet.Name,
                    dictionaryReference = new DictionaryReference()
                    {
                        ifdGuid    = "",
                        legacyGuid = ""
                    },
                    ifcVersion = new IfcVersion()
                    {
                        version = ConvertToSematicVersion(pSet.IfcVersion.version).ToString(),
                        schema  = pSet.IfcVersion.schema
                    },
                    definition = pSet.Definition
                };

                propertySet.applicableIfcClasses = new List <ApplicableIfcClass>();
                foreach (var applicableClass in pSet.ApplicableClasses)
                {
                    propertySet.applicableIfcClasses.Add(new ApplicableIfcClass()
                    {
                        name = applicableClass,
                        type = pSet.ApplicableTypeValue
                    });
                }

                //Insert missing standard localizations as dummys
                propertySet.localizations = new List <Localization>();
                foreach (string standardLanguage in StandardLanguages.OrderBy(x => x))
                {
                    if (propertySet.localizations.Where(x => x.language == standardLanguage).FirstOrDefault() == null)
                    {
                        propertySet.localizations.Add(new Localization()
                        {
                            language   = standardLanguage,
                            name       = string.Empty,
                            definition = string.Empty
                        });
                    }
                }

                if (CheckBSDD)
                {
                    if (propertySet.dictionaryReference.legacyGuid.Length == 0)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        log.Info($"      ERROR: The GUID is missing in PSet!");
                        Console.ResetColor();
                    }
                }
                IfdConceptList ifdConceptList = _bsdd.SearchNests(pSet.Name);
                if (ifdConceptList == null)
                {
                    log.Info($"      Could not find the PSet in bSDD");
                }
                else
                {
                    numberOfPsetsWithbSDDGuid++;
                    IfdConcept bsddPSet = ifdConceptList.IfdConcept.FirstOrDefault();
                    log.Info($"      Loaded Property from bSDD (1 out of {ifdConceptList.IfdConcept.Count})");
                    log.Info($"      Loaded PSet from bSDD");
                    log.Info($"         Guid:        {bsddPSet.Guid}");
                    log.Info($"         Status:      {bsddPSet.Status}");
                    log.Info($"         VersionDate: {bsddPSet.VersionDate}");
                    log.Info($"         Web:         http://bsdd.buildingsmart.org/#concept/browse/{bsddPSet.Guid}");

                    if (ifdConceptList.IfdConcept.Count == 1)
                    {
                        log.Info($"      The GUID of the PSet in the file was changed {propertySet.dictionaryReference.legacyGuid} => {bsddPSet.Guid}");
                        propertySet.dictionaryReference.ifdGuid = bsddPSet.Guid;
                    }
                }
                propertySet.dictionaryReference.dictionaryWebUri = $"http://bsdd.buildingsmart.org/#concept/browse/{propertySet.dictionaryReference.ifdGuid}";
                propertySet.dictionaryReference.dictionaryApiUri = $"http://bsdd.buildingsmart.org/api/4.0/IfdConcept/{propertySet.dictionaryReference.ifdGuid}";

                log.Info($"   Now checking the properties within the PSet");
                propertySet.properties = LoadProperties(pSet, pSet.PropertyDefs);
                propertySet            = Utils.PrepareTexts(propertySet);

                string targetFileYaml = sourceFile.Replace("xml", "YAML").Replace(sourceFolderXml, targetFolderYaml);
                string targetFileJson = sourceFile.Replace("xml", "json").Replace(sourceFolderXml, targetFolderJson);
                string targetFileResx = sourceFile.Replace("xml", "resx").Replace(sourceFolderXml, targetFolderResx);

                var ScalarStyleSingleQuoted = new YamlMemberAttribute()
                {
                    ScalarStyle = ScalarStyle.SingleQuoted
                };

                var yamlSerializer = new SerializerBuilder()
                                     //.WithNamingConvention(new CamelCaseNamingConvention())
                                     .WithAttributeOverride <PropertySet>(nc => nc.name, ScalarStyleSingleQuoted)
                                     .WithAttributeOverride <PropertySet>(nc => nc.definition, ScalarStyleSingleQuoted)
                                     .WithAttributeOverride <Localization>(nc => nc.name, ScalarStyleSingleQuoted)
                                     .WithAttributeOverride <Localization>(nc => nc.definition, ScalarStyleSingleQuoted)
                                     .Build();

                string yamlContent = yamlSerializer.Serialize(propertySet);
                File.WriteAllText(targetFileYaml, yamlContent, Encoding.UTF8);
                log.Info("The PSet was saved as YAML file");

                JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
                jsonSerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                jsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                string jsonContent = JsonConvert.SerializeObject(propertySet, Formatting.Indented, jsonSerializerSettings);
                File.WriteAllText(targetFileJson, jsonContent, Encoding.UTF8);
                log.Info("The PSet was saved as JSON file");

                var yamlDeserializer = new DeserializerBuilder()
                                       .Build();
                try
                {
                    propertySet = yamlDeserializer.Deserialize <PropertySet>(new StringReader(File.ReadAllText(targetFileYaml)));
                    log.Info("The YAML file is valid");
                }
                catch (Exception ex)
                {
                    Console.Write("   ERROR!");
                    log.Info(ex.Message);
                }


                ResxWriter resx = new ResxWriter(targetFileResx);
                resx.Write(propertySet, StandardLanguages);
                log.Info("The PSet was saved as RESX file");
            }
            log.Info($"Number of PSets:                 {numberOfPsets}");
            log.Info($"   with not resolved bSDD Guid:  {numberOfPsetsWithbSDDGuid}");
            log.Info($"Number of Properties:            {numberOfProperties}");
            log.Info($"   with not resolved bSDD Guid:  {numberOfPropertiesWithbSDDGuid}");
        }
Exemplo n.º 2
0
        private List <Property> LoadProperties(PropertySetDef pset, List <PropertyDef> PropertyDefs)
        {
            List <Property> properties = new List <Property>();

            foreach (PropertyDef psetProperty in PropertyDefs)
            {
                numberOfProperties++;
                log.Info("      .................");
                int itemNumber = 0;
                foreach (var item in psetProperty.Items)
                {
                    string ty = item.ToString();
                    if (item.ToString().Contains("PropertyType"))
                    {
                        break;
                    }
                    itemNumber++;
                }
                PropertyType psetValueType = (PropertyType)psetProperty.Items[itemNumber];
                PropertyTypeTypePropertyBoundedValue    psetBoundedValue    = null;
                PropertyTypeTypeComplexProperty         psetComplexProperty = null;
                PropertyTypeTypePropertyEnumeratedValue psetEnumeratedValue = null;
                PropertyTypeTypePropertyListValue       psetListValue       = null;
                PropertyTypeTypePropertyReferenceValue  psetReferenceValue  = null;
                PropertyTypeTypePropertySingleValue     psetSingleValue     = null;
                PropertyTypeTypePropertyTableValue      psetTableValue      = null;

                string valueTypeAsString = psetValueType.Item.ToString().Replace("PSet2YamlConverter.", "");

                Property property = new Property()
                {
                    name = psetProperty.Items[0].ToString(),
                    dictionaryReference = new DictionaryReference()
                    {
                        dictionaryIdentifier = "http://bsdd.buildingsmart.org",
                        dictionaryNamespace  = "PSet",
                        ifdGuid    = "",
                        legacyGuid = psetProperty.ifdguid,
                        legacyGuidAsIfcGlobalId = Utils.GuidConverterToIfcGuid(psetProperty.ifdguid)
                    },
                    definition = psetProperty.Items[2].ToString()
                };
                log.Info($"      Name: {property.name}");
                if (CheckBSDD)
                {
                    if (property.dictionaryReference.legacyGuidAsIfcGlobalId.Length == 0)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        log.Info($"      ERROR: The GUID for {property.name} is missing in PSet!");
                        Console.ResetColor();
                    }
                }

                if (CheckGuidWithBsdd(property.dictionaryReference.legacyGuidAsIfcGlobalId) == false)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    log.Info($"      ERROR: The GUID {property.dictionaryReference.legacyGuidAsIfcGlobalId} for {property.name} is not resolved by http://bsdd.buildingsmart.org");
                    Console.ResetColor();

                    IfdConceptList ifdConceptList = _bsdd.SearchProperties(pset.Name + "." + property.name);
                    if (ifdConceptList == null)
                    {
                        log.Info($"      Could not find the Property in bSDD");
                    }
                    else
                    {
                        numberOfPropertiesWithbSDDGuid++;
                        IfdConcept bsddProperty = ifdConceptList.IfdConcept.FirstOrDefault();
                        log.Info($"      Loaded Property from bSDD (1 out of {ifdConceptList.IfdConcept.Count})");
                        log.Info($"         Guid:           {bsddProperty.Guid}");
                        log.Info($"         Status:         {bsddProperty.Status}");
                        log.Info($"         VersionDate:    {bsddProperty.VersionDate}");
                        log.Info($"         Web:            http://bsdd.buildingsmart.org/#concept/browse/{bsddProperty.Guid}");
                        foreach (var item in bsddProperty.FullNames)
                        {
                            int    l   = item.Language.LanguageCode.Length;
                            string tab = new string(' ', 10 - l);
                            log.Info($"         Name {item.Language.LanguageCode}:{tab}{item.Name}");
                        }
                        if (ifdConceptList.IfdConcept.Count == 1)
                        {
                            log.Info($"      The GUID in the PSet file was changed {property.dictionaryReference.legacyGuid} => {bsddProperty.Guid}");
                            property.dictionaryReference.ifdGuid = bsddProperty.Guid;
                        }
                    }
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    log.Info($"      OK: The GUID {property.dictionaryReference.legacyGuidAsIfcGlobalId} for {property.name} is properly resolved by http://bsdd.buildingsmart.org");
                    property.dictionaryReference.ifdGuid = property.dictionaryReference.legacyGuidAsIfcGlobalId;
                    Console.ResetColor();
                }
                property.dictionaryReference.dictionaryWebUri = $"http://bsdd.buildingsmart.org/#concept/browse/{property.dictionaryReference.ifdGuid}";
                property.dictionaryReference.dictionaryApiUri = $"http://bsdd.buildingsmart.org/api/4.0/IfdConcept/{property.dictionaryReference.ifdGuid}";
                property.localizations = new List <Localization>();
                PropertyDefNameAliases nameAliases;
                if (psetProperty.Items.Length >= 4)
                {
                    nameAliases = (PropertyDefNameAliases)psetProperty.Items[3];
                    PropertyDefDefinitionAliases definitionAliases = new PropertyDefDefinitionAliases();
                    if (psetProperty.Items.Length >= 5)
                    {
                        definitionAliases = (PropertyDefDefinitionAliases)psetProperty.Items[4];
                    }

                    foreach (var alias in nameAliases.NameAlias)
                    {
                        property.localizations.Add(new Localization()
                        {
                            language   = alias.lang,
                            name       = alias.Value ?? string.Empty,
                            definition = definitionAliases.DefinitionAlias.Where(x => x.lang == alias.lang)?.FirstOrDefault()?.Value ?? string.Empty
                        });
                    }
                }

                //Insert missing standard localizations as dummys
                foreach (string standardLanguage in StandardLanguages.OrderBy(x => x))
                {
                    if (property.localizations.Where(x => x.language == standardLanguage).FirstOrDefault() == null)
                    {
                        property.localizations.Add(new Localization()
                        {
                            language   = standardLanguage,
                            name       = string.Empty,
                            definition = string.Empty
                        });
                    }
                }

                IfcDataType    resultParseIfcDataType;
                ReferenceClass resultParseReferenceClass;

                switch (valueTypeAsString)
                {
                case "PropertyTypeTypePropertyBoundedValue":
                    psetBoundedValue = (PropertyTypeTypePropertyBoundedValue)psetValueType.Item;
                    property.typePropertyBoundedValue          = new TypePropertyBoundedValue();
                    property.typePropertyBoundedValue.typeName = nameof(TypePropertyBoundedValue);
                    Enum.TryParse(psetSingleValue?.DataType?.type.ToString() ?? string.Empty, out resultParseIfcDataType);
                    property.typePropertyBoundedValue.dataType        = resultParseIfcDataType;
                    property.typePropertyBoundedValue.unitType        = psetBoundedValue.UnitType.ToString() ?? string.Empty;
                    property.typePropertyBoundedValue.LowerBoundValue = psetBoundedValue.ValueRangeDef.LowerBoundValue.value?.ToString() ?? string.Empty;
                    property.typePropertyBoundedValue.UpperBoundValue = psetBoundedValue.ValueRangeDef.UpperBoundValue.value?.ToString() ?? string.Empty;
                    break;

                case "PropertyTypeTypeComplexProperty":
                    psetComplexProperty                        = (PropertyTypeTypeComplexProperty)psetValueType.Item;
                    property.typeComplexProperty               = new TypeComplexProperty();
                    property.typeComplexProperty.name          = psetComplexProperty.name ?? string.Empty;
                    property.typeComplexProperty.subProperties = LoadProperties(pset, psetComplexProperty.PropertyDef);    //Recursiv loading
                    break;

                case "PropertyTypeTypePropertyEnumeratedValue":
                    psetEnumeratedValue = (PropertyTypeTypePropertyEnumeratedValue)psetValueType.Item;
                    property.typePropertyEnumeratedValue                   = new TypePropertyEnumeratedValue();
                    property.typePropertyEnumeratedValue.listName          = psetEnumeratedValue.EnumList.name;
                    property.typePropertyEnumeratedValue.enumerationValues = new List <EnumerationValue>();
                    foreach (var enumValue in psetEnumeratedValue.EnumList.EnumItem)
                    {
                        EnumerationValue enumerationValue = new EnumerationValue()
                        {
                            ifdGuid       = string.Empty,// Utils.GuidConverterToIfcGuid(Guid.NewGuid().ToString()),
                            name          = Utils.CleanUp(enumValue),
                            definition    = string.Empty,
                            localizations = new List <Localization>()
                        };

                        foreach (string standardLanguage in StandardLanguages.OrderBy(x => x))
                        {
                            enumerationValue.localizations.Add(new Localization()
                            {
                                language   = standardLanguage,
                                name       = Utils.FirstUpperRestLower(enumValue.ToString()),
                                definition = string.Empty
                            });
                        }

                        property.typePropertyEnumeratedValue.enumerationValues.Add(enumerationValue);
                    }
                    break;

                case "PropertyTypeTypePropertyListValue":
                    psetListValue = (PropertyTypeTypePropertyListValue)psetValueType.Item;
                    property.typePropertyListValue = new TypePropertyListValue();
                    Enum.TryParse(psetListValue?.ListValue.DataType?.type.ToString() ?? string.Empty, out resultParseIfcDataType);
                    property.typePropertyListValue.dataType    = resultParseIfcDataType;
                    property.typePropertyListValue.unitType    = psetListValue?.ListValue.UnitType?.type.ToString() ?? string.Empty;
                    property.typePropertyListValue.measureType = "";
                    if (psetListValue.ListValue.Values.ValueItem.Count > 0)
                    {
                        property.typePropertyListValue.listValues = new List <string>();
                        foreach (string valueItem in psetListValue.ListValue.Values.ValueItem)
                        {
                            property.typePropertyListValue.listValues.Add(valueItem);
                        }
                    }
                    break;

                case "PropertyTypeTypePropertyReferenceValue":
                    psetReferenceValue = (PropertyTypeTypePropertyReferenceValue)psetValueType.Item;
                    property.typePropertyReferenceValue = new TypePropertyReferenceValue();

                    Enum.TryParse(psetReferenceValue.reftype.ToString() ?? string.Empty, out resultParseReferenceClass);
                    property.typePropertyReferenceValue.refType = resultParseReferenceClass;
                    if (property.typePropertyReferenceValue.refType.ToString().StartsWith("Ifc"))
                    {
                        property.typePropertyReferenceValue.guid        = string.Empty;
                        property.typePropertyReferenceValue.url         = "http://buildingsmart-tech.org";
                        property.typePropertyReferenceValue.libraryName = "Industry Foundation Classes by buildingSMART International";
                        property.typePropertyReferenceValue.sectionref  = "Core Schema";
                    }
                    else
                    {
                        property.typePropertyReferenceValue.guid        = string.Empty;
                        property.typePropertyReferenceValue.url         = string.Empty;
                        property.typePropertyReferenceValue.libraryName = string.Empty;
                        property.typePropertyReferenceValue.sectionref  = string.Empty;
                    }
                    break;

                case "PropertyTypeTypePropertySingleValue":
                    psetSingleValue = (PropertyTypeTypePropertySingleValue)psetValueType.Item;
                    property.typePropertySingleValue = new TypePropertySingleValue();
                    Enum.TryParse(psetSingleValue?.DataType?.type.ToString() ?? string.Empty, out resultParseIfcDataType);
                    property.typePropertySingleValue.dataType    = resultParseIfcDataType;
                    property.typePropertySingleValue.unitType    = psetSingleValue?.UnitType?.type.ToString() ?? string.Empty;
                    property.typePropertySingleValue.measureType = "";
                    break;

                case "PropertyTypeTypePropertyTableValue":
                    psetTableValue = (PropertyTypeTypePropertyTableValue)psetValueType.Item;
                    property.typePropertyTableValue            = new TypePropertyTableValue();
                    property.typePropertyTableValue.Expression = psetTableValue.Expression;

                    property.typePropertyTableValue.DefiningValue = new TableDefValues();
                    Enum.TryParse(psetTableValue?.DefiningValue?.DataType?.type.ToString() ?? string.Empty, out resultParseIfcDataType);
                    property.typePropertyTableValue.DefiningValue.dataType    = resultParseIfcDataType;
                    property.typePropertyTableValue.DefiningValue.unitType    = psetTableValue?.DefiningValue.UnitType?.type.ToString() ?? string.Empty;
                    property.typePropertyTableValue.DefiningValue.measureType = "";

                    property.typePropertyTableValue.DefinedValue = new TableDefValues();
                    Enum.TryParse(psetTableValue?.DefinedValue.DataType?.type.ToString() ?? string.Empty, out resultParseIfcDataType);
                    property.typePropertyTableValue.DefinedValue.dataType    = resultParseIfcDataType;
                    property.typePropertyTableValue.DefinedValue.unitType    = psetTableValue?.DefiningValue.UnitType?.type.ToString() ?? string.Empty;
                    property.typePropertyTableValue.DefinedValue.measureType = "";
                    break;
                }
                ;

                property.status = new PublicationStatus()
                {
                    versionNumber     = 4,
                    dateOfVersion     = new DateTime(2018, 1, 1),
                    revisionNumber    = 2,
                    dateOfRevision    = new DateTime(2018, 1, 1),
                    status            = PublicationStatus.Status.Active.ToString(),
                    dateOfCreation    = new DateTime(2018, 1, 1),
                    dateOfActivation  = new DateTime(2018, 1, 1),
                    dateOfLastChange  = new DateTime(2018, 1, 1),
                    languageOfCreator = "en-EN"
                };


                properties.Add(property);
            }

            return(properties);
        }
Exemplo n.º 3
0
        public Converter(string sourceFolderXml, string targetFolderYaml, string targetFolderJson, bool checkBSDD = false)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;

            CheckBSDD = checkBSDD;
            _bsdd     = new Bsdd();

            string propertySetVersionList  = string.Empty;
            string propertySetTemplateList = string.Empty;
            string propertyTypeList        = string.Empty;
            string propertyUnitList        = string.Empty;

            foreach (string sourceFile in Directory.EnumerateFiles(sourceFolderXml, "PSet*.xml").OrderBy(x => x).ToList())//.Where(x=>x.Contains("Pset_ConstructionResource")))
            {
                PropertySetDef pSet = PropertySetDef.LoadFromFile(sourceFile);
                Console.WriteLine("--------------------------------------------------");
                Console.WriteLine($"Checking PSet {pSet.Name}");
                Console.WriteLine($"Opened PSet-File {sourceFile.Replace(sourceFolderXml + @"\", string.Empty)}");
                IfdConceptList ifdConceptList = _bsdd.SearchNests(pSet.Name);
                if (ifdConceptList == null)
                {
                    Console.WriteLine($"Could not find the PSet in bSDD");
                }
                else
                {
                    IfdConcept bsddPSet = ifdConceptList.IfdConcept.FirstOrDefault();
                    Console.WriteLine($"Loaded PSet from bSDD");
                    Console.WriteLine($"Guid:        {bsddPSet.Guid}");
                    Console.WriteLine($"Status:      {bsddPSet.Status}");
                    Console.WriteLine($"VersionDate: {bsddPSet.VersionDate}");
                }


                if (!propertySetVersionList.Contains(pSet.IfcVersion.version))
                {
                    propertySetVersionList += pSet.IfcVersion.version + ",";
                }
                if (!propertySetTemplateList.Contains(pSet.templatetype.ToString()))
                {
                    propertySetTemplateList += pSet.templatetype.ToString() + ",";
                }

                PropertySet propertySet = new PropertySet()
                {
                    name       = pSet.Name,
                    ifdGuid    = "",
                    legacyGuid = "",
                    ifcVersion = new IfcVersion()
                    {
                        version = ConvertToSematicVersion(pSet.IfcVersion.version).ToString(),
                        schema  = pSet.IfcVersion.schema
                    },
                    definition = pSet.Definition
                };

                propertySet.applicableIfcClasses = new List <ApplicableIfcClass>();
                foreach (var applicableClass in pSet.ApplicableClasses)
                {
                    propertySet.applicableIfcClasses.Add(new ApplicableIfcClass()
                    {
                        name = applicableClass,
                        type = pSet.ApplicableTypeValue
                    });
                }

                //Insert missing standard localizations as dummys
                propertySet.localizations = new List <Localization>();
                foreach (string standardLanguage in StandardLanguages.OrderBy(x => x))
                {
                    if (propertySet.localizations.Where(x => x.language == standardLanguage).FirstOrDefault() == null)
                    {
                        propertySet.localizations.Add(new Localization()
                        {
                            language   = standardLanguage,
                            name       = string.Empty,
                            definition = string.Empty
                        });
                    }
                }

                Console.WriteLine($"Now checking the properties within the PSet");
                propertySet.properties = LoadProperties(pSet, pSet.PropertyDefs);
                propertySet            = Utils.PrepareTexts(propertySet);

                string targetFileYaml = sourceFile.Replace("xml", "YAML").Replace(sourceFolderXml, targetFolderYaml);
                string targetFileJson = sourceFile.Replace("xml", "json").Replace(sourceFolderXml, targetFolderJson);
                //Console.WriteLine($"   Writing {targetFileYaml.Replace(targetFolderYaml + @"\", string.Empty)}");
                //Console.WriteLine($"   Writing {targetFileJson.Replace(targetFolderJson + @"\", string.Empty)}");

                var ScalarStyleSingleQuoted = new YamlMemberAttribute()
                {
                    ScalarStyle = ScalarStyle.SingleQuoted
                };

                var yamlSerializer = new SerializerBuilder()
                                     //.WithNamingConvention(new CamelCaseNamingConvention())
                                     .WithAttributeOverride <PropertySet>(nc => nc.name, ScalarStyleSingleQuoted)
                                     .WithAttributeOverride <PropertySet>(nc => nc.definition, ScalarStyleSingleQuoted)
                                     .WithAttributeOverride <Localization>(nc => nc.name, ScalarStyleSingleQuoted)
                                     .WithAttributeOverride <Localization>(nc => nc.definition, ScalarStyleSingleQuoted)
                                     .Build();

                string yamlContent = yamlSerializer.Serialize(propertySet);
                File.WriteAllText(targetFileYaml, yamlContent, Encoding.UTF8);
                Console.WriteLine("The PSet was saved as YAML file");

                JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
                jsonSerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                jsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                string jsonContent = JsonConvert.SerializeObject(propertySet, Formatting.Indented, jsonSerializerSettings);
                File.WriteAllText(targetFileJson, jsonContent, Encoding.UTF8);
                Console.WriteLine("The PSet was saved as JSON file");

                var yamlDeserializer = new DeserializerBuilder()
                                       .Build();
                try
                {
                    propertySet = yamlDeserializer.Deserialize <PropertySet>(new StringReader(File.ReadAllText(targetFileYaml)));
                    Console.WriteLine("The YAML file is valid");
                }
                catch (Exception ex)
                {
                    Console.Write("   ERROR!");
                    Console.WriteLine(ex.Message);
                }
            }
            Console.WriteLine($"Used Versions in PSets: {propertySetVersionList}");
            Console.WriteLine($"Used Templates in PSets: {propertySetTemplateList}");
            Console.WriteLine($"Used PropertyTypes: {propertyTypeList}");
            Console.WriteLine($"Used Units: {propertyUnitList}");
        }
Exemplo n.º 4
0
        public void Save()
        {
            // build map of enumerations
            Dictionary <string, DocPropertyEnumeration> mapPropEnum = new Dictionary <string, DocPropertyEnumeration>();

            foreach (DocPropertyEnumeration docEnum in this.m_project.PropertyEnumerations)
            {
                if (!mapPropEnum.ContainsKey(docEnum.Name))
                {
                    mapPropEnum.Add(docEnum.Name, docEnum);
                }
            }

            using (Package zip = ZipPackage.Open(this.m_stream, FileMode.Create))
            {
                foreach (DocSection docSection in this.m_project.Sections)
                {
                    foreach (DocSchema docSchema in docSection.Schemas)
                    {
                        if (this.m_type == null || this.m_type == typeof(DocPropertySet))
                        {
                            foreach (DocPropertySet docPset in docSchema.PropertySets)
                            {
                                if (m_included == null || this.m_included.ContainsKey(docPset))
                                {
                                    if (docPset.IsVisible())
                                    {
                                        Uri         uri  = PackUriHelper.CreatePartUri(new Uri(docPset.Name + ".xml", UriKind.Relative));
                                        PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
                                        using (Stream refstream = part.GetStream())
                                        {
                                            refstream.SetLength(0);
                                            PropertySetDef psd = Program.ExportPsd(docPset, mapPropEnum, this.m_project);
                                            using (FormatXML format = new FormatXML(refstream, typeof(PropertySetDef), PropertySetDef.DefaultNamespace, null))
                                            {
                                                format.Instance = psd;
                                                format.Save();
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (this.m_type == null || this.m_type == typeof(DocQuantitySet))
                        {
                            foreach (DocQuantitySet docQset in docSchema.QuantitySets)
                            {
                                if (m_included == null || this.m_included.ContainsKey(docQset))
                                {
                                    Uri         uri  = PackUriHelper.CreatePartUri(new Uri(docQset.Name + ".xml", UriKind.Relative));
                                    PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
                                    using (Stream refstream = part.GetStream())
                                    {
                                        refstream.SetLength(0);
                                        QtoSetDef psd = Program.ExportQto(docQset, this.m_project);
                                        using (FormatXML format = new FormatXML(refstream, typeof(QtoSetDef), PropertySetDef.DefaultNamespace, null))
                                        {
                                            format.Instance = psd;
                                            format.Save();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 5
0
        public static void Download(DocProject project, System.ComponentModel.BackgroundWorker worker, string baseurl, string username, string password)
        {
            if (project.Sections[4].Schemas.Count == 0)
            {
                project.Sections[4].Schemas.Add(new DocSchema());
            }

            string url = baseurl + "api/4.0/session/login?email=" + HttpUtility.UrlEncode(username) + "&password="******"POST";
            request.ContentLength = 0;
            request.ContentType   = "application/x-www-form-urlencoded";
            request.Accept        = "application/json";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            System.IO.Stream       stream = response.GetResponseStream();
            System.IO.StreamReader reader = new System.IO.StreamReader(stream);
            string body = reader.ReadToEnd();

            string cookie = response.Headers.Get("Set-Cookie");

            string[] parts     = cookie.Split(new char[] { ';', ',' }); // bug? comma separates session ID
            string   match     = "peregrineapisessionid=";
            string   sessionid = null;

            foreach (string part in parts)
            {
                if (part.StartsWith(match))
                {
                    sessionid = part.Substring(match.Length);
                    break;
                }
            }

            /*-Get all users:
             * var client = new RestClient("http://test.bsdd.buildingsmart.org/api/4.0/IfdUser/");
             * var request = new RestRequest(Method.GET);
             * request.AddHeader("cookie", "peregrineapisessionid=thesessionid");
             * request.AddHeader("accept", "application/json");
             * request.AddHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
             * IRestResponse response = client.Execute(request);*/

            /*- Get all languages:
             * var client = new RestClient("http://test.bsdd.buildingsmart.org/api/4.0/IfdLanguage/");
             * var request = new RestRequest(Method.GET);
             * request.AddHeader("cookie", "peregrineapisessionid={{sessionId}}");
             * request.AddHeader("accept", "application/json");
             * request.AddHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
             * IRestResponse response = client.Execute(request);*/
            request               = (HttpWebRequest)HttpWebRequest.Create(baseurl + "api/4.0/IfdLanguage/");
            request.Method        = "GET";
            request.ContentLength = 0;
            request.ContentType   = "application/x-www-form-urlencoded; charset=UTF-8";
            request.Headers.Add("cookie", "peregrineapisessionid=" + sessionid);
            request.Accept = "application/json";
            response       = (HttpWebResponse)request.GetResponse();

            stream = response.GetResponseStream();
            reader = new System.IO.StreamReader(stream);
            body   = reader.ReadToEnd();

            body.ToString();

            request               = (HttpWebRequest)HttpWebRequest.Create(baseurl + "api/4.0/IfdConcept/search/filter/language/1ASQw0qJqHuO00025QrE$V/type/NEST/Pset_*");
            request.Method        = "GET";
            request.ContentLength = 0;
            request.ContentType   = "application/x-www-form-urlencoded; charset=UTF-8";
            request.Headers.Add("cookie", "peregrineapisessionid=" + sessionid);
            request.Accept = "application/json";
            response       = (HttpWebResponse)request.GetResponse();

            stream = response.GetResponseStream();
            reader = new System.IO.StreamReader(stream);
            body   = reader.ReadToEnd();

            System.IO.Stream       ms     = new System.IO.MemoryStream();
            System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);
            writer.Write(body);
            writer.Flush();
            ms.Position = 0;
            //System.IO.MemoryStream mstream = new System.IO.MemoryStream()

            ResponseSearch ifdRoot;

            try
            {
                DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
                //settings.UseSimpleDictionaryFormat = true;
                System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(ResponseSearch));
                ifdRoot = (ResponseSearch)ser.ReadObject(ms);
            }
            catch
            {
                return;
            }

            // PERF: consider API on server that would return all information at once (currently 150+ round trips)
            for (int iConc = 0; iConc < ifdRoot.IfdConcept.Length; iConc++)
            {
                IfdConcept concept = ifdRoot.IfdConcept[iConc];
                worker.ReportProgress((int)(100.0 * (double)iConc / (double)ifdRoot.IfdConcept.Length));

                // api/4.0/IfdPSet/{guid}/ifcVersion/{ifcVersion}/XML

#if true                                   //figure out version info // language code starting at 5th character then lowercase -- e.g. "IFC-2X4" -> "2x4"
                string ifcversion = "2x4"; // "IFC4";// "ifc-2X4"; //???? what should this be ???? -- code "ifc-2X4" appears in headers; "IFC-2x4" appears in UI; "IFC4" is official schema name
                request               = (HttpWebRequest)HttpWebRequest.Create(baseurl + "api/4.0/IfdPSet/" + concept.guid + "/ifcVersion/" + ifcversion + "/XML");
                request.Method        = "GET";
                request.ContentLength = 0;
                request.ContentType   = "application/x-www-form-urlencoded; charset=UTF-8";
                request.Headers.Add("cookie", "peregrineapisessionid=" + sessionid);
                request.Accept = "application/xml";
#endif
#if false // worked April 1, but no longer works as of 2017-06-13 (http body returns "null" -- as in 4 character string) -- issue with test server -- CoBuilder merge wiped out content??
                request               = (HttpWebRequest)HttpWebRequest.Create(baseurl + "api/4.0/IfdConcept/" + concept.guid + "/children");
                request.Method        = "GET";
                request.ContentLength = 0;
                request.ContentType   = "application/x-www-form-urlencoded; charset=UTF-8";
                request.Headers.Add("cookie", "peregrineapisessionid=" + sessionid);
                request.Accept = "application/json";
                //request.Accept = "application/xml";
#endif
                try
                {
                    response = (HttpWebResponse)request.GetResponse();

                    stream = response.GetResponseStream();


                    reader = new System.IO.StreamReader(stream);
                    body   = reader.ReadToEnd();
                    if (body != null && body != "null") // !!!!
                    {
                        ms     = new MemoryStream();
                        writer = new StreamWriter(ms, Encoding.Unicode);
                        writer.Write(body);
                        writer.Flush();
                        ms.Position = 0;

                        try
                        {
                            using (FormatXML format = new FormatXML(ms, typeof(PropertySetDef), null, null))
                            {
                                format.Load();
                                PropertySetDef psd = (PropertySetDef)format.Instance;
                                Program.ImportPsd(psd, project);
                            }
                        }
                        catch
                        {
                            System.Diagnostics.Debug.WriteLine("Error downloading property set: " + concept.guid.ToString());
                        }


#if false
                        ResponsePset ifdResponse;
                        DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
                        //settings.UseSimpleDictionaryFormat = true;
                        System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(ResponsePset));

                        try
                        {
                            System.IO.Stream       xs      = new System.IO.MemoryStream();
                            System.IO.StreamWriter xwriter = new System.IO.StreamWriter(xs);
                            xwriter.Write(body);
                            xwriter.Flush();
                            xs.Position = 0;

                            ifdResponse = (ResponsePset)ser.ReadObject(xs);

                            ifdResponse.ToString();


                            DocPropertySet docPset = new DocPropertySet();
                            docPset.Uuid = new Guid();// concept.guid;
                            foreach (IfdName ifdName in concept.fullNames)
                            {
                                // if english
                                if (ifdName.languageFamily == "IFC")
                                {
                                    docPset.Name = ifdName.name;
                                }
                                else
                                {
                                    DocLocalization docLoc = new DocLocalization();
                                    docLoc.Locale = ifdName.language.languageCode;
                                    docLoc.Name   = ifdName.name;
                                    docPset.Localization.Add(docLoc);
                                }
                            }
                            docPset.Documentation = concept.definitions.description;
                            project.Sections[4].Schemas[0].PropertySets.Add(docPset);

                            foreach (IfdConceptInRelationship ifdProp in ifdResponse.IfdConceptInRelationship)
                            {
                                //ifdProp.fullNames[0].
                                DocProperty docProp = new DocProperty();
                                if (ifdProp.definitions != null)
                                {
                                    docProp.Documentation = ifdProp.definitions.description;
                                }
                                docPset.Properties.Add(docProp);

                                foreach (IfdName ifdName in ifdProp.fullNames)
                                {
                                    // if english
                                    if (ifdName.languageFamily == "IFC")
                                    {
                                        //docProp.Name = ifdName.name;
                                        string[] nameparts = ifdName.name.Split('.');
                                        if (nameparts.Length == 2)
                                        {
                                            docPset.Name = nameparts[0];
                                            docProp.Name = nameparts[1];
                                        }
                                    }
                                    else
                                    {
                                        DocLocalization docLoc = new DocLocalization();
                                        docLoc.Locale = ifdName.language.languageCode;
                                        docLoc.Name   = ifdName.name;
                                        docProp.Localization.Add(docLoc);
                                    }
                                }
                            }
                        }
#endif
                    }
                }
                catch
                {
                    //...
                    return;
                }
            }
        }