mamift / LinqToXsdCore

LinqToXsd ported to .NET Core (targets .NET Standard 2 for generated code and .NET Core 3.1, .NET 5+ for the code generator CLI tool).
Microsoft Public License
43 stars 15 forks source link

Bug: optional enums #20

Closed jods4 closed 3 years ago

jods4 commented 3 years ago

Generated code doesn't correctly take into account optional enums.

See this excerpt generated from ISO 20022 pain.002.001.03.xsd

        /// <summary>
        /// <para>
        /// Occurrence: optional
        /// </para>
        /// <para>
        /// Regular expression: (StsId?, OrgnlInstrId?, OrgnlEndToEndId?, TxSts?, StsRsnInf*, ChrgsInf*, AccptncDtTm?, AcctSvcrRef?, ClrSysRef?, OrgnlTxRef?)
        /// </para>
        /// </summary>
        public virtual TransactionIndividualStatus3Code TxSts {
            get {
                XElement x = this.GetElement(System.Xml.Linq.XName.Get("TxSts", "urn:iso:std:iso:20022:tech:xsd:pain.002.001.03"));
                return ((TransactionIndividualStatus3Code)(Enum.Parse(typeof(TransactionIndividualStatus3Code), XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype))));
            }
            set {
                this.SetElementWithValidation(System.Xml.Linq.XName.Get("TxSts", "urn:iso:std:iso:20022:tech:xsd:pain.002.001.03"), value.ToString(), "TxSts", global::Iso20022.Pain_002_001_03.TransactionIndividualStatus3CodeValidator.TypeDefinition);
            }
        }

You can see in the comments that this field is correctly described as Occurence: optional and Regex: (... TxSts? ...).

Yet the property type is a non-nullable Enum TransactionIndividualStatus3Code.

If you try to read its value, you don't get 0 but an ArgumentNullException because it calls Enum.Parse passing null as the string value (from XTypedServices.ParseValue<string>).

I think a fix would need to:

Bonus chatter: I am not sure what runtime you support. If you can go with .net core 2.0 / .net standard 2.1 then there's a handy generic Enum.Parse<> that was added.

mamift commented 3 years ago

Are you able to direct me to the schema file(s) that you used? I tried Googling it and could only find this page: https://www.iso20022.org/catalogue-messages/iso-20022-messages-archive

But I don't know which ZIP file to download; there's a lot to filter there.

jods4 commented 3 years ago

Sorry, I thought the bug would be generic enough to not require a specific xsd test case. That excerpt comes from code generated out of ISO pain.002.001.03, which is indeed rather large (not a minimal repro). Here's one copy of that schema: https://github.com/sladjan/xsd-camt/blob/master/src/main/resources/schema/pain.002.001.03.xsd

jods4 commented 3 years ago

I fixed this in PR #21 with a very small one-line change.