private static TBuilder WithOverridesFromJsonPropertyAttributes <TBuilder>(this TBuilder builder) where TBuilder : BuilderSkeleton <TBuilder> { // Use VersionInfo from the model namespace as that should be stable. // If this is not generated in the future we will get an obvious compiler error. var targetNamespace = typeof(VersionInfo).Namespace; // Get all the concrete model types from the code generated namespace. var types = typeof(KubernetesEntityAttribute).Assembly .ExportedTypes .Where(type => type.Namespace == targetNamespace && !type.IsInterface && !type.IsAbstract); // Map any JsonPropertyAttribute instances to YamlMemberAttribute instances. foreach (var type in types) { foreach (var property in type.GetProperties()) { var jsonAttribute = property.GetCustomAttribute <JsonPropertyAttribute>(); if (jsonAttribute == null) { continue; } var yamlAttribute = new YamlMemberAttribute { Alias = jsonAttribute.PropertyName }; builder.WithAttributeOverride(type, property.Name, yamlAttribute); } } return(builder); }
public void AttributeOverridesAndNamingConventionDoNotConflict() { var namingConvention = new CamelCaseNamingConvention(); var yamlMember = new YamlMemberAttribute { Alias = "Required" }; var serializer = new SerializerBuilder() .WithNamingConvention(namingConvention) .WithAttributeOverride <Foo>(f => f.IsRequired, yamlMember) .Build(); var yaml = serializer.Serialize(new Foo { IsRequired = true }); Assert.Contains("required: true", yaml); var deserializer = new DeserializerBuilder() .WithNamingConvention(namingConvention) .WithAttributeOverride <Foo>(f => f.IsRequired, yamlMember) .Build(); var deserializedFoo = deserializer.Deserialize <Foo>(yaml); Assert.True(deserializedFoo.IsRequired); }
public void RoundtripAliasOverride() { var writer = new StringWriter(); var input = new NameConvention { AliasTest = "Fourth" }; var attribute = new YamlMemberAttribute(); attribute.Alias = "fourthOverride"; var serializer = new SerializerBuilder() .WithAttributeOverride <NameConvention>(nc => nc.AliasTest, attribute) .Build(); serializer.Serialize(writer, input, input.GetType()); var text = writer.ToString(); // Todo: use RegEx once FluentAssertions 2.2 is released text.TrimEnd('\r', '\n').Should().Be("fourthOverride: Fourth"); DeserializerBuilder.WithAttributeOverride <NameConvention>(n => n.AliasTest, attribute); var output = Deserializer.Deserialize <NameConvention>(UsingReaderFor(text)); output.AliasTest.Should().Be(input.AliasTest); }
public void SerializationRespectsScalarStyleOverride() { var writer = new StringWriter(); var obj = new ScalarStyleExample(); var overrides = new YamlAttributeOverrides(); var style1 = new YamlMemberAttribute(); style1.ScalarStyle = ScalarStyle.DoubleQuoted; var style2 = new YamlMemberAttribute(); style2.ScalarStyle = ScalarStyle.Literal; overrides.Add(typeof(ScalarStyleExample), "LiteralString", style1); overrides.Add(typeof(ScalarStyleExample), "DoubleQuotedString", style2); var serializer = new Serializer(overrides: overrides); serializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); serialized.Should() .Be("LiteralString: \"Test\"\r\nDoubleQuotedString: |-\r\n Test\r\n", "the properties should be specifically styled"); }
public void RoundtripAliasOverride() { var writer = new StringWriter(); var input = new NameConvention { AliasTest = "Fourth" }; var overrides = new YamlAttributeOverrides(); var attribute = new YamlMemberAttribute(); attribute.Alias = "fourthOverride"; overrides.Add(typeof(NameConvention), "AliasTest", attribute); var serializer = new Serializer(overrides: overrides); serializer.Serialize(writer, input, input.GetType()); var text = writer.ToString(); // Todo: use RegEx once FluentAssertions 2.2 is released text.TrimEnd('\r', '\n').Should().Be("fourthOverride: Fourth"); var deserializer = new Deserializer(overrides: overrides); var output = deserializer.Deserialize <NameConvention>(UsingReaderFor(text)); output.AliasTest.Should().Be(input.AliasTest); }
public override IEnumerable <IPropertyDescriptor> GetProperties(Type type, object container) { var i_result = new List <IPropertyDescriptor>(); if (type.GetCustomAttribute <YamlOnlySerializeSerializableAttribute>() != null) { i_result = (from p in (from p in innerTypeDescriptor.GetProperties(type, container) where p.GetCustomAttribute <YamlSerializableAttribute>() != null && p.GetCustomAttribute <YamlIgnoreAttribute>() == null select p).Select((Func <IPropertyDescriptor, IPropertyDescriptor>) delegate(IPropertyDescriptor p) { PropertyDescriptor propertyDescriptor = new PropertyDescriptor(p); YamlMemberAttribute customAttribute = p.GetCustomAttribute <YamlMemberAttribute>(); if (customAttribute != null) { if (customAttribute.SerializeAs != null) { propertyDescriptor.TypeOverride = customAttribute.SerializeAs; } propertyDescriptor.Order = customAttribute.Order; propertyDescriptor.ScalarStyle = customAttribute.ScalarStyle; if (customAttribute.Alias != null) { propertyDescriptor.Name = customAttribute.Alias; } } return(propertyDescriptor); }) orderby p.Order select p).ToList(); } else { i_result = (from p in (from p in innerTypeDescriptor.GetProperties(type, container) where p.GetCustomAttribute <YamlIgnoreAttribute>() == null select p).Select((Func <IPropertyDescriptor, IPropertyDescriptor>) delegate(IPropertyDescriptor p) { PropertyDescriptor propertyDescriptor = new PropertyDescriptor(p); YamlMemberAttribute customAttribute = p.GetCustomAttribute <YamlMemberAttribute>(); if (customAttribute != null) { if (customAttribute.SerializeAs != null) { propertyDescriptor.TypeOverride = customAttribute.SerializeAs; } propertyDescriptor.Order = customAttribute.Order; propertyDescriptor.ScalarStyle = customAttribute.ScalarStyle; if (customAttribute.Alias != null) { propertyDescriptor.Name = customAttribute.Alias; } } return(propertyDescriptor); }) orderby p.Order select p).ToList(); } return(i_result); }
public override IEnumerable <IPropertyDescriptor> GetProperties(Type type, object container) { return(innerTypeDescriptor.GetProperties(type, container).Select(delegate(IPropertyDescriptor p) { YamlMemberAttribute customAttribute = p.GetCustomAttribute <YamlMemberAttribute>(); if (customAttribute != null && !customAttribute.ApplyNamingConventions) { return p; } return new PropertyDescriptor(p) { Name = namingConvention.Apply(p.Name) }; })); }
public override List <Attribute> GetAttributes(System.Reflection.MemberInfo memberInfo, bool inherit = true) { var attributes = base.GetAttributes(memberInfo, inherit); for (int i = attributes.Count - 1; i >= 0; i--) { var attribute = attributes[i] as DataMemberAttribute; if (attribute != null) { attributes[i] = new YamlMemberAttribute(attribute.Name) { Order = attribute.Order }; } else if (attributes[i] is DataMemberIgnoreAttribute) { attributes[i] = new YamlIgnoreAttribute(); } else if (attributes[i] is DataContractAttribute) { var alias = ((DataContractAttribute)attributes[i]).Alias; if (!string.IsNullOrWhiteSpace(alias)) { attributes[i] = new YamlTagAttribute(alias); } } else if (attributes[i] is DataStyleAttribute) { switch (((DataStyleAttribute)attributes[i]).Style) { case DataStyle.Any: attributes[i] = new YamlStyleAttribute(YamlStyle.Any); break; case DataStyle.Compact: attributes[i] = new YamlStyleAttribute(YamlStyle.Flow); break; case DataStyle.Normal: attributes[i] = new YamlStyleAttribute(YamlStyle.Block); break; } } } return(attributes); }
protected virtual bool PrepareMember(MemberDescriptorBase member) { var memberType = member.Type; // Remove all SyncRoot from members if (member is PropertyDescriptor && member.OriginalName == "SyncRoot" && (member.DeclaringType.Namespace ?? string.Empty).StartsWith(SystemCollectionsNamespace)) { return(false); } // Process all attributes just once instead of getting them one by one var attributes = AttributeRegistry.GetAttributes(member.MemberInfo); YamlStyleAttribute styleAttribute = null; YamlMemberAttribute memberAttribute = null; DefaultValueAttribute defaultValueAttribute = null; foreach (var attribute in attributes) { // Member is not displayed if there is a YamlIgnore attribute on it if (attribute is YamlIgnoreAttribute) { return(false); } if (attribute is YamlMemberAttribute) { memberAttribute = (YamlMemberAttribute)attribute; continue; } if (attribute is DefaultValueAttribute) { defaultValueAttribute = (DefaultValueAttribute)attribute; continue; } if (attribute is YamlStyleAttribute) { styleAttribute = (YamlStyleAttribute)attribute; continue; } var yamlRemap = attribute as YamlRemapAttribute; if (yamlRemap != null) { if (member.AlternativeNames == null) { member.AlternativeNames = new List <string>(); } if (!string.IsNullOrEmpty(yamlRemap.Name)) { member.AlternativeNames.Add(yamlRemap.Name); } } } // If the member has a set, this is a conventional assign method if (member.HasSet) { member.SerializeMemberMode = SerializeMemberMode.Content; } else { // Else we cannot only assign its content if it is a class member.SerializeMemberMode = (memberType != typeof(string) && memberType.GetTypeInfo().IsClass) || memberType.GetTypeInfo().IsInterface || type.IsAnonymous() ? SerializeMemberMode.Content : SerializeMemberMode.Never; } // If it's a private member, check it has a YamlMemberAttribute on it if (!member.IsPublic) { if (memberAttribute == null) { return(false); } } // Gets the style member.Style = styleAttribute != null ? styleAttribute.Style : YamlStyle.Any; member.Mask = 1; // Handle member attribute if (memberAttribute != null) { member.Mask = memberAttribute.Mask; if (!member.HasSet) { if (memberAttribute.SerializeMethod == SerializeMemberMode.Assign || (memberType.GetTypeInfo().IsValueType&& member.SerializeMemberMode == SerializeMemberMode.Content)) { throw new ArgumentException("{0} {1} is not writeable by {2}.".DoFormat(memberType.FullName, member.OriginalName, memberAttribute.SerializeMethod.ToString())); } } if (memberAttribute.SerializeMethod != SerializeMemberMode.Default) { member.SerializeMemberMode = memberAttribute.SerializeMethod; } member.Order = memberAttribute.Order; } if (member.SerializeMemberMode == SerializeMemberMode.Binary) { if (!memberType.IsArray) { throw new InvalidOperationException("{0} {1} of {2} is not an array. Can not be serialized as binary." .DoFormat(memberType.FullName, member.OriginalName, type.FullName)); } if (!memberType.GetElementType().IsPureValueType()) { throw new InvalidOperationException("{0} is not a pure ValueType. {1} {2} of {3} can not serialize as binary.".DoFormat(memberType.GetElementType(), memberType.FullName, member.OriginalName, type.FullName)); } } // If this member cannot be serialized, remove it from the list if (member.SerializeMemberMode == SerializeMemberMode.Never) { return(false); } // ShouldSerialize // YamlSerializeAttribute(Never) => false // ShouldSerializeSomeProperty => call it // DefaultValueAttribute(default) => compare to it // otherwise => true var shouldSerialize = type.GetMethod("ShouldSerialize" + member.OriginalName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (shouldSerialize != null && shouldSerialize.ReturnType == typeof(bool) && member.ShouldSerialize == null) { member.ShouldSerialize = obj => (bool)shouldSerialize.Invoke(obj, EmptyObjectArray); } if (defaultValueAttribute != null && member.ShouldSerialize == null && !emitDefaultValues) { object defaultValue = defaultValueAttribute.Value; Type defaultType = defaultValue == null ? null : defaultValue.GetType(); if (defaultType.IsNumeric() && defaultType != memberType) { defaultValue = memberType.CastToNumericType(defaultValue); } member.ShouldSerialize = obj => !TypeExtensions.AreEqual(defaultValue, member.Get(obj)); } if (member.ShouldSerialize == null) { member.ShouldSerialize = ShouldSerializeDefault; } if (memberAttribute != null && !string.IsNullOrEmpty(memberAttribute.Name)) { member.Name = memberAttribute.Name; } else { member.Name = NamingConvention.Convert(member.OriginalName); } return(true); }
private Attribute RemapToYaml(Attribute originalAttribute) { Attribute attribute = null; var memberAttribute = originalAttribute as DataMemberAttribute; if (memberAttribute != null) { SerializeMemberMode mode; switch (memberAttribute.Mode) { case DataMemberMode.Default: case DataMemberMode.ReadOnly: // ReadOnly is better as default or content? mode = SerializeMemberMode.Default; break; case DataMemberMode.Assign: mode = SerializeMemberMode.Assign; break; case DataMemberMode.Content: mode = SerializeMemberMode.Content; break; case DataMemberMode.Binary: mode = SerializeMemberMode.Binary; break; case DataMemberMode.Never: mode = SerializeMemberMode.Never; break; default: throw new ArgumentOutOfRangeException(); } attribute = new YamlMemberAttribute(memberAttribute.Name, mode) { Order = memberAttribute.Order, Mask = memberAttribute.Mask }; //Trace.WriteLine(string.Format("Attribute remapped {0}", memberAttribute.Name)); } else if (originalAttribute is DataMemberIgnoreAttribute) { attribute = new YamlIgnoreAttribute(); } else if (originalAttribute is DataContractAttribute) { var alias = ((DataContractAttribute)originalAttribute).Alias; if (!string.IsNullOrWhiteSpace(alias)) { attribute = new YamlTagAttribute(alias); } } else if (originalAttribute is DataStyleAttribute) { switch (((DataStyleAttribute)originalAttribute).Style) { case DataStyle.Any: attribute = new YamlStyleAttribute(YamlStyle.Any); break; case DataStyle.Compact: attribute = new YamlStyleAttribute(YamlStyle.Flow); break; case DataStyle.Normal: attribute = new YamlStyleAttribute(YamlStyle.Block); break; } } else if (originalAttribute is DataAliasAttribute) { attribute = new YamlRemapAttribute(((DataAliasAttribute)originalAttribute).Name); } return(attribute ?? originalAttribute); }
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}"); }
public override List <Attribute> GetAttributes(System.Reflection.MemberInfo memberInfo, bool inherit = true) { var attributes = base.GetAttributes(memberInfo, inherit); for (int i = attributes.Count - 1; i >= 0; i--) { var attribute = attributes[i] as DataMemberAttribute; if (attribute != null) { SerializeMemberMode mode; switch (attribute.Mode) { case DataMemberMode.Default: case DataMemberMode.ReadOnly: // ReadOnly is better as default or content? mode = SerializeMemberMode.Default; break; case DataMemberMode.Assign: mode = SerializeMemberMode.Assign; break; case DataMemberMode.Content: mode = SerializeMemberMode.Content; break; case DataMemberMode.Binary: mode = SerializeMemberMode.Binary; break; case DataMemberMode.Never: mode = SerializeMemberMode.Never; break; default: throw new ArgumentOutOfRangeException(); } attributes[i] = new YamlMemberAttribute(attribute.Name, mode) { Order = attribute.Order }; } else if (attributes[i] is DataMemberIgnoreAttribute) { attributes[i] = new YamlIgnoreAttribute(); } else if (attributes[i] is DataContractAttribute) { var alias = ((DataContractAttribute)attributes[i]).Alias; if (!string.IsNullOrWhiteSpace(alias)) { attributes[i] = new YamlTagAttribute(alias); } } else if (attributes[i] is DataStyleAttribute) { switch (((DataStyleAttribute)attributes[i]).Style) { case DataStyle.Any: attributes[i] = new YamlStyleAttribute(YamlStyle.Any); break; case DataStyle.Compact: attributes[i] = new YamlStyleAttribute(YamlStyle.Flow); break; case DataStyle.Normal: attributes[i] = new YamlStyleAttribute(YamlStyle.Block); break; } } } return(attributes); }
public YamlTranslationWriter(string translationSourceFile, string folderYaml, string folderJson, string folderResx) { log.Info($"Inject the translation into the YAML files from this source table: {translationSourceFile}"); if (translationSourceFile != null) { log.Info($"Inject translations from {translationSourceFile}"); } if (folderYaml != null) { log.Info($"Inject into YAML files in this target folder: {folderYaml}"); } if (folderJson != null) { log.Info($"Inject into JSON files in this target folder: {folderJson}"); } if (folderResx != null) { log.Info($"Inject into RESX files in this target folder: {folderResx}"); } if (translationSourceFile == null) { log.Error($"ERROR - The parameter translationSourceFile does not exist. Exiting!"); return; } else if (!File.Exists(translationSourceFile)) { log.Error($"ERROR - File {translationSourceFile} does not exist. Exiting!"); return; } if (folderYaml == null) { log.Error($"ERROR - The parameter folderXml does not exist. Exiting!"); return; } else if (!Directory.Exists(folderYaml)) { log.Error($"ERROR - The Directory {folderYaml} does not exist. Exiting!"); return; } if (folderJson != null) { if (!Directory.Exists(folderJson)) { log.Error($"ERROR - The Directory {folderJson} does not exist. Exiting!"); return; } } if (folderResx != null) { if (!Directory.Exists(folderResx)) { log.Error($"ERROR - The Directory {folderResx} does not exist. Exiting!"); return; } } foreach (Translation translation in ReadTranslationDataFromExcel(translationSourceFile)) { string yamlFileName = Path.Combine(folderYaml, $"{translation.pset}.YAML"); var yamlDeserializer = new DeserializerBuilder().Build(); PropertySet propertySet; try { propertySet = yamlDeserializer.Deserialize <PropertySet>(new StringReader(File.ReadAllText(yamlFileName))); log.Info($"Opened the YAML file {yamlFileName}"); } catch (Exception ex) { log.Error(ex.Message); return; } 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(); switch (translation.type) { case "PSet": log.Info($"Translate PSet {translation.pset} => {translation.name_TL} [{translation.language}]"); var localizationPSet = propertySet.localizations.Where(x => x.language.ToLower() == translation.language.ToLower()).FirstOrDefault(); localizationPSet.name = translation.name_TL; localizationPSet.definition = translation.definition_tl; string yamlContentPSet = yamlSerializer.Serialize(propertySet); File.WriteAllText(yamlFileName, yamlContentPSet, Encoding.UTF8); break; case "Property": log.Info($"Translated Property {translation.pset}.{translation.name} => {translation.name_TL} [{translation.language}]"); try { var localizationProperty = propertySet.properties.Where(x => x.name == translation.name).FirstOrDefault().localizations.Where(x => x.language.ToLower() == translation.language.ToLower()).FirstOrDefault(); localizationProperty.name = translation.name_TL; localizationProperty.definition = translation.definition_tl; string yamlContentProperty = yamlSerializer.Serialize(propertySet); File.WriteAllText(yamlFileName, yamlContentProperty, Encoding.UTF8); } catch (Exception ex) { log.Error($"ERROR: {ex.Message}"); } break; } if (folderJson != null) { string targetFileJson = yamlFileName.Replace(".YAML", ".json").Replace(folderYaml, folderJson); 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"); } if (folderResx != null) { string targetFileResx = yamlFileName.Replace(".YAML", ".resx").Replace(folderYaml, folderResx); ResxWriter resx = new ResxWriter(targetFileResx); resx.Write(propertySet, StandardLanguages); log.Info("The PSet was saved as RESX file"); } } }
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}"); }