Inheritance: PrimitiveMapping
        internal CodeTypeDeclaration ExportEnum(EnumMapping mapping, Type type)
        {
            CodeTypeDeclaration codeClass = new CodeTypeDeclaration(mapping.TypeDesc.Name);

            codeClass.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true));
            codeClass.IsEnum = true;
            if (mapping.IsFlags && mapping.Constants.Length > 31)
            {
                codeClass.BaseTypes.Add(new CodeTypeReference(typeof(long)));
            }
            codeClass.TypeAttributes |= TypeAttributes.Public;
            CodeNamespace.Types.Add(codeClass);
            for (int i = 0; i < mapping.Constants.Length; i++)
            {
                ExportConstant(codeClass, mapping.Constants[i], type, mapping.IsFlags, 1L << i);
            }
            if (mapping.IsFlags)
            {
                // Add [FlagsAttribute]
                CodeAttributeDeclaration flags = new CodeAttributeDeclaration(typeof(FlagsAttribute).FullName);
                codeClass.CustomAttributes.Add(flags);
            }
            CodeGenerator.ValidateIdentifiers(codeClass);
            return(codeClass);
        }
Ejemplo n.º 2
0
        private string WriteEnumMethod(EnumMapping mapping, object v)
        {
            string returnString = null;

            if (mapping != null)
            {
                ConstantMapping[] constants = mapping.Constants;
                if (constants.Length > 0)
                {
                    bool foundValue = false;
                    var  enumValue  = Convert.ToInt64(v);
                    for (int i = 0; i < constants.Length; i++)
                    {
                        ConstantMapping c = constants[i];
                        if (enumValue == c.Value)
                        {
                            returnString = c.XmlName;
                            foundValue   = true;
                            break;
                        }
                    }

                    if (!foundValue)
                    {
                        if (mapping.IsFlags)
                        {
                            string[] xmlNames = new string[constants.Length];
                            long[]   valueIds = new long[constants.Length];

                            for (int i = 0; i < constants.Length; i++)
                            {
                                xmlNames[i] = constants[i].XmlName;
                                valueIds[i] = constants[i].Value;
                            }

                            returnString = FromEnum(enumValue, xmlNames, valueIds);
                        }
                        else
                        {
                            throw CreateInvalidEnumValueException(v, mapping.TypeDesc.FullName);
                        }
                    }
                }
            }
            else
            {
                returnString = v.ToString();
            }

            if (mapping.IsSoap)
            {
                WriteXsiType(mapping.TypeName, mapping.Namespace);
                Writer.WriteString(returnString);
                return(null);
            }
            else
            {
                return(returnString);
            }
        }
Ejemplo n.º 3
0
        private string WriteEnumMethod(EnumMapping mapping, object v)
        {
            if (mapping != null && mapping.IsSoap)
            {
                throw new PlatformNotSupportedException();
            }

            if (mapping != null && mapping.IsFlags)
            {
                Type type = mapping.TypeDesc.Type;

                List <string> valueStrings = new List <string>();
                List <long>   valueIds     = new List <long>();
                foreach (var value in Enum.GetValues(type))
                {
                    valueStrings.Add(value.ToString());
                    valueIds.Add(Convert.ToInt64(value));
                }

                return(FromEnum(Convert.ToInt64(v), valueStrings.ToArray(), valueIds.ToArray()));
            }
            else
            {
                return(v.ToString());
            }
        }
Ejemplo n.º 4
0
        private TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, bool isList)
        {
            TypeMapping mapping = (TypeMapping)base.ImportedMappings[dataType];

            if (mapping != null)
            {
                return(mapping);
            }
            XmlSchemaSimpleType type     = this.FindDataType(dataType.DerivedFrom);
            TypeDesc            typeDesc = base.Scope.GetTypeDesc(type);

            if ((typeDesc != null) && (typeDesc != base.Scope.GetTypeDesc(typeof(string))))
            {
                return(this.ImportPrimitiveDataType(dataType));
            }
            identifier = Accessor.UnescapeName(identifier);
            string      name     = base.GenerateUniqueTypeName(identifier);
            EnumMapping mapping2 = new EnumMapping {
                IsReference = base.Schemas.IsReference(dataType),
                TypeDesc    = new TypeDesc(name, name, TypeKind.Enum, null, TypeFlags.None),
                TypeName    = identifier,
                Namespace   = typeNs,
                IsFlags     = isList
            };
            CodeIdentifiers identifiers = new CodeIdentifiers();

            if (!(dataType.Content is XmlSchemaSimpleTypeRestriction))
            {
                throw new InvalidOperationException(Res.GetString("XmlInvalidEnumContent", new object[] { dataType.Content.GetType().Name, identifier }));
            }
            XmlSchemaSimpleTypeRestriction content = (XmlSchemaSimpleTypeRestriction)dataType.Content;

            for (int i = 0; i < content.Facets.Count; i++)
            {
                object obj2 = content.Facets[i];
                if (obj2 is XmlSchemaEnumerationFacet)
                {
                    XmlSchemaEnumerationFacet facet    = (XmlSchemaEnumerationFacet)obj2;
                    ConstantMapping           mapping3 = new ConstantMapping();
                    string str2 = CodeIdentifier.MakeValid(facet.Value);
                    mapping3.Name    = identifiers.AddUnique(str2, mapping3);
                    mapping3.XmlName = facet.Value;
                    mapping3.Value   = i;
                }
            }
            mapping2.Constants = (ConstantMapping[])identifiers.ToArray(typeof(ConstantMapping));
            if (isList && (mapping2.Constants.Length > 0x3f))
            {
                mapping = new PrimitiveMapping {
                    TypeDesc = base.Scope.GetTypeDesc(typeof(string)),
                    TypeName = mapping.TypeDesc.DataType.Name
                };
                base.ImportedMappings.Add(dataType, mapping);
                return(mapping);
            }
            base.ImportedMappings.Add(dataType, mapping2);
            base.Scope.AddTypeMapping(mapping2);
            return(mapping2);
        }
 private object ImportDefaultValue(TypeMapping mapping, string defaultValue)
 {
     if (defaultValue == null)
     {
         return(null);
     }
     if (mapping is PrimitiveMapping)
     {
         if (mapping is EnumMapping)
         {
             EnumMapping       mapping2  = (EnumMapping)mapping;
             ConstantMapping[] constants = mapping2.Constants;
             if (mapping2.IsFlags)
             {
                 Hashtable vals     = new Hashtable();
                 string[]  strArray = new string[constants.Length];
                 long[]    ids      = new long[constants.Length];
                 for (int j = 0; j < constants.Length; j++)
                 {
                     ids[j]      = mapping2.IsFlags ? (((long)1L) << j) : ((long)j);
                     strArray[j] = constants[j].Name;
                     vals.Add(constants[j].Name, ids[j]);
                 }
                 return(XmlCustomFormatter.FromEnum(XmlCustomFormatter.ToEnum(defaultValue, vals, mapping2.TypeName, true), strArray, ids, mapping2.TypeDesc.FullName));
             }
             for (int i = 0; i < constants.Length; i++)
             {
                 if (constants[i].XmlName == defaultValue)
                 {
                     return(constants[i].Name);
                 }
             }
             throw new InvalidOperationException(Res.GetString("XmlInvalidDefaultValue", new object[] { defaultValue, mapping2.TypeDesc.FullName }));
         }
         PrimitiveMapping mapping3 = (PrimitiveMapping)mapping;
         if (!mapping3.TypeDesc.HasCustomFormatter)
         {
             if (mapping3.TypeDesc.FormatterName == "String")
             {
                 return(defaultValue);
             }
             if (mapping3.TypeDesc.FormatterName == "DateTime")
             {
                 return(XmlCustomFormatter.ToDateTime(defaultValue));
             }
             Type       type   = typeof(XmlConvert);
             MethodInfo method = type.GetMethod("To" + mapping3.TypeDesc.FormatterName, new Type[] { typeof(string) });
             if (method != null)
             {
                 return(method.Invoke(type, new object[] { defaultValue }));
             }
         }
         else if (mapping3.TypeDesc.HasDefaultSupport)
         {
             return(XmlCustomFormatter.ToDefaultValue(defaultValue, mapping3.TypeDesc.FormatterName));
         }
     }
     return(DBNull.Value);
 }
Ejemplo n.º 6
0
        internal string GetStringForEnumCompare(EnumMapping mapping, string memberName, bool useReflection)
        {
            if (!useReflection)
            {
                CodeIdentifier.CheckValidIdentifier(memberName);
                return(mapping.TypeDesc.CSharpName + ".@" + memberName);
            }
            string variable = this.GetStringForEnumMember(mapping.TypeDesc.CSharpName, memberName, useReflection);

            return(this.GetStringForEnumLongValue(variable, useReflection));
        }
 private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMapping, bool useReflection)
 {
     string ident = null;
     for (int i = 0; i < choiceMapping.Constants.Length; i++)
     {
         string xmlName = choiceMapping.Constants[i].XmlName;
         if (element.Any && (element.Name.Length == 0))
         {
             if (!(xmlName == "##any:"))
             {
                 continue;
             }
             if (useReflection)
             {
                 ident = choiceMapping.Constants[i].Value.ToString(CultureInfo.InvariantCulture);
             }
             else
             {
                 ident = choiceMapping.Constants[i].Name;
             }
             break;
         }
         int length = xmlName.LastIndexOf(':');
         string str3 = (length < 0) ? choiceMapping.Namespace : xmlName.Substring(0, length);
         string str4 = (length < 0) ? xmlName : xmlName.Substring(length + 1);
         if ((element.Name == str4) && (((element.Form == XmlSchemaForm.Unqualified) && string.IsNullOrEmpty(str3)) || (element.Namespace == str3)))
         {
             if (useReflection)
             {
                 ident = choiceMapping.Constants[i].Value.ToString(CultureInfo.InvariantCulture);
             }
             else
             {
                 ident = choiceMapping.Constants[i].Name;
             }
             break;
         }
     }
     if ((ident == null) || (ident.Length == 0))
     {
         if (element.Any && (element.Name.Length == 0))
         {
             throw new InvalidOperationException(Res.GetString("XmlChoiceMissingAnyValue", new object[] { choiceMapping.TypeDesc.FullName }));
         }
         throw new InvalidOperationException(Res.GetString("XmlChoiceMissingValue", new object[] { choiceMapping.TypeDesc.FullName, element.Namespace + ":" + element.Name, element.Name, element.Namespace }));
     }
     if (!useReflection)
     {
         CodeIdentifier.CheckValidIdentifier(ident);
     }
     return ident;
 }
Ejemplo n.º 8
0
        private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, string n, string ns, XmlMapping parentMapping)
        {
            if (o is Enum)
            {
                Writer.WriteStartElement(n, ns);

                EnumMapping enumMapping = null;
                Type        enumType    = o.GetType();
                foreach (var m in parentMapping.Scope.TypeMappings)
                {
                    var em = m as EnumMapping;
                    if (em != null && em.TypeDesc.Type == enumType)
                    {
                        enumMapping = em;
                        break;
                    }
                }

                Debug.Assert(enumMapping != null);

                WriteXsiType(enumMapping.TypeName, ns);
                Writer.WriteString(WriteEnumMethod(enumMapping, o));
                Writer.WriteEndElement();
                return(true);
            }

            if (o is Array)
            {
                Debug.Assert(parentMapping != null);
                Writer.WriteStartElement(n, ns);
                ArrayMapping arrayMapping = null;
                Type         arrayType    = o.GetType();
                foreach (var m in parentMapping.Scope.TypeMappings)
                {
                    var am = m as ArrayMapping;
                    if (am != null && am.TypeDesc.Type == arrayType)
                    {
                        arrayMapping = am;
                        break;
                    }
                }

                Debug.Assert(arrayMapping != null);
                WriteXsiType(arrayMapping.TypeName, ns);
                WriteMember(o, null, arrayMapping.ElementsSortedByDerivation, null, null, arrayMapping.TypeDesc, true);
                Writer.WriteEndElement();

                return(true);
            }

            return(false);
        }
Ejemplo n.º 9
0
        private Dictionary <string, long> WriteHashtable(EnumMapping mapping, string name)
        {
            var h = new Dictionary <string, long>();

            ConstantMapping[] constants = mapping.Constants;

            for (int i = 0; i < constants.Length; i++)
            {
                h.Add(constants[i].XmlName, constants[i].Value);
            }

            return(h);
        }
Ejemplo n.º 10
0
        TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier)
        {
            EnumMapping enumMapping = (EnumMapping)mappings[dataType];

            if (enumMapping != null)
            {
                return(enumMapping);
            }
            XmlSchemaSimpleType sourceDataType = FindDataType(dataType.DerivedFrom);
            TypeDesc            sourceTypeDesc = scope.GetTypeDesc(sourceDataType);

            if (sourceTypeDesc != null && sourceTypeDesc != scope.GetTypeDesc(typeof(string)))
            {
                return(ImportPrimitiveDataType(dataType));
            }
            string typeName = GenerateUniqueTypeName(identifier);

            enumMapping           = new EnumMapping();
            enumMapping.TypeDesc  = new TypeDesc(typeName, typeName, TypeKind.Enum, null, 0);
            enumMapping.TypeName  = identifier;
            enumMapping.Namespace = typeNs;
            enumMapping.IsFlags   = false;
            mappings.Add(dataType, enumMapping);
            CodeIdentifiers constants = new CodeIdentifiers();

            if (!(dataType.Content is XmlSchemaSimpleTypeRestriction))
            {
                throw new InvalidOperationException(Res.GetString(Res.XmlInvalidEnumContent, dataType.Content.GetType().Name, identifier));
            }

            XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)dataType.Content;

            for (int i = 0; i < restriction.Facets.Count; i++)
            {
                object facet = restriction.Facets[i];
                if (!(facet is XmlSchemaEnumerationFacet))
                {
                    continue;
                }
                XmlSchemaEnumerationFacet enumeration = (XmlSchemaEnumerationFacet)facet;
                ConstantMapping           constant    = new ConstantMapping();
                string constantName = CodeIdentifier.MakeValid(enumeration.Value);
                constant.Name    = constants.AddUnique(constantName, constant);
                constant.XmlName = enumeration.Value;
                constant.Value   = i;
            }
            enumMapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping));
            scope.AddTypeMapping(enumMapping);
            return(enumMapping);
        }
        EnumMapping ImportEnumMapping(EnumModel model)
        {
            SoapAttributes a      = GetAttributes(model.Type);
            string         typeNs = defaultNs;

            if (a.SoapType != null && a.SoapType.Namespace != null)
            {
                typeNs = a.SoapType.Namespace;
            }

            string typeName = string.Empty;

            if (a.SoapType != null)
            {
                typeName = a.SoapType.TypeName;
            }
            if (typeName.Length == 0)
            {
                typeName = model.TypeDesc.Name;
            }

            EnumMapping mapping = (EnumMapping)GetTypeMapping(typeName, typeNs, model.TypeDesc);

            if (mapping == null)
            {
                mapping           = new EnumMapping();
                mapping.IsSoap    = true;
                mapping.TypeDesc  = model.TypeDesc;
                mapping.TypeName  = typeName;
                mapping.Namespace = typeNs;
                mapping.IsFlags   = model.Type.IsDefined(typeof(FlagsAttribute), false);
                typeScope.AddTypeMapping(mapping);
                types.Add(typeName, typeNs, mapping);
                ArrayList constants = new ArrayList();
                for (int i = 0; i < model.Constants.Length; i++)
                {
                    ConstantMapping constant = ImportConstantMapping(model.Constants[i]);
                    if (constant != null)
                    {
                        constants.Add(constant);
                    }
                }
                if (constants.Count == 0)
                {
                    throw new InvalidOperationException(Res.GetString(Res.XmlNoSerializableMembers, model.TypeDesc.FullName));
                }
                mapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping));
            }
            return(mapping);
        }
Ejemplo n.º 12
0
        XmlQualifiedName ExportEnumMapping(EnumMapping mapping, string ns)
        {
            if (!mapping.IncludeInSchema)
            {
                throw new InvalidOperationException(Res.GetString(Res.XmlCannotIncludeInSchema, mapping.TypeDesc.Name));
            }
            XmlSchemaSimpleType dataType = (XmlSchemaSimpleType)types[mapping];

            if (dataType == null)
            {
                CheckForDuplicateType(mapping.TypeName, mapping.Namespace);
                dataType      = new XmlSchemaSimpleType();
                dataType.Name = mapping.TypeName;
                types.Add(mapping, dataType);
                AddSchemaItem(dataType, mapping.Namespace, ns);

                XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();
                restriction.BaseTypeName = new XmlQualifiedName("string", XmlSchema.Namespace);

                for (int i = 0; i < mapping.Constants.Length; i++)
                {
                    ConstantMapping           constant    = mapping.Constants[i];
                    XmlSchemaEnumerationFacet enumeration = new XmlSchemaEnumerationFacet();
                    enumeration.Value = constant.XmlName;
                    restriction.Facets.Add(enumeration);
                }
                if (!mapping.IsFlags)
                {
                    dataType.Content = restriction;
                }
                else
                {
                    XmlSchemaSimpleTypeList list     = new XmlSchemaSimpleTypeList();
                    XmlSchemaSimpleType     enumType = new XmlSchemaSimpleType();
                    enumType.Content = restriction;
                    list.ItemType    = enumType;
                    dataType.Content = list;
                }
            }
            else
            {
                AddSchemaImport(mapping.Namespace, ns);
            }
            return(new XmlQualifiedName(dataType.Name, mapping.Namespace));
        }
Ejemplo n.º 13
0
        void ExportEnum(EnumMapping mapping)
        {
            CodeTypeDeclaration codeClass = new CodeTypeDeclaration(mapping.TypeDesc.Name);

            codeClass.IsEnum          = true;
            codeClass.TypeAttributes |= TypeAttributes.Public;
            codeClass.Comments.Add(new CodeCommentStatement("<remarks/>", true));
            codeNamespace.Types.Add(codeClass);
            codeClass.CustomAttributes = new CodeAttributeDeclarationCollection();
            AddTypeMetadata(codeClass.CustomAttributes, mapping.TypeName, mapping.Namespace, mapping.IncludeInSchema);

            for (int i = 0; i < mapping.Constants.Length; i++)
            {
                ExportConstant(codeClass, mapping.Constants[i]);
            }
            if (mapping.IsFlags)
            {
                AddCustomAttribute(codeClass.CustomAttributes, typeof(FlagsAttribute), new CodeAttributeArgument[0]);
            }
        }
 private XmlQualifiedName ExportEnumMapping(EnumMapping mapping, string ns)
 {
     if (((XmlSchemaSimpleType)this.types[mapping]) == null)
     {
         this.CheckForDuplicateType(mapping.TypeName, mapping.Namespace);
         XmlSchemaSimpleType type = new XmlSchemaSimpleType {
             Name = mapping.TypeName
         };
         this.types.Add(mapping, type);
         this.AddSchemaItem(type, mapping.Namespace, ns);
         XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction {
             BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")
         };
         for (int i = 0; i < mapping.Constants.Length; i++)
         {
             ConstantMapping           mapping2 = mapping.Constants[i];
             XmlSchemaEnumerationFacet item     = new XmlSchemaEnumerationFacet {
                 Value = mapping2.XmlName
             };
             restriction.Facets.Add(item);
         }
         if (!mapping.IsFlags)
         {
             type.Content = restriction;
         }
         else
         {
             XmlSchemaSimpleTypeList list  = new XmlSchemaSimpleTypeList();
             XmlSchemaSimpleType     type2 = new XmlSchemaSimpleType {
                 Content = restriction
             };
             list.ItemType = type2;
             type.Content  = list;
         }
     }
     else
     {
         this.AddSchemaImport(mapping.Namespace, ns);
     }
     return(new XmlQualifiedName(mapping.TypeName, mapping.Namespace));
 }
Ejemplo n.º 15
0
        private object WriteEnumMethod(EnumMapping mapping, Func <string> readFunc)
        {
            if (mapping.IsSoap)
            {
                // #10676: As all SOAP relates APIs are not in CoreCLR yet, the reflection based method
                // currently throws PlatformNotSupportedException when types require SOAP serialization.
                throw new PlatformNotSupportedException();
            }

            string source = readFunc();

            if (mapping.IsFlags)
            {
                Dictionary <string, long> table = WriteHashtable(mapping, mapping.TypeDesc.Name);
                return(Enum.ToObject(mapping.TypeDesc.Type, ToEnum(source, table, mapping.TypeDesc.Name)));
            }
            else
            {
                return(Enum.Parse(mapping.TypeDesc.Type, source));
            }
        }
Ejemplo n.º 16
0
        private EnumMapping ImportEnumMapping(EnumModel model)
        {
            SoapAttributes a         = this.GetAttributes(model.Type);
            string         defaultNs = this.defaultNs;

            if ((a.SoapType != null) && (a.SoapType.Namespace != null))
            {
                defaultNs = a.SoapType.Namespace;
            }
            string      typeName    = XmlConvert.EncodeLocalName(this.XsdTypeName(model.Type, a, model.TypeDesc.Name));
            EnumMapping typeMapping = (EnumMapping)this.GetTypeMapping(typeName, defaultNs, model.TypeDesc);

            if (typeMapping == null)
            {
                typeMapping = new EnumMapping {
                    IsSoap    = true,
                    TypeDesc  = model.TypeDesc,
                    TypeName  = typeName,
                    Namespace = defaultNs,
                    IsFlags   = model.Type.IsDefined(typeof(FlagsAttribute), false)
                };
                this.typeScope.AddTypeMapping(typeMapping);
                this.types.Add(typeName, defaultNs, typeMapping);
                ArrayList list = new ArrayList();
                for (int i = 0; i < model.Constants.Length; i++)
                {
                    ConstantMapping mapping2 = this.ImportConstantMapping(model.Constants[i]);
                    if (mapping2 != null)
                    {
                        list.Add(mapping2);
                    }
                }
                if (list.Count == 0)
                {
                    throw new InvalidOperationException(Res.GetString("XmlNoSerializableMembers", new object[] { model.TypeDesc.FullName }));
                }
                typeMapping.Constants = (ConstantMapping[])list.ToArray(typeof(ConstantMapping));
            }
            return(typeMapping);
        }
        internal CodeTypeDeclaration ExportEnum(EnumMapping mapping, Type type)
        {
            CodeTypeDeclaration declaration = new CodeTypeDeclaration(mapping.TypeDesc.Name);

            declaration.Comments.Add(new CodeCommentStatement(Res.GetString("XmlRemarks"), true));
            declaration.IsEnum = true;
            if (mapping.IsFlags && (mapping.Constants.Length > 0x1f))
            {
                declaration.BaseTypes.Add(new CodeTypeReference(typeof(long)));
            }
            declaration.TypeAttributes |= TypeAttributes.Public;
            this.CodeNamespace.Types.Add(declaration);
            for (int i = 0; i < mapping.Constants.Length; i++)
            {
                ExportConstant(declaration, mapping.Constants[i], type, mapping.IsFlags, ((long)1L) << i);
            }
            if (mapping.IsFlags)
            {
                CodeAttributeDeclaration declaration2 = new CodeAttributeDeclaration(typeof(FlagsAttribute).FullName);
                declaration.CustomAttributes.Add(declaration2);
            }
            CodeGenerator.ValidateIdentifiers(declaration);
            return(declaration);
        }
Ejemplo n.º 18
0
        private TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, TypeFlags flags, bool isList)
        {
            TypeMapping mapping = (TypeMapping)ImportedMappings[dataType];
            if (mapping != null)
                return mapping;

            XmlSchemaType sourceType = dataType;
            while (!sourceType.DerivedFrom.IsEmpty)
            {
                sourceType = FindType(sourceType.DerivedFrom, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue);
            }
            if (sourceType is XmlSchemaComplexType) return null;
            TypeDesc sourceTypeDesc = Scope.GetTypeDesc((XmlSchemaSimpleType)sourceType);
            if (sourceTypeDesc != null && sourceTypeDesc.FullName != typeof(string).FullName)
                return ImportPrimitiveDataType(dataType, flags);
            identifier = Accessor.UnescapeName(identifier);
            string typeName = GenerateUniqueTypeName(identifier);
            EnumMapping enumMapping = new EnumMapping();
            enumMapping.IsReference = Schemas.IsReference(dataType);
            enumMapping.TypeDesc = new TypeDesc(typeName, typeName, TypeKind.Enum, null, 0);
            if (dataType.Name != null && dataType.Name.Length > 0)
                enumMapping.TypeName = identifier;
            enumMapping.Namespace = typeNs;
            enumMapping.IsFlags = isList;

            CodeIdentifiers constants = new CodeIdentifiers();
            XmlSchemaSimpleTypeContent content = dataType.Content;

            if (content is XmlSchemaSimpleTypeRestriction)
            {
                XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)content;
                for (int i = 0; i < restriction.Facets.Count; i++)
                {
                    object facet = restriction.Facets[i];
                    if (!(facet is XmlSchemaEnumerationFacet)) continue;
                    XmlSchemaEnumerationFacet enumeration = (XmlSchemaEnumerationFacet)facet;
                    // validate the enumeration value
                    if (sourceTypeDesc != null && sourceTypeDesc.HasCustomFormatter)
                    {
                        XmlCustomFormatter.ToDefaultValue(enumeration.Value, sourceTypeDesc.FormatterName);
                    }
                    ConstantMapping constant = new ConstantMapping();
                    string constantName = CodeIdentifier.MakeValid(enumeration.Value);
                    constant.Name = constants.AddUnique(constantName, constant);
                    constant.XmlName = enumeration.Value;
                    constant.Value = i;
                }
            }
            enumMapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping));
            if (isList && enumMapping.Constants.Length > 63)
            {
                // if we have 64+ flag constants we cannot map the type to long enum, we will use string mapping instead.
                mapping = GetDefaultMapping(TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.CanBeAttributeValue);
                ImportedMappings.Add(dataType, mapping);
                return mapping;
            }
            ImportedMappings.Add(dataType, enumMapping);
            Scope.AddTypeMapping(enumMapping);
            return enumMapping;
        }
        string WriteHashtable(EnumMapping mapping, string typeName) {

            CodeIdentifier.CheckValidIdentifier(typeName);
            string propName = MakeUnique(mapping, typeName + "Values");
            if (propName == null) return CodeIdentifier.GetCSharpName(typeName);
            string memberName = MakeUnique(mapping, "_" + propName);
            propName = CodeIdentifier.GetCSharpName(propName);

            Writer.WriteLine();
            Writer.Write(typeof(Hashtable).FullName);
            Writer.Write(" ");
            Writer.Write(memberName);
            Writer.WriteLine(";");
            Writer.WriteLine();

            Writer.Write("internal ");
            Writer.Write(typeof(Hashtable).FullName);
            Writer.Write(" ");
            Writer.Write(propName);
            Writer.WriteLine(" {");
            Writer.Indent++;

            Writer.WriteLine("get {");
            Writer.Indent++;

            Writer.Write("if ((object)");
            Writer.Write(memberName);
            Writer.WriteLine(" == null) {");
            Writer.Indent++;

            Writer.Write(typeof(Hashtable).FullName);
            Writer.Write(" h = new ");
            Writer.Write(typeof(Hashtable).FullName);
            Writer.WriteLine("();");

            ConstantMapping[] constants = mapping.Constants;

            for (int i = 0; i < constants.Length; i++) {
                Writer.Write("h.Add(");
                WriteQuotedCSharpString(constants[i].XmlName);
                if (!mapping.TypeDesc.UseReflection){
                    Writer.Write(", (long)");
                    Writer.Write(mapping.TypeDesc.CSharpName);
                    Writer.Write(".@");
                    CodeIdentifier.CheckValidIdentifier(constants[i].Name);
                    Writer.Write(constants[i].Name);
                }
                else{
                    Writer.Write(", ");
                    Writer.Write(constants[i].Value.ToString(CultureInfo.InvariantCulture)+"L");
                }

                Writer.WriteLine(");");
            }

            Writer.Write(memberName);
            Writer.WriteLine(" = h;");

            Writer.Indent--;
            Writer.WriteLine("}");

            Writer.Write("return ");
            Writer.Write(memberName);
            Writer.WriteLine(";");

            Writer.Indent--;
            Writer.WriteLine("}");

            Writer.Indent--;
            Writer.WriteLine("}");

            return propName;
        }
        private string WriteEnumMethod(EnumMapping mapping, object v)
        {
            if (mapping != null && mapping.IsSoap)
            {
                throw new PlatformNotSupportedException();
            }

            if (mapping != null && mapping.IsFlags)
            {
                Type type = mapping.TypeDesc.Type;

                List<string> valueStrings = new List<string>();
                List<long> valueIds = new List<long>();
                foreach (var value in Enum.GetValues(type))
                {
                    valueStrings.Add(value.ToString());
                    valueIds.Add(Convert.ToInt64(value));
                }

                return FromEnum(Convert.ToInt64(v), valueStrings.ToArray(), valueIds.ToArray());
            }
            else
            {
                return v.ToString();
            }
        }
Ejemplo n.º 21
0
        void ExportEnum(EnumMapping mapping) {
            CodeTypeDeclaration codeClass = new CodeTypeDeclaration(mapping.TypeDesc.Name);
            codeClass.IsEnum = true;
            codeClass.TypeAttributes |= TypeAttributes.Public;
            codeClass.Comments.Add(new CodeCommentStatement("<remarks/>", true));
            codeNamespace.Types.Add(codeClass);
            codeClass.CustomAttributes = new CodeAttributeDeclarationCollection();
            AddTypeMetadata(codeClass.CustomAttributes, mapping.TypeName, mapping.Namespace, mapping.IncludeInSchema);

            for (int i = 0; i < mapping.Constants.Length; i++) {
                ExportConstant(codeClass, mapping.Constants[i]);
            }
            if (mapping.IsFlags) {
                AddCustomAttribute(codeClass.CustomAttributes, typeof(FlagsAttribute), new CodeAttributeArgument[0]);
            }
        }
Ejemplo n.º 22
0
        string WriteHashtable(EnumMapping mapping, string typeName) {

            CodeIdentifier.CheckValidIdentifier(typeName);
            string propName = MakeUnique(mapping, typeName + "Values");
            if (propName == null) return CodeIdentifier.EscapeKeywords(typeName);
            string memberName = MakeUnique(mapping, "_" + propName);
            propName = CodeIdentifier.EscapeKeywords(propName);

            writer.WriteLine();
            writer.Write(typeof(Hashtable).FullName);
            writer.Write(" ");
            writer.Write(memberName);
            writer.WriteLine(";");
            writer.WriteLine();

            writer.Write("internal ");
            writer.Write(typeof(Hashtable).FullName);
            writer.Write(" ");
            writer.Write(propName);
            writer.WriteLine(" {");
            writer.Indent++;

            writer.WriteLine("get {");
            writer.Indent++;

            writer.Write("if ((object)");
            writer.Write(memberName);
            writer.WriteLine(" == null) {");
            writer.Indent++;

            writer.Write(typeof(Hashtable).FullName);
            writer.Write(" h = new ");
            writer.Write(typeof(Hashtable).FullName);
            writer.WriteLine("();");

            ConstantMapping[] constants = mapping.Constants;

            for (int i = 0; i < constants.Length; i++) {
                writer.Write("h.Add(");
                WriteQuotedCSharpString(constants[i].XmlName);
                writer.Write(", (");
                writer.Write(typeof(long).FullName);
                writer.Write(")");

                writer.Write(CodeIdentifier.EscapeKeywords(mapping.TypeDesc.FullName));
                writer.Write(".@");
                CodeIdentifier.CheckValidIdentifier(constants[i].Name);
                writer.Write(constants[i].Name);

                writer.WriteLine(");");
            }

            writer.Write(memberName);
            writer.WriteLine(" = h;");

            writer.Indent--;
            writer.WriteLine("}");

            writer.Write("return ");
            writer.Write(memberName);
            writer.WriteLine(";");

            writer.Indent--;
            writer.WriteLine("}");

            writer.Indent--;
            writer.WriteLine("}");

            return propName;
        }
Ejemplo n.º 23
0
        XmlSchemaType ExportEnumMapping(EnumMapping mapping, string ns) {
            if (!mapping.IncludeInSchema) throw new InvalidOperationException(Res.GetString(Res.XmlCannotIncludeInSchema, mapping.TypeDesc.Name));
            XmlSchemaSimpleType dataType = (XmlSchemaSimpleType)types[mapping];
            if (dataType == null) {
                CheckForDuplicateType(mapping, mapping.Namespace);
                dataType = new XmlSchemaSimpleType();
                dataType.Name = mapping.TypeName;
                if (!mapping.IsAnonymousType) {
                    types.Add(mapping, dataType);
                    AddSchemaItem(dataType, mapping.Namespace, ns);
                }
                XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();
                restriction.BaseTypeName = new XmlQualifiedName("string", XmlSchema.Namespace);

                for (int i = 0; i < mapping.Constants.Length; i++) {
                    ConstantMapping constant = mapping.Constants[i];
                    XmlSchemaEnumerationFacet enumeration = new XmlSchemaEnumerationFacet();
                    enumeration.Value = constant.XmlName;
                    restriction.Facets.Add(enumeration);
                }
                if (!mapping.IsFlags) {
                    dataType.Content = restriction;
                }
                else {
                    XmlSchemaSimpleTypeList list = new XmlSchemaSimpleTypeList();
                    XmlSchemaSimpleType enumType = new XmlSchemaSimpleType();
                    enumType.Content =  restriction;
                    list.ItemType = enumType;
                    dataType.Content =  list;
                }
            }
            if (!mapping.IsAnonymousType) {
                AddSchemaImport(mapping.Namespace, ns);
            }
            return dataType;
        }
Ejemplo n.º 24
0
        void WriteEnumMethod(EnumMapping mapping) {
            string tableName = null;
            if (mapping.IsFlags)
                tableName = WriteHashtable(mapping, mapping.TypeDesc.Name);

            string methodName = (string)methodNames[mapping];
            writer.WriteLine();
            string fullTypeName = CodeIdentifier.EscapeKeywords(mapping.TypeDesc.FullName);
            if (mapping.IsSoap) {
                writer.Write("object");
                writer.Write(" ");
                writer.Write(methodName);
                writer.WriteLine("() {");
                writer.Indent++;
                writer.WriteLine("string s = Reader.ReadElementString();");
            }
            else {
                writer.Write(fullTypeName);
                writer.Write(" ");
                writer.Write(methodName);
                writer.WriteLine("(string s) {");
                writer.Indent++;
            }

            ConstantMapping[] constants = mapping.Constants;

            if (mapping.IsFlags) {
                writer.Write("return (");
                writer.Write(fullTypeName);
                writer.Write(")ToEnum(s, ");
                writer.Write(tableName);
                writer.Write(", ");
                WriteQuotedCSharpString(fullTypeName);
                writer.WriteLine(");");
            }
            else {
                writer.WriteLine("switch (s) {");
                writer.Indent++;
                for (int i = 0; i < constants.Length; i++) {
                    ConstantMapping c = constants[i];

                    CodeIdentifier.CheckValidIdentifier(c.Name);
                    writer.Write("case ");
                    WriteQuotedCSharpString(c.XmlName);
                    writer.Write(": return ");

                    writer.Write(fullTypeName);
                    writer.Write(".@");
                    writer.Write(c.Name);
                    writer.WriteLine(";");
                }
                
                writer.Write("default: throw CreateUnknownConstantException(s, typeof(");
                writer.Write(fullTypeName);
                writer.WriteLine("));");
                writer.Indent--;
                writer.WriteLine("}");
            }

            writer.Indent--;
            writer.WriteLine("}");
        }
Ejemplo n.º 25
0
        static internal string ExportDefaultValue(TypeMapping mapping, object value)
        {
            #if DEBUG
            // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
            if (!(mapping is PrimitiveMapping))
            {
                throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Mapping " + mapping.GetType() + ", should not have Default"));
            }
            else if (mapping.IsList)
            {
                throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Mapping " + mapping.GetType() + ", should not have Default"));
            }
            #endif


            if (mapping is EnumMapping)
            {
                EnumMapping em = (EnumMapping)mapping;

                #if DEBUG
                // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
                if (value.GetType() != typeof(string))
                {
                    throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, Res.GetString(Res.XmlInvalidDefaultValue, value.ToString(), value.GetType().FullName)));
                }
                #endif

                // check the validity of the value
                ConstantMapping[] c = em.Constants;
                if (em.IsFlags)
                {
                    string[]  names  = new string[c.Length];
                    long[]    ids    = new long[c.Length];
                    Hashtable values = new Hashtable();
                    for (int i = 0; i < c.Length; i++)
                    {
                        names[i] = c[i].XmlName;
                        ids[i]   = 1 << i;
                        values.Add(c[i].Name, ids[i]);
                    }
                    long val = XmlCustomFormatter.ToEnum((string)value, values, em.TypeName, false);
                    return(val != 0 ? XmlCustomFormatter.FromEnum(val, names, ids) : null);
                }
                else
                {
                    for (int i = 0; i < c.Length; i++)
                    {
                        if (c[i].Name == (string)value)
                        {
                            return(c[i].XmlName);
                        }
                    }
                    return(null); // unknown value
                }
            }

            PrimitiveMapping pm = (PrimitiveMapping)mapping;

            if (!pm.TypeDesc.HasCustomFormatter)
            {
                #if DEBUG
                // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
                if (pm.TypeDesc.Type == null)
                {
                    throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Mapping for " + pm.TypeDesc.Name + " missing type property"));
                }
                #endif

                if (pm.TypeDesc.FormatterName == "String")
                {
                    return((string)value);
                }

                Type formatter = typeof(XmlConvert);
                System.Reflection.MethodInfo format = formatter.GetMethod("ToString", new Type[] { pm.TypeDesc.Type });
                if (format != null)
                {
                    return((string)format.Invoke(formatter, new Object[] { value }));
                }
            }
            else
            {
                string defaultValue = XmlCustomFormatter.FromDefaultValue(value, pm.TypeDesc.FormatterName);
                if (defaultValue == null)
                {
                    throw new InvalidOperationException(Res.GetString(Res.XmlInvalidDefaultValue, value.ToString(), pm.TypeDesc.Name));
                }
                return(defaultValue);
            }
            throw new InvalidOperationException(Res.GetString(Res.XmlInvalidDefaultValue, value.ToString(), pm.TypeDesc.Name));
        }
Ejemplo n.º 26
0
        XmlQualifiedName ExportEnumMapping(EnumMapping mapping, string ns) {
            XmlSchemaSimpleType dataType = (XmlSchemaSimpleType)types[mapping];
            if (dataType == null) {
                CheckForDuplicateType(mapping.TypeName, mapping.Namespace);
                dataType = new XmlSchemaSimpleType();
                dataType.Name = mapping.TypeName;
                types.Add(mapping, dataType);
                AddSchemaItem(dataType, mapping.Namespace, ns);

                XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();
                restriction.BaseTypeName = new XmlQualifiedName("string", XmlSchema.Namespace);

                for (int i = 0; i < mapping.Constants.Length; i++) {
                    ConstantMapping constant = mapping.Constants[i];
                    XmlSchemaEnumerationFacet enumeration = new XmlSchemaEnumerationFacet();
                    enumeration.Value = constant.XmlName;
                    restriction.Facets.Add(enumeration);
                }
                if (!mapping.IsFlags) {
                    dataType.Content = restriction;
                }
                else {
                    XmlSchemaSimpleTypeList list = new XmlSchemaSimpleTypeList();
                    XmlSchemaSimpleType enumType = new XmlSchemaSimpleType();
                    enumType.Content =  restriction;
                    list.ItemType = enumType;
                    dataType.Content =  list;
                }
            }
            else {
                AddSchemaImport(mapping.Namespace, ns);
            }
            return new XmlQualifiedName(mapping.TypeName, mapping.Namespace);
        }
Ejemplo n.º 27
0
        string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMapping, bool useReflection) {
            string enumValue = null;

            for (int i = 0; i < choiceMapping.Constants.Length; i++) {
                string xmlName = choiceMapping.Constants[i].XmlName;

                if (element.Any && element.Name.Length == 0) {
                    if (xmlName == "##any:") {
                        if (useReflection)
                            enumValue = choiceMapping.Constants[i].Value.ToString(CultureInfo.InvariantCulture);
                        else
                            enumValue = choiceMapping.Constants[i].Name;
                        break;
                    }
                    continue;
                }
                int colon = xmlName.LastIndexOf(':');
                string choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon);
                string choiceName = colon < 0 ? xmlName : xmlName.Substring(colon+1);

                if (element.Name == choiceName) {
                    if ((element.Form == XmlSchemaForm.Unqualified && string.IsNullOrEmpty(choiceNs)) || element.Namespace == choiceNs) {
                        if (useReflection)
                            enumValue = choiceMapping.Constants[i].Value.ToString(CultureInfo.InvariantCulture);
                        else
                            enumValue = choiceMapping.Constants[i].Name;
                        break;
                    }
                }
            }
            if (enumValue == null || enumValue.Length == 0) {
                if (element.Any && element.Name.Length == 0) {
                    // Type {0} is missing enumeration value '##any' for XmlAnyElementAttribute.
                    throw new InvalidOperationException(Res.GetString(Res.XmlChoiceMissingAnyValue, choiceMapping.TypeDesc.FullName));
                }
                // Type {0} is missing value for '{1}'.
                throw new InvalidOperationException(Res.GetString(Res.XmlChoiceMissingValue, choiceMapping.TypeDesc.FullName, element.Namespace + ":" + element.Name, element.Name, element.Namespace));
            }
            if(!useReflection)
                CodeIdentifier.CheckValidIdentifier(enumValue);
            return enumValue;
        }
 private void CheckChoiceIdentifierMapping(EnumMapping choiceMapping)
 {
     System.Xml.Serialization.NameTable table = new System.Xml.Serialization.NameTable();
     for (int i = 0; i < choiceMapping.Constants.Length; i++)
     {
         string xmlName = choiceMapping.Constants[i].XmlName;
         int length = xmlName.LastIndexOf(':');
         string name = (length < 0) ? xmlName : xmlName.Substring(length + 1);
         string ns = (length < 0) ? "" : xmlName.Substring(0, length);
         if (table[name, ns] != null)
         {
             throw new InvalidOperationException(Res.GetString("XmlChoiceIdDuplicate", new object[] { choiceMapping.TypeName, xmlName }));
         }
         table.Add(name, ns, choiceMapping.Constants[i]);
     }
 }
 internal CodeTypeDeclaration ExportEnum(EnumMapping mapping, Type type)
 {
     CodeTypeDeclaration declaration = new CodeTypeDeclaration(mapping.TypeDesc.Name);
     declaration.Comments.Add(new CodeCommentStatement(Res.GetString("XmlRemarks"), true));
     declaration.IsEnum = true;
     if (mapping.IsFlags && (mapping.Constants.Length > 0x1f))
     {
         declaration.BaseTypes.Add(new CodeTypeReference(typeof(long)));
     }
     declaration.TypeAttributes |= TypeAttributes.Public;
     this.CodeNamespace.Types.Add(declaration);
     for (int i = 0; i < mapping.Constants.Length; i++)
     {
         ExportConstant(declaration, mapping.Constants[i], type, mapping.IsFlags, ((long) 1L) << i);
     }
     if (mapping.IsFlags)
     {
         CodeAttributeDeclaration declaration2 = new CodeAttributeDeclaration(typeof(FlagsAttribute).FullName);
         declaration.CustomAttributes.Add(declaration2);
     }
     CodeGenerator.ValidateIdentifiers(declaration);
     return declaration;
 }
 private EnumMapping ImportEnumMapping(EnumModel model, string ns, bool repeats)
 {
     XmlAttributes a = this.GetAttributes(model.Type, false);
     string str = ns;
     if ((a.XmlType != null) && (a.XmlType.Namespace != null))
     {
         str = a.XmlType.Namespace;
     }
     string name = IsAnonymousType(a, ns) ? null : this.XsdTypeName(model.Type, a, model.TypeDesc.Name);
     name = XmlConvert.EncodeLocalName(name);
     EnumMapping mapping = (EnumMapping) this.GetTypeMapping(name, str, model.TypeDesc, this.types, model.Type);
     if (mapping == null)
     {
         mapping = new EnumMapping {
             TypeDesc = model.TypeDesc,
             TypeName = name,
             Namespace = str,
             IsFlags = model.Type.IsDefined(typeof(FlagsAttribute), false)
         };
         if (mapping.IsFlags && repeats)
         {
             throw new InvalidOperationException(Res.GetString("XmlIllegalAttributeFlagsArray", new object[] { model.TypeDesc.FullName }));
         }
         mapping.IsList = repeats;
         mapping.IncludeInSchema = (a.XmlType == null) || a.XmlType.IncludeInSchema;
         if (!mapping.IsAnonymousType)
         {
             this.types.Add(name, str, mapping);
         }
         else
         {
             this.anonymous[model.Type] = mapping;
         }
         ArrayList list = new ArrayList();
         for (int i = 0; i < model.Constants.Length; i++)
         {
             ConstantMapping mapping2 = this.ImportConstantMapping(model.Constants[i]);
             if (mapping2 != null)
             {
                 list.Add(mapping2);
             }
         }
         if (list.Count == 0)
         {
             throw new InvalidOperationException(Res.GetString("XmlNoSerializableMembers", new object[] { model.TypeDesc.FullName }));
         }
         mapping.Constants = (ConstantMapping[]) list.ToArray(typeof(ConstantMapping));
         this.typeScope.AddTypeMapping(mapping);
     }
     return mapping;
 }
Ejemplo n.º 31
0
        private TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, bool isList)
        {
            TypeMapping mapping = (TypeMapping)ImportedMappings[dataType];

            if (mapping != null)
            {
                return(mapping);
            }

            XmlSchemaSimpleType sourceDataType = FindDataType(dataType.DerivedFrom);
            TypeDesc            sourceTypeDesc = Scope.GetTypeDesc(sourceDataType);

            if (sourceTypeDesc != null && sourceTypeDesc != Scope.GetTypeDesc(typeof(string)))
            {
                return(ImportPrimitiveDataType(dataType));
            }
            identifier = Accessor.UnescapeName(identifier);
            string      typeName    = GenerateUniqueTypeName(identifier);
            EnumMapping enumMapping = new EnumMapping();

            enumMapping.IsReference = Schemas.IsReference(dataType);
            enumMapping.TypeDesc    = new TypeDesc(typeName, typeName, TypeKind.Enum, null, 0);
            enumMapping.TypeName    = identifier;
            enumMapping.Namespace   = typeNs;
            enumMapping.IsFlags     = isList;
            CodeIdentifiers constants = new CodeIdentifiers();

            if (!(dataType.Content is XmlSchemaSimpleTypeRestriction))
            {
                throw new InvalidOperationException(SR.Format(SR.XmlInvalidEnumContent, dataType.Content.GetType().Name, identifier));
            }

            XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)dataType.Content;

            for (int i = 0; i < restriction.Facets.Count; i++)
            {
                object facet = restriction.Facets[i];
                if (!(facet is XmlSchemaEnumerationFacet))
                {
                    continue;
                }
                XmlSchemaEnumerationFacet enumeration = (XmlSchemaEnumerationFacet)facet;
                ConstantMapping           constant    = new ConstantMapping();
                string constantName = CodeIdentifier.MakeValid(enumeration.Value);
                constant.Name    = constants.AddUnique(constantName, constant);
                constant.XmlName = enumeration.Value;
                constant.Value   = i;
            }
            enumMapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping));
            if (isList && enumMapping.Constants.Length > 63)
            {
                // if we have 64+ flag constants we cannot map the type to long enum, we will use string mapping instead.
                mapping          = new PrimitiveMapping();
                mapping.TypeDesc = Scope.GetTypeDesc(typeof(string));
                mapping.TypeName = mapping.TypeDesc.DataType.Name;
                ImportedMappings.Add(dataType, mapping);
                return(mapping);
            }
            ImportedMappings.Add(dataType, enumMapping);
            Scope.AddTypeMapping(enumMapping);
            return(enumMapping);
        }
        private void WriteEnumValue(EnumMapping mapping, SourceInfo source, out Type returnType)
        {
            string methodName = ReferenceMapping(mapping);

#if DEBUG
            // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
            if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name));
#endif

            // For enum, its write method (eg. Write1_Gender) could be called multiple times
            // prior to its declaration.
            MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder,
                    methodName,
                    CodeGenerator.PrivateMethodAttributes,
                    typeof(string),
                    new Type[] { mapping.TypeDesc.Type });
            ilg.Ldarg(0);
            source.Load(mapping.TypeDesc.Type);
            ilg.Call(methodBuilder);
            returnType = typeof(string);
        }
 private XmlSchemaType ExportEnumMapping(EnumMapping mapping, string ns)
 {
     if (!mapping.IncludeInSchema)
     {
         throw new InvalidOperationException(Res.GetString("XmlCannotIncludeInSchema", new object[] { mapping.TypeDesc.Name }));
     }
     XmlSchemaSimpleType type = (XmlSchemaSimpleType) this.types[mapping];
     if (type == null)
     {
         this.CheckForDuplicateType(mapping, mapping.Namespace);
         type = new XmlSchemaSimpleType {
             Name = mapping.TypeName
         };
         if (!mapping.IsAnonymousType)
         {
             this.types.Add(mapping, type);
             this.AddSchemaItem(type, mapping.Namespace, ns);
         }
         XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction {
             BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema")
         };
         for (int i = 0; i < mapping.Constants.Length; i++)
         {
             ConstantMapping mapping2 = mapping.Constants[i];
             XmlSchemaEnumerationFacet item = new XmlSchemaEnumerationFacet {
                 Value = mapping2.XmlName
             };
             restriction.Facets.Add(item);
         }
         if (!mapping.IsFlags)
         {
             type.Content = restriction;
         }
         else
         {
             XmlSchemaSimpleTypeList list = new XmlSchemaSimpleTypeList();
             XmlSchemaSimpleType type2 = new XmlSchemaSimpleType {
                 Content = restriction
             };
             list.ItemType = type2;
             type.Content = list;
         }
     }
     if (!mapping.IsAnonymousType)
     {
         this.AddSchemaImport(mapping.Namespace, ns);
     }
     return type;
 }
Ejemplo n.º 34
0
        internal CodeTypeDeclaration ExportEnum(EnumMapping mapping, Type type) {
            CodeTypeDeclaration codeClass = new CodeTypeDeclaration(mapping.TypeDesc.Name);

            codeClass.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true));
            codeClass.IsEnum = true;
            if (mapping.IsFlags && mapping.Constants.Length > 31) {
                codeClass.BaseTypes.Add(new CodeTypeReference(typeof(long)));
            }
            codeClass.TypeAttributes |= TypeAttributes.Public;
            CodeNamespace.Types.Add(codeClass);
            for (int i = 0; i < mapping.Constants.Length; i++) {
                ExportConstant(codeClass, mapping.Constants[i], type, mapping.IsFlags, 1L << i);
            }
            if (mapping.IsFlags) {
                // Add [FlagsAttribute]
                CodeAttributeDeclaration flags = new CodeAttributeDeclaration(typeof(FlagsAttribute).FullName);
                codeClass.CustomAttributes.Add(flags);
            }
            CodeGenerator.ValidateIdentifiers(codeClass);
            return codeClass;
        }
        private void WriteEnumMethod(EnumMapping mapping)
        {
            string methodName = (string)MethodNames[mapping];
            List<Type> argTypes = new List<Type>();
            List<string> argNames = new List<string>();
            argTypes.Add(mapping.TypeDesc.Type);
            argNames.Add("v");
            ilg = new CodeGenerator(this.typeBuilder);
            ilg.BeginMethod(
                typeof(string),
                GetMethodBuilder(methodName),
                argTypes.ToArray(),
                argNames.ToArray(),
                CodeGenerator.PrivateMethodAttributes);
            LocalBuilder sLoc = ilg.DeclareLocal(typeof(string), "s");
            ilg.Load(null);
            ilg.Stloc(sLoc);
            ConstantMapping[] constants = mapping.Constants;

            if (constants.Length > 0)
            {
                InternalHashtable values = new InternalHashtable();
                List<Label> caseLabels = new List<Label>();
                List<string> retValues = new List<string>();
                Label defaultLabel = ilg.DefineLabel();
                Label endSwitchLabel = ilg.DefineLabel();
                // This local is necessary; otherwise, it becomes if/else
                LocalBuilder localTmp = ilg.DeclareLocal(mapping.TypeDesc.Type, "localTmp");
                ilg.Ldarg("v");
                ilg.Stloc(localTmp);
                for (int i = 0; i < constants.Length; i++)
                {
                    ConstantMapping c = constants[i];
                    if (values[c.Value] == null)
                    {
                        Label caseLabel = ilg.DefineLabel();
                        ilg.Ldloc(localTmp);
                        ilg.Ldc(Enum.ToObject(mapping.TypeDesc.Type, c.Value));
                        ilg.Beq(caseLabel);
                        caseLabels.Add(caseLabel);
                        retValues.Add(GetCSharpString(c.XmlName));
                        values.Add(c.Value, c.Value);
                    }
                }


                if (mapping.IsFlags)
                {
                    ilg.Br(defaultLabel);
                    for (int i = 0; i < caseLabels.Count; i++)
                    {
                        ilg.MarkLabel(caseLabels[i]);
                        ilg.Ldc(retValues[i]);
                        ilg.Stloc(sLoc);
                        ilg.Br(endSwitchLabel);
                    }
                    ilg.MarkLabel(defaultLabel);
                    RaCodeGen.ILGenForEnumLongValue(ilg, "v");
                    LocalBuilder strArray = ilg.DeclareLocal(typeof(String[]), "strArray");
                    ilg.NewArray(typeof(String), constants.Length);
                    ilg.Stloc(strArray);
                    for (int i = 0; i < constants.Length; i++)
                    {
                        ConstantMapping c = constants[i];
                        ilg.Ldloc(strArray);
                        ilg.Ldc(i);
                        ilg.Ldstr(GetCSharpString(c.XmlName));
                        ilg.Stelem(typeof(String));
                    }
                    ilg.Ldloc(strArray);
                    LocalBuilder longArray = ilg.DeclareLocal(typeof(long[]), "longArray");
                    ilg.NewArray(typeof(long), constants.Length);
                    ilg.Stloc(longArray);

                    for (int i = 0; i < constants.Length; i++)
                    {
                        ConstantMapping c = constants[i];
                        ilg.Ldloc(longArray);
                        ilg.Ldc(i);
                        ilg.Ldc(c.Value);
                        ilg.Stelem(typeof(long));
                    }
                    ilg.Ldloc(longArray);
                    ilg.Ldstr(GetCSharpString(mapping.TypeDesc.FullName));
                    MethodInfo XmlSerializationWriter_FromEnum = typeof(XmlSerializationWriter).GetMethod(
                        "FromEnum",
                        CodeGenerator.StaticBindingFlags,
                        new Type[] { typeof(Int64), typeof(String[]), typeof(Int64[]), typeof(String) }
                        );
                    ilg.Call(XmlSerializationWriter_FromEnum);
                    ilg.Stloc(sLoc);
                    ilg.Br(endSwitchLabel);
                }
                else
                {
                    ilg.Br(defaultLabel);
                    // Case bodies
                    for (int i = 0; i < caseLabels.Count; i++)
                    {
                        ilg.MarkLabel(caseLabels[i]);
                        ilg.Ldc(retValues[i]);
                        ilg.Stloc(sLoc);
                        ilg.Br(endSwitchLabel);
                    }
                    MethodInfo CultureInfo_get_InvariantCulture = typeof(CultureInfo).GetMethod(
                        "get_InvariantCulture",
                        CodeGenerator.StaticBindingFlags,
                        Array.Empty<Type>()
                        );
                    MethodInfo Int64_ToString = typeof(Int64).GetMethod(
                        "ToString",
                        CodeGenerator.InstanceBindingFlags,
                        new Type[] { typeof(IFormatProvider) }
                        );
                    MethodInfo XmlSerializationWriter_CreateInvalidEnumValueException = typeof(XmlSerializationWriter).GetMethod(
                        "CreateInvalidEnumValueException",
                        CodeGenerator.InstanceBindingFlags,
                        new Type[] { typeof(object), typeof(string) }
                        );
                    // Default body
                    ilg.MarkLabel(defaultLabel);
                    ilg.Ldarg(0);
                    ilg.Ldarg("v");
                    ilg.ConvertValue(mapping.TypeDesc.Type, typeof(Int64));
                    LocalBuilder numLoc = ilg.DeclareLocal(typeof(Int64), "num");
                    ilg.Stloc(numLoc);
                    // Invoke method on Value type need address
                    ilg.LdlocAddress(numLoc);
                    ilg.Call(CultureInfo_get_InvariantCulture);
                    ilg.Call(Int64_ToString);
                    ilg.Ldstr(GetCSharpString(mapping.TypeDesc.FullName));
                    ilg.Call(XmlSerializationWriter_CreateInvalidEnumValueException);
                    ilg.Throw();
                }
                ilg.MarkLabel(endSwitchLabel);
            }
            ilg.Ldloc(sLoc);
            ilg.EndMethod();
        }
Ejemplo n.º 36
0
        void WriteEnumValue(EnumMapping mapping, string source) {
            string methodName = ReferenceMapping(mapping);

            #if DEBUG
                // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
                if (methodName == null) throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorMethod, mapping.TypeDesc.Name) + Environment.StackTrace);
            #endif

            Writer.Write(methodName);
            Writer.Write("(");
            Writer.Write(source);
            Writer.Write(")");
        }
        TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, bool isList) {
            TypeMapping mapping = (TypeMapping)ImportedMappings[dataType];
            if (mapping != null)
                return mapping;

            XmlSchemaSimpleType sourceDataType = FindDataType(dataType.DerivedFrom);
            TypeDesc sourceTypeDesc = Scope.GetTypeDesc(sourceDataType);
            if (sourceTypeDesc != null && sourceTypeDesc != Scope.GetTypeDesc(typeof(string)))
                return ImportPrimitiveDataType(dataType);
            identifier = Accessor.UnescapeName(identifier);
            string typeName = GenerateUniqueTypeName(identifier);
            EnumMapping enumMapping = new EnumMapping();
            enumMapping.IsReference = Schemas.IsReference(dataType);
            enumMapping.TypeDesc = new TypeDesc(typeName, typeName, TypeKind.Enum, null, 0);
            enumMapping.TypeName = identifier;
            enumMapping.Namespace = typeNs;
            enumMapping.IsFlags = isList;
            CodeIdentifiers constants = new CodeIdentifiers();

            if (!(dataType.Content is XmlSchemaSimpleTypeRestriction))
                throw new InvalidOperationException(Res.GetString(Res.XmlInvalidEnumContent, dataType.Content.GetType().Name, identifier));

            XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)dataType.Content;

            for (int i = 0; i < restriction.Facets.Count; i++) {
                object facet = restriction.Facets[i];
                if (!(facet is XmlSchemaEnumerationFacet)) continue;
                XmlSchemaEnumerationFacet enumeration = (XmlSchemaEnumerationFacet)facet;
                ConstantMapping constant = new ConstantMapping();
                string constantName = CodeIdentifier.MakeValid(enumeration.Value);
                constant.Name = constants.AddUnique(constantName, constant);
                constant.XmlName = enumeration.Value;
                constant.Value = i;
            }
            enumMapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping));
            if (isList && enumMapping.Constants.Length > 63) {
                // if we have 64+ flag constants we cannot map the type to long enum, we will use string mapping instead.
                mapping = new PrimitiveMapping();
                mapping.TypeDesc = Scope.GetTypeDesc(typeof(string));
                mapping.TypeName = mapping.TypeDesc.DataType.Name;
                ImportedMappings.Add(dataType, mapping);
                return mapping;
            }
            ImportedMappings.Add(dataType, enumMapping);
            Scope.AddTypeMapping(enumMapping);
            return enumMapping;
        }
        void WriteEnumMethod(EnumMapping mapping) {
            MethodBuilder get_TableName = null;
            if (mapping.IsFlags)
                WriteHashtable(mapping, mapping.TypeDesc.Name, out get_TableName);

            string methodName = (string)MethodNames[mapping];
            string fullTypeName = mapping.TypeDesc.CSharpName;
            List<Type> argTypes = new List<Type>();
            List<string> argNames = new List<string>();
            Type returnType;
            Type underlyingType;

            returnType = mapping.TypeDesc.Type;
            underlyingType = Enum.GetUnderlyingType(returnType);
            argTypes.Add(typeof(string));
            argNames.Add("s");
            ilg = new CodeGenerator(this.typeBuilder);
            ilg.BeginMethod(
                returnType,
                GetMethodBuilder(methodName),
                argTypes.ToArray(),
                argNames.ToArray(),
                CodeGenerator.PrivateMethodAttributes);

            ConstantMapping[] constants = mapping.Constants;
            if (mapping.IsFlags) {
                {
                    MethodInfo XmlSerializationReader_ToEnum = typeof(XmlSerializationReader).GetMethod(
                        "ToEnum",
                        CodeGenerator.StaticBindingFlags,
                        null,
                        new Type[] { typeof(String), typeof(Hashtable), typeof(String) },
                        null
                        );
                    ilg.Ldarg("s");
                    ilg.Ldarg(0);
                    Debug.Assert(get_TableName != null);
                    ilg.Call(get_TableName);
                    ilg.Ldstr(fullTypeName);
                    ilg.Call(XmlSerializationReader_ToEnum);
                    // XmlSerializationReader_ToEnum return long!
                    if (underlyingType != typeof(long)) {
                        ilg.ConvertValue(typeof(long), underlyingType);
                    }
                    ilg.Stloc(ilg.ReturnLocal);
                    ilg.Br(ilg.ReturnLabel);
                }
            }
            else {
                List<Label> caseLabels = new List<Label>();
                List<object> retValues = new List<object>();
                Label defaultLabel = ilg.DefineLabel();
                Label endSwitchLabel = ilg.DefineLabel();
                // This local is necessary; otherwise, it becomes if/else
                LocalBuilder localTmp = ilg.GetTempLocal(typeof(string));
                ilg.Ldarg("s");
                ilg.Stloc(localTmp);
                ilg.Ldloc(localTmp);
                ilg.Brfalse(defaultLabel);
                Hashtable cases = new Hashtable();
                for (int i = 0; i < constants.Length; i++) {
                    ConstantMapping c = constants[i];

                    CodeIdentifier.CheckValidIdentifier(c.Name);
                    if (cases[c.XmlName] == null) {
                        cases[c.XmlName] = c.XmlName;
                        Label caseLabel = ilg.DefineLabel();
                        ilg.Ldloc(localTmp);
                        ilg.Ldstr(c.XmlName);
                        MethodInfo String_op_Equality = typeof(string).GetMethod(
                            "op_Equality",
                            CodeGenerator.StaticBindingFlags,
                            null,
                            new Type[] { typeof(string), typeof(string) },
                            null
                            );
                        ilg.Call(String_op_Equality);
                        ilg.Brtrue(caseLabel);
                        caseLabels.Add(caseLabel);
                        retValues.Add(Enum.ToObject(mapping.TypeDesc.Type, c.Value));
                    }
                }

                ilg.Br(defaultLabel);
                // Case bodies
                for (int i = 0; i < caseLabels.Count; i++) {
                    ilg.MarkLabel(caseLabels[i]);
                    ilg.Ldc(retValues[i]);
                    ilg.Stloc(ilg.ReturnLocal);
                    ilg.Br(ilg.ReturnLabel);
                }
                MethodInfo XmlSerializationReader_CreateUnknownConstantException = typeof(XmlSerializationReader).GetMethod(
                    "CreateUnknownConstantException",
                    CodeGenerator.InstanceBindingFlags,
                    null,
                    new Type[] { typeof(string), typeof(Type) },
                    null
                    );
                // Default body
                ilg.MarkLabel(defaultLabel);
                ilg.Ldarg(0);
                ilg.Ldarg("s");
                // typeof(..)
                ilg.Ldc(mapping.TypeDesc.Type);
                ilg.Call(XmlSerializationReader_CreateUnknownConstantException);
                ilg.Throw();
                // End switch
                ilg.MarkLabel(endSwitchLabel);
            }

            ilg.MarkLabel(ilg.ReturnLabel);
            ilg.Ldloc(ilg.ReturnLocal);
            ilg.EndMethod();
        }
 string MakeUnique(EnumMapping mapping, string name) {
     string uniqueName = name;
     object m = Enums[uniqueName];
     if (m != null) {
         if (m == mapping) {
             // we already have created the hashtable
             return null;
         }
         int i = 0;
         while (m != null) {
             i++;
             uniqueName = name + i.ToString(CultureInfo.InvariantCulture);
             m = Enums[uniqueName];
         }
     }
     Enums.Add(uniqueName, mapping);
     return uniqueName;
 }
        string WriteHashtable(EnumMapping mapping, string typeName, out MethodBuilder get_TableName) {
            get_TableName = null;

            CodeIdentifier.CheckValidIdentifier(typeName);
            string propName = MakeUnique(mapping, typeName + "Values");
            if (propName == null) return CodeIdentifier.GetCSharpName(typeName);
            string memberName = MakeUnique(mapping, "_" + propName);
            propName = CodeIdentifier.GetCSharpName(propName);

            FieldBuilder fieldBuilder = this.typeBuilder.DefineField(
                memberName,
                typeof(Hashtable),
                FieldAttributes.Private
                );

            PropertyBuilder propertyBuilder = this.typeBuilder.DefineProperty(
                propName,
                PropertyAttributes.None,
                CallingConventions.HasThis,
                typeof(Hashtable),
                null, null, null, null, null);

            ilg = new CodeGenerator(this.typeBuilder);
            ilg.BeginMethod(
                typeof(Hashtable),
                "get_" + propName,
                CodeGenerator.EmptyTypeArray,
                CodeGenerator.EmptyStringArray,
                MethodAttributes.Assembly | MethodAttributes.HideBySig | MethodAttributes.SpecialName);

            ilg.Ldarg(0);
            ilg.LoadMember(fieldBuilder);
            ilg.Load(null);
            ilg.If(Cmp.EqualTo);

            ConstructorInfo Hashtable_ctor = typeof(Hashtable).GetConstructor(
                CodeGenerator.InstanceBindingFlags,
                null,
                CodeGenerator.EmptyTypeArray,
                null
                );
            LocalBuilder hLoc = ilg.DeclareLocal(typeof(Hashtable), "h");
            ilg.New(Hashtable_ctor);
            ilg.Stloc(hLoc);

            ConstantMapping[] constants = mapping.Constants;
            MethodInfo Hashtable_Add = typeof(Hashtable).GetMethod(
                "Add",
                CodeGenerator.InstanceBindingFlags,
                null,
                new Type[] { typeof(Object), typeof(Object) },
                null
                );

            for (int i = 0; i < constants.Length; i++) {
                ilg.Ldloc(hLoc);
                ilg.Ldstr(constants[i].XmlName);
                ilg.Ldc(Enum.ToObject(mapping.TypeDesc.Type, constants[i].Value));
                ilg.ConvertValue(mapping.TypeDesc.Type, typeof(long));
                ilg.ConvertValue(typeof(long), typeof(Object));

                ilg.Call(Hashtable_Add);
            }

            ilg.Ldarg(0);
            ilg.Ldloc(hLoc);
            ilg.StoreMember(fieldBuilder);

            ilg.EndIf();

            ilg.Ldarg(0);
            ilg.LoadMember(fieldBuilder);

            get_TableName = ilg.EndMethod();
            propertyBuilder.SetGetMethod(get_TableName);

            return propName;
        }
        void WriteEnumMethod(EnumMapping mapping) {
            string tableName = null;
            if (mapping.IsFlags)
                tableName = WriteHashtable(mapping, mapping.TypeDesc.Name);

            string methodName = (string)MethodNames[mapping];
            Writer.WriteLine();
            bool useReflection = mapping.TypeDesc.UseReflection;
            string fullTypeName = mapping.TypeDesc.CSharpName;

            if (mapping.IsSoap) {
                Writer.Write("object");
                Writer.Write(" ");
                Writer.Write(methodName);
                Writer.WriteLine("() {");
                Writer.Indent++;
                Writer.WriteLine("string s = Reader.ReadElementString();");
            }
            else {
                Writer.Write(useReflection?"object":fullTypeName);
                Writer.Write(" ");
                Writer.Write(methodName);
                Writer.WriteLine("(string s) {");
                Writer.Indent++;
            }

            ConstantMapping[] constants = mapping.Constants;
            if (mapping.IsFlags) {
                if (useReflection){
                    Writer.Write("return ");
                    Writer.Write(typeof(Enum).FullName);
                    Writer.Write(".ToObject(");
                    Writer.Write(RaCodeGen.GetStringForTypeof(fullTypeName, useReflection));
                    Writer.Write(", ToEnum(s, ");
                    Writer.Write(tableName);
                    Writer.Write(", ");
                    WriteQuotedCSharpString(fullTypeName);
                    Writer.WriteLine("));");
                }
                else{
                    Writer.Write("return (");
                    Writer.Write(fullTypeName);
                    Writer.Write(")ToEnum(s, ");
                    Writer.Write(tableName);
                    Writer.Write(", ");
                    WriteQuotedCSharpString(fullTypeName);
                    Writer.WriteLine(");");
                }
            }
            else {
                Writer.WriteLine("switch (s) {");
                Writer.Indent++;
                Hashtable cases = new Hashtable();
                for (int i = 0; i < constants.Length; i++) {
                    ConstantMapping c = constants[i];

                    CodeIdentifier.CheckValidIdentifier(c.Name);
                    if (cases[c.XmlName] == null) {
                        Writer.Write("case ");
                        WriteQuotedCSharpString(c.XmlName);
                        Writer.Write(": return ");
                        Writer.Write(RaCodeGen.GetStringForEnumMember(fullTypeName, c.Name, useReflection));
                        Writer.WriteLine(";");
                        cases[c.XmlName] = c.XmlName;
                    }
                }
                
                Writer.Write("default: throw CreateUnknownConstantException(s, ");
                Writer.Write(RaCodeGen.GetStringForTypeof(fullTypeName, useReflection));
                Writer.WriteLine(");");
                Writer.Indent--;
                Writer.WriteLine("}");
            }

            Writer.Indent--;
            Writer.WriteLine("}");
        }
Ejemplo n.º 42
0
        TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier) {
            EnumMapping enumMapping = (EnumMapping)mappings[dataType];
            if (enumMapping != null) return enumMapping;
            XmlSchemaType sourceType = FindType(dataType.DerivedFrom);
            if (sourceType is XmlSchemaComplexType) return null;
            TypeDesc sourceTypeDesc = scope.GetTypeDesc((XmlSchemaSimpleType)sourceType);
            if (sourceTypeDesc != null && sourceTypeDesc.FullName != typeof(string).FullName)
                return ImportPrimitiveDataType(dataType);
            string typeName = GenerateUniqueTypeName(identifier);
            enumMapping = new EnumMapping();
            enumMapping.TypeDesc = new TypeDesc(typeName, typeName, TypeKind.Enum, null, 0);
            enumMapping.TypeName = identifier;
            enumMapping.Namespace = typeNs;
            enumMapping.IsFlags = false;

            mappings.Add(dataType, enumMapping);
            CodeIdentifiers constants = new CodeIdentifiers();
            XmlSchemaSimpleTypeContent content = dataType.Content;

            if (content is XmlSchemaSimpleTypeRestriction) {
                XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)content;
                for (int i = 0; i < restriction.Facets.Count; i++) {
                    object facet = restriction.Facets[i];
                    if (!(facet is XmlSchemaEnumerationFacet)) continue;
                    XmlSchemaEnumerationFacet enumeration = (XmlSchemaEnumerationFacet)facet;
                    // validate the enumeration value
                    if (sourceTypeDesc != null && sourceTypeDesc.HasCustomFormatter) {
                        XmlCustomFormatter.ToDefaultValue(enumeration.Value, sourceTypeDesc.FormatterName);
                    }
                    ConstantMapping constant = new ConstantMapping();
                    string constantName = CodeIdentifier.MakeValid(enumeration.Value);
                    constant.Name = constants.AddUnique(constantName, constant);
                    constant.XmlName = enumeration.Value;
                    constant.Value = i;
                }
            }
            enumMapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping));
            scope.AddTypeMapping(enumMapping);
            return enumMapping;
        }
        EnumMapping ImportEnumMapping(EnumModel model) {
            SoapAttributes a = GetAttributes(model.Type);
            string typeNs = defaultNs;
            if (a.SoapType != null && a.SoapType.Namespace != null)
                typeNs = a.SoapType.Namespace;
            string typeName = XsdTypeName(model.Type, a, model.TypeDesc.Name);
            typeName = XmlConvert.EncodeLocalName(typeName);

            EnumMapping mapping = (EnumMapping)GetTypeMapping(typeName, typeNs, model.TypeDesc);
            if (mapping == null) {
                mapping = new EnumMapping();
                mapping.IsSoap = true;
                mapping.TypeDesc = model.TypeDesc;
                mapping.TypeName = typeName;
                mapping.Namespace = typeNs;
                mapping.IsFlags =  model.Type.IsDefined(typeof(FlagsAttribute), false);
                typeScope.AddTypeMapping(mapping);
                types.Add(typeName, typeNs, mapping);
                ArrayList constants = new ArrayList();
                for (int i = 0; i < model.Constants.Length; i++) {
                    ConstantMapping constant = ImportConstantMapping(model.Constants[i]);
                    if (constant != null) constants.Add(constant);
                }
                if (constants.Count == 0) {
                    throw new InvalidOperationException(Res.GetString(Res.XmlNoSerializableMembers, model.TypeDesc.FullName));
                }
                mapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping));
            }
            return mapping;
        }
Ejemplo n.º 44
0
        EnumMapping ImportEnumeratedChoice(ElementAccessor[] choice, string typeNs, string typeName) {
            typeName = GenerateUniqueTypeName(typeName, typeNs);
            EnumMapping enumMapping = new EnumMapping();
            enumMapping.TypeDesc = new TypeDesc(typeName, typeName, TypeKind.Enum, null, 0);
            enumMapping.TypeName = typeName;
            enumMapping.Namespace = typeNs;
            enumMapping.IsFlags = false;
            enumMapping.IncludeInSchema = false;

            CodeIdentifiers constants = new CodeIdentifiers();

            for (int i = 0; i < choice.Length; i++) {
                ElementAccessor element = choice[i];
                ConstantMapping constant = new ConstantMapping();
                string constantName = CodeIdentifier.MakeValid(element.Name);
                constant.Name = constants.AddUnique(constantName, constant);
                constant.XmlName = element.Namespace == typeNs ? element.Name : element.Namespace + ":" + element.Name;
                constant.Value = i;
            }
            enumMapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping));
            scope.AddTypeMapping(enumMapping);
            return enumMapping;
        }
Ejemplo n.º 45
0
        void WriteEnumMethod(EnumMapping mapping) {
            string methodName = (string)MethodNames[mapping];
            Writer.WriteLine();
            string fullTypeName = mapping.TypeDesc.CSharpName;
            if (mapping.IsSoap) {
                Writer.Write("void ");
                Writer.Write(methodName);
                Writer.WriteLine("(object e) {");
                WriteLocalDecl(fullTypeName, "v", "e", mapping.TypeDesc.UseReflection);
            }
            else {
                Writer.Write("string ");
                Writer.Write(methodName);
                Writer.Write("(");
                Writer.Write(mapping.TypeDesc.UseReflection? "object" : fullTypeName );
                Writer.WriteLine(" v) {");
            }
            Writer.Indent++;
            Writer.WriteLine("string s = null;");
            ConstantMapping[] constants = mapping.Constants;

            if (constants.Length > 0) {
                Hashtable values = new Hashtable();
                if (mapping.TypeDesc.UseReflection)
                    Writer.WriteLine("switch ("+RaCodeGen.GetStringForEnumLongValue("v", mapping.TypeDesc.UseReflection)+" ){");
                else
                    Writer.WriteLine("switch (v) {");
                Writer.Indent++;
                for (int i = 0; i < constants.Length; i++) {
                    ConstantMapping c = constants[i];
                    if (values[c.Value] == null) {
                        WriteEnumCase(fullTypeName, c, mapping.TypeDesc.UseReflection);
                        Writer.Write("s = ");
                        WriteQuotedCSharpString(c.XmlName);
                        Writer.WriteLine("; break;");
                        values.Add(c.Value, c.Value);
                    }
                }
                

                if (mapping.IsFlags) {
                    Writer.Write("default: s = FromEnum(");
                    Writer.Write(RaCodeGen.GetStringForEnumLongValue("v", mapping.TypeDesc.UseReflection));
                    Writer.Write(", new string[] {");
                    Writer.Indent++;
                    for (int i = 0; i < constants.Length; i++) {
                        ConstantMapping c = constants[i];
                        if (i > 0)
                            Writer.WriteLine(", ");
                        WriteQuotedCSharpString(c.XmlName);
                    }
                    Writer.Write("}, new ");
                    Writer.Write(typeof(long).FullName);
                    Writer.Write("[] {");

                    for (int i = 0; i < constants.Length; i++) {
                        ConstantMapping c = constants[i];
                        if (i > 0)
                            Writer.WriteLine(", ");
                        Writer.Write("(long)");
                        if (mapping.TypeDesc.UseReflection)
                            Writer.Write(c.Value.ToString(CultureInfo.InvariantCulture));
                        else {
                            Writer.Write(fullTypeName);
                            Writer.Write(".@");
                            CodeIdentifier.CheckValidIdentifier(c.Name);
                            Writer.Write(c.Name);
                        }
                    }
                    Writer.Indent--;
                    Writer.Write("}, ");
                    WriteQuotedCSharpString(mapping.TypeDesc.FullName);
                    Writer.WriteLine("); break;");
                }
                else {
                    Writer.Write("default: throw CreateInvalidEnumValueException(");
                    Writer.Write(RaCodeGen.GetStringForEnumLongValue("v", mapping.TypeDesc.UseReflection));
                    Writer.Write(".ToString(System.Globalization.CultureInfo.InvariantCulture), ");
                    WriteQuotedCSharpString(mapping.TypeDesc.FullName);
                    Writer.WriteLine(");");
                }
                Writer.Indent--;
                Writer.WriteLine("}");
            }
            if (mapping.IsSoap) {
                Writer.Write("WriteXsiType(");
                WriteQuotedCSharpString(mapping.TypeName);
                Writer.Write(", ");
                WriteQuotedCSharpString(mapping.Namespace);
                Writer.WriteLine(");");
                Writer.WriteLine("Writer.WriteString(s);");
            }
            else {
                Writer.WriteLine("return s;");
            }
            Writer.Indent--;
            Writer.WriteLine("}");
        }
        void CheckChoiceIdentifierMapping(EnumMapping choiceMapping) {
            NameTable ids = new NameTable();
            for (int i = 0; i < choiceMapping.Constants.Length; i++) {
                string choiceId = choiceMapping.Constants[i].XmlName;
                int colon = choiceId.LastIndexOf(':');
                string choiceName = colon < 0 ? choiceId : choiceId.Substring(colon+1);
                string choiceNs = colon < 0 ? "" : choiceId.Substring(0, colon);

                if (ids[choiceName, choiceNs] != null) {
                    // Enum values in the XmlChoiceIdentifier '{0}' have to be unique.  Value '{1}' already present.
                    throw new InvalidOperationException(Res.GetString(Res.XmlChoiceIdDuplicate, choiceMapping.TypeName, choiceId));
                }
                ids.Add(choiceName, choiceNs, choiceMapping.Constants[i]);
            }
        }
Ejemplo n.º 47
0
 internal string GetStringForEnumCompare(EnumMapping mapping, string memberName, bool useReflection){
     if(!useReflection){
         CodeIdentifier.CheckValidIdentifier(memberName);
         return mapping.TypeDesc.CSharpName+".@"+memberName;
     }
     string memberAccess = GetStringForEnumMember(mapping.TypeDesc.CSharpName, memberName, useReflection);
     return GetStringForEnumLongValue(memberAccess, useReflection);
 }
        EnumMapping ImportEnumMapping(EnumModel model, string ns, bool repeats) {
            XmlAttributes a = GetAttributes(model.Type, false);
            string typeNs = ns;
            if (a.XmlType != null && a.XmlType.Namespace != null)
                typeNs = a.XmlType.Namespace;

            string typeName = XsdTypeName(model.Type, a, model.TypeDesc.Name);
            typeName = XmlConvert.EncodeLocalName(typeName);

            EnumMapping mapping = (EnumMapping)GetTypeMapping(typeName, typeNs, model.TypeDesc, types, model.Type);
            if (mapping == null) {
                mapping = new EnumMapping();
                mapping.TypeDesc = model.TypeDesc;
                mapping.TypeName = typeName;
                mapping.Namespace = typeNs;
                mapping.IsFlags =  model.Type.IsDefined(typeof(FlagsAttribute), false);
                if (mapping.IsFlags && repeats)
                    throw new InvalidOperationException(Res.GetString(Res.XmlIllegalAttributeFlagsArray, model.TypeDesc.FullName));
                mapping.IsList = repeats;
                mapping.IncludeInSchema = a.XmlType == null ? true : a.XmlType.IncludeInSchema;
                if (!mapping.IsAnonymousType)
                    types.Add(typeName, typeNs, mapping);
                else
                    anonymous[model.Type] = mapping;
                ArrayList constants = new ArrayList();                
                for (int i = 0; i < model.Constants.Length; i++) {
                    ConstantMapping constant = ImportConstantMapping(model.Constants[i]);
                    if (constant != null) constants.Add(constant);
                }
                if (constants.Count == 0) {
                    throw new InvalidOperationException(Res.GetString(Res.XmlNoSerializableMembers, model.TypeDesc.FullName));
                }
                mapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping));
                typeScope.AddTypeMapping(mapping);
            }
            return mapping;
        }