private static void ExtractSoapParameters(WfServiceOperationParameterCollection rst, ServiceDescription desc, Message msg)
 {
     if (msg.Parts["parameters"] != null)
     {
         var ppsElemName = msg.Parts["parameters"].Element;
         var schema      = desc.Types.Schemas[ppsElemName.Namespace];
         System.Xml.Schema.XmlSchemaElement     innerTypes = (System.Xml.Schema.XmlSchemaElement)schema.Elements[ppsElemName];
         System.Xml.Schema.XmlSchemaComplexType xType      = innerTypes.SchemaType as System.Xml.Schema.XmlSchemaComplexType;
         if (xType != null)
         {
             System.Xml.Schema.XmlSchemaSequence xSeq = xType.Particle as System.Xml.Schema.XmlSchemaSequence;
             if (xSeq != null)
             {
                 foreach (var xItem in xSeq.Items)
                 {
                     if (xItem is System.Xml.Schema.XmlSchemaElement)
                     {
                         System.Xml.Schema.XmlSchemaElement xElem = xItem as System.Xml.Schema.XmlSchemaElement;
                         rst.Add(new WfServiceOperationParameter()
                         {
                             Name = xElem.Name, Type = SolveType(xElem.SchemaTypeName)
                         });
                     }
                 }
             }
         }
     }
 }
        /// <summary>
        /// Load this XmlSchema Element from a .net schema element
        /// </summary>
        /// <param name="element">The element to load from</param>
        public void Load(System.Xml.Schema.XmlSchemaElement element)
        {
            // Load base
            base.Load(element);

            this.Name      = element.QualifiedName != null ? element.QualifiedName.Name : element.Name;
            this.Namespace = element.QualifiedName != null ? element.QualifiedName.Namespace : Schema.TargetNamespace;
            this.MinOccurs = element.MinOccursString;
            this.MaxOccurs = element.MaxOccursString;

            // If Schema Type name is null, then that means the element defines an inline type
            if (element.SchemaType != null && element.SchemaType.Name != null)
            {
                this.type = Schema.FindType(element.SchemaType.Name);
            }
            else if (element.ElementSchemaType != null && element.ElementSchemaType.Name != null)
            {
                this.type = Schema.FindType(element.ElementSchemaType.Name);
            }
            else if (element.SchemaType != null)
            {
                Schema.CreateType(element.SchemaType, new XmlQualifiedName(this.Name, this.Namespace));
                this.type = Schema.FindType(element.SchemaType.Name);
                // Weird ...
                if (this.type == null)
                {
                    this.type = Schema.FindType(element.SchemaType.Name);
                }
                this.type.Documentation = "Autogenerated for element";
                this.type.Namespace     = this.Namespace;
            }
        }
        /// <summary> Return the C# type of this XmlSchemaAttribute. </summary>
        public static string GetAttributeTypeName(System.Xml.Schema.XmlSchemaElement parentElt, System.Xml.Schema.XmlSchemaAttribute attrib)
        {
            string attribTypeName = attrib.SchemaTypeName.Name;

            switch (attribTypeName)
            {
            case "":                      // => Dynamically generated enumeration
                return(Capitalize(parentElt.Name)
                       + Capitalize(attrib.Name));

            case "boolean": return("System.Boolean");

            case "int": return("System.Int64");

            case "nonNegativeInteger":
            case "positiveInteger": return("System.Int32");

            case "string": return("System.String");

            default:
                if (!KnowEnums.Contains(attribTypeName) && attribTypeName.Length > 0)
                {
                    log.Warn("\n\nUnknow TYPE (can be an enum): " + attribTypeName + "\n\n");
                }
                return(Program.Conformer.ToCapitalized(attribTypeName));
            }
        }
        /// <summary>
        /// Register an element
        /// </summary>
        /// <param name="e">The element to register</param>
        protected void RegisterElement(System.Xml.Schema.XmlSchemaElement e)
        {
            if (content == null)
            {
                content = new List <XmlSchemaObject>();
            }

            XmlSchemaElement ele = new XmlSchemaElement(Schema, this);

            ele.Load(e);
            content.Add(ele);
        }
        private string CreateProcessXmlFieldSchemaString(string name)
        {
            System.Xml.Schema.XmlSchema            xmlSchema   = new System.Xml.Schema.XmlSchema();
            System.Xml.Schema.XmlSchemaComplexType complexType = new System.Xml.Schema.XmlSchemaComplexType();
            System.Xml.Schema.XmlSchemaSequence    sequence    = new System.Xml.Schema.XmlSchemaSequence();
            complexType.Particle = sequence;
            System.Xml.Schema.XmlSchemaElement rootElement = new System.Xml.Schema.XmlSchemaElement();
            rootElement.SchemaType = complexType;
            rootElement.Name       = name;
            xmlSchema.Items.Add(rootElement);
            System.IO.StringWriter stream = new System.IO.StringWriter();
            xmlSchema.Write(stream);
            string outString = stream.ToString();

            stream.Close();
            stream.Dispose();
            return(outString);
        }
        /// <summary> Returns the unspecified value of the type of this attribute. </summary>
        public static string GetUnspecifiedValue(System.Xml.Schema.XmlSchemaElement parentElt, System.Xml.Schema.XmlSchemaAttribute attrib)
        {
            // The unspecified value is used to know if the user set a value
            // (in this case, we should write it; even if it is the default value)
            switch (attrib.SchemaTypeName.Name)
            {
            case "boolean": return(attrib.DefaultValue == null ? "false" : attrib.DefaultValue); // This value is meaningless because of its "bool XXXIsSpecified" property

            case "int": return(long.MinValue.ToString());                                        // Use a value outside the range of integers

            case "nonNegativeInteger":
            case "positiveInteger": return("-1");                     // value should be positive (so we can use -1 as unspecified value)

            case "string": return("null");

            default:                     // => Treat it as Enumeration
                return(GetAttributeTypeName(parentElt, attrib) + ".Unspecified");
            }
        }
Exemple #7
0
        private static string AttributeToXmlValue(System.Xml.Schema.XmlSchemaElement schemaElt, System.Xml.Schema.XmlSchemaAttribute attrib, string attribName, bool isRoot)
        {
            string fieldType = Utils.GetAttributeTypeName(schemaElt, attrib);
            string val       = "attribute." + Utils.Capitalize(attribName);

            switch (fieldType)
            {
            case "System.Boolean": return(val + " ? \"true\" : \"false\"");

            case "System.Int32": return(val + ".ToString()");

            case "System.Int64": return(val + ".ToString()");

            case "System.String": return("GetAttributeValue(" + val + (isRoot? ", type)" : ", mappedClass)"));

            default:                     // => Enum
                return("GetXmlEnumValue(typeof(" + fieldType + "), " + val + ")");
            }
        }
        /// <summary> Fill the ClassDeclaration with Attributes of the XmlSchemaElement. </summary>
        public static void GenerateAttribute(System.Xml.Schema.XmlSchemaElement attElt, Refly.CodeDom.ClassDeclaration cd, System.Xml.Schema.XmlSchemaComplexType refSchemaType)
        {
            cd.Doc.Summary.AddText(AnnotationToString(attElt.Annotation));             // Create the <summary />
            cd.Parent = new Refly.CodeDom.StringTypeDeclaration("BaseAttribute");
            // Add [AttributeUsage(AttributeTargets, AllowMultiple]  and  [Serializable]
            // Note: There is a problem with the order of the arguments, that's why they are together
            bool   targetsAll       = Utils.TargetsAll(Utils.Capitalize(attElt.Name));
            string attributeTargets = "System.AttributeTargets.";

            if (Utils.IsRoot(Utils.Capitalize(attElt.Name)) || targetsAll)
            {
                attributeTargets += "Class | System.AttributeTargets.Struct | System.AttributeTargets.Interface";
            }
            if (targetsAll)
            {
                attributeTargets += " | System.AttributeTargets.";
            }
            if (!Utils.IsRoot(Utils.Capitalize(attElt.Name)) || targetsAll)
            {
                attributeTargets += "Property | System.AttributeTargets.Field";
            }
            Refly.CodeDom.AttributeDeclaration attribUsage = cd.CustomAttributes.Add("System.AttributeUsage");
            attribUsage.Arguments.Add("", new Refly.CodeDom.Expressions.SnippetExpression(
                                          attributeTargets + ", AllowMultiple=" + Utils.AllowMultipleValue(attElt.Name)));
            cd.CustomAttributes.Add("System.Serializable");

            // Add the constructors
            Refly.CodeDom.ConstructorDeclaration defCtor = cd.AddConstructor();
            defCtor.Doc.Summary.AddText(" Default constructor (position=0) ");             // Create the <summary />
            defCtor.BaseContructorArgs.Add(new Refly.CodeDom.Expressions.SnippetExpression("0"));
            Refly.CodeDom.ConstructorDeclaration posCtor = cd.AddConstructor();
            posCtor.Doc.Summary.AddText(" Constructor taking the position of the attribute. ");             // Create the <summary />
            posCtor.Signature.Parameters.Add(typeof(int), "position");
            posCtor.BaseContructorArgs.Add(new Refly.CodeDom.Expressions.SnippetExpression("position"));

            System.Xml.Schema.XmlSchemaComplexType type = attElt.SchemaType as System.Xml.Schema.XmlSchemaComplexType;
            if (type == null && !attElt.SchemaTypeName.IsEmpty)            // eg:  <xs:element name="cache" type="cacheType" />
            {
                type = refSchemaType;
            }

            if (type != null)
            {
                // Add the attribute members
                System.Collections.ArrayList attribMembers = Utils.GetAttributes(type.Attributes);
                log.Debug("Add Attribute members: Count=" + attribMembers.Count);
                foreach (System.Xml.Schema.XmlSchemaAttribute attribMember in attribMembers)
                {
                    string memberType = Utils.GetAttributeTypeName(attElt, attribMember);
                    if (attribMember.SchemaTypeName.Name == string.Empty)                  // Create the dynamically generated enumeration
                    {
                        log.Debug("Generate Enumeration for SimpleType: " + memberType);
                        GenerateEnumeration(attribMember.SchemaType, cd.Namespace.AddEnum(memberType, false));
                    }

                    // Add the field with its default value
                    Refly.CodeDom.FieldDeclaration fd = cd.AddField(
                        memberType, attribMember.Name.Replace("-", "").ToLower());
                    // Set the unspecified value (to know if specified by the user)
                    fd.InitExpression = new Refly.CodeDom.Expressions.SnippetExpression(Utils.GetUnspecifiedValue(attElt, attribMember));
                    // Add its public property with a comment
                    Refly.CodeDom.PropertyDeclaration pd = cd.AddProperty(fd, true, true, false);
                    pd.Doc.Summary.AddText(AnnotationToString(attribMember.Annotation));                     // Create the <summary />
                    if (memberType == "System.Boolean")
                    {
                        // Add the field+property to know if this field has been specified
                        Refly.CodeDom.FieldDeclaration boolIsSpec = cd.AddField(
                            "System.Boolean", fd.Name + "specified");
                        cd.AddProperty(boolIsSpec, true, false, false).Doc.Summary.AddText(" Tells if " + pd.Name + " has been specified. ");                         // Create the <summary />
                        pd.Set.Add(new Refly.CodeDom.Expressions.SnippetExpression(
                                       boolIsSpec.Name + " = true"));
                    }

                    // Add the System.Type property (to allow setting this attribute with a type)
                    if (Utils.IsSystemType(attElt.Name, attribMember, memberType))
                    {
                        log.Debug("  Create System.Type for <" + attElt.Name + "> <" + attribMember.Name + ">");
                        Refly.CodeDom.PropertyDeclaration pdType = cd.AddProperty(typeof(System.Type), pd.Name + "Type");
                        pdType.Doc.Summary.AddText(AnnotationToString(attribMember.Annotation));                         // Create the <summary />
                        pdType.Get.Add(new Refly.CodeDom.Expressions.SnippetExpression(
                                           "return System.Type.GetType( this." + pd.Name + " )"));
                        pdType.Set.Add(new Refly.CodeDom.Expressions.SnippetExpression(string.Format(
                                                                                           @"if(value.Assembly == typeof(int).Assembly)
					this.{0} = value.FullName.Substring(7);
				else
					this.{0} = value.FullName + "", "" + value.Assembly.GetName().Name"                    , pd.Name)));
                    }

                    // Add the object property (to allow setting this attribute with any object)
                    if (Utils.IsSystemObject(attElt.Name, attribMember, memberType))
                    {
                        bool IsSystemEnum = Utils.IsSystemEnum(attElt.Name, attribMember, memberType);
                        log.Debug("  Create object version " + (IsSystemEnum?"+ EnumFormat ":"") + "for <" + attElt.Name + "> <" + attribMember.Name + ">");
                        Refly.CodeDom.PropertyDeclaration pdType = cd.AddProperty(typeof(object), pd.Name + "Object");
                        pdType.Doc.Summary.AddText(AnnotationToString(attribMember.Annotation));                         // Create the <summary />
                        pdType.Get.Add(new Refly.CodeDom.Expressions.SnippetExpression(
                                           "return this." + pd.Name));
                        // handle conversion of enum values
                        if (IsSystemEnum)
                        {
                            pdType.Set.Add(new Refly.CodeDom.Expressions.SnippetExpression(string.Format(
                                                                                               @"if(value is System.Enum)
					this.{0} = System.Enum.Format(value.GetType(), value, this.{0}EnumFormat);
				else
					this.{0} = value==null ? ""null"" : value.ToString()"                    , pd.Name)));
                        }
                        else
                        {
                            pdType.Set.Add(new Refly.CodeDom.Expressions.SnippetExpression(string.Format(
                                                                                               @"this.{0} = value==null ? ""null"" : value.ToString()", pd.Name)));
                        }

                        // Add the field xxxEnumFormat to set the string to use when formatting an Enum
                        if (IsSystemEnum)
                        {
                            Refly.CodeDom.FieldDeclaration fdEnumFormat = cd.AddField(
                                typeof(string), (fd.Name + "EnumFormat").ToLower());
                            // Set the default value
                            fdEnumFormat.InitExpression = new Refly.CodeDom.Expressions.SnippetExpression("\"g\"");
                            // Add its public property with a comment
                            Refly.CodeDom.PropertyDeclaration pdEnumFormat = cd.AddProperty(fdEnumFormat, true, true, false);
                            pdEnumFormat.Doc.Summary.AddText("'format' used by System.Enum.Format() in " + pdType.Name);                             // Create the <summary />
                        }
                    }
                }

                if (type.IsMixed)                // used by elements like <param>
                {
                    // Add the field with its default value
                    Refly.CodeDom.FieldDeclaration fd = cd.AddField("System.String", "Content");
                    // Add the unspecified value (to know if specified by the user)
                    fd.InitExpression = new Refly.CodeDom.Expressions.SnippetExpression("null");
                    // Add its public property with a comment
                    Refly.CodeDom.PropertyDeclaration pd = cd.AddProperty(fd, true, true, false);
                    pd.Doc.Summary.AddText(" Gets or sets the content of this element ");                     // Create the <summary />
                }
            }
            else
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("Unknow Element: ").Append(attElt.Name);
                if (attElt.SchemaType != null)
                {
                    sb.Append(", SchemaType = ").Append(attElt.SchemaType).Append(" - ").Append(attElt.SchemaType.Name);
                }
                if (!attElt.SchemaTypeName.IsEmpty)
                {
                    sb.Append(", SchemaTypeName = ").Append(attElt.SchemaTypeName.Name);
                }
                if (attElt.ElementType != null)
                {
                    sb.Append(", ElementType = ").Append(attElt.ElementType);
                }
                log.Warn(sb.ToString());
            }
        }
        static void Main()
        {
            try
            {
                log.Info("Generation of NHibernate.Mapping.Attributes");

                // Open the Schema (in /NHMA/ directory)
                System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("../../../../NHibernate.Mapping.Attributes/nhibernate-mapping.xsd");
                schema = System.Xml.Schema.XmlSchema.Read(reader, null);

                Refly.CodeDom.NamespaceDeclaration nd = new Refly.CodeDom.NamespaceDeclaration("NHibernate.Mapping.Attributes", conformer);
                nd.Imports.Clear();                 // remove "using System;"
                conformer.Capitalize = true;
                Refly.CodeDom.ClassDeclaration hbmWriter = nd.AddClass("HbmWriter");
                hbmWriter.Attributes = System.Reflection.TypeAttributes.Public;
                hbmWriter.Doc.Summary.AddText(" Write a XmlSchemaElement from attributes in a System.Type. ");                 // Create the <summary />

                Refly.CodeDom.FieldDeclaration fdDefaultHelper = hbmWriter.AddField("HbmWriterHelper", "DefaultHelper");
                fdDefaultHelper.InitExpression = new Refly.CodeDom.Expressions.SnippetExpression("new HbmWriterHelperEx()");
                // Add its public property with a comment
                Refly.CodeDom.PropertyDeclaration pdDefaultHelper = hbmWriter.AddProperty(fdDefaultHelper, true, true, false);
                pdDefaultHelper.Doc.Summary.AddText(" Gets or sets the HbmWriterHelper used by HbmWriter ");                 // Create the <summary />

                Refly.CodeDom.FieldDeclaration fdStartQuote = hbmWriter.AddField(typeof(string), "StartQuote");
                // Add its public property with a comment
                Refly.CodeDom.PropertyDeclaration pdStartQuote = hbmWriter.AddProperty(fdStartQuote, false, true, false);
                pdStartQuote.Get.Add(new Refly.CodeDom.Expressions.SnippetExpression(@"if(_startQuote==null || _startQuote.Length==0)
					_startQuote = ""{{"";
				return _startQuote"                ));
                pdStartQuote.Doc.Summary.AddText(" Gets or sets the beginning string used when declaring an identifier for an AttributeIdenfierAttribute ");                 // Create the <summary />

                Refly.CodeDom.FieldDeclaration fdEndQuote = hbmWriter.AddField(typeof(string), "EndQuote");
                // Add its public property with a comment
                Refly.CodeDom.PropertyDeclaration pdEndQuote = hbmWriter.AddProperty(fdEndQuote, false, true, false);
                pdEndQuote.Get.Add(new Refly.CodeDom.Expressions.SnippetExpression(@"if(_endQuote==null || _endQuote.Length==0)
					_endQuote = ""}}"";
				return _endQuote"                ));
                pdEndQuote.Doc.Summary.AddText(" Gets or sets the ending string used when declaring an identifier for an AttributeIdenfierAttribute ");                 // Create the <summary />

                Refly.CodeDom.FieldDeclaration fdPatterns = hbmWriter.AddField(typeof(System.Collections.Hashtable), "Patterns");
                // Add its public property with a comment
                Refly.CodeDom.PropertyDeclaration pdPatterns = hbmWriter.AddProperty(fdPatterns, false, true, false);
                pdPatterns.Get.Add(new Refly.CodeDom.Expressions.SnippetExpression(@"if(_patterns==null)
				{
					_patterns = new System.Collections.Hashtable();
					_patterns.Add(@""Nullables.Nullable(\w+), Nullables"", ""Nullables.NHibernate.Nullable$1Type, Nullables.NHibernate"");
					_patterns.Add(@""System.Data.SqlTypes.Sql(\w+), System.Data"", ""NHibernate.UserTypes.SqlTypes.Sql$1Type, NHibernate.UserTypes.SqlTypes"");
				}
				return _patterns"                ));
                pdPatterns.Doc.Summary.AddText(" Gets or sets the Patterns to convert properties types (the key is the pattern string and the value is the replacement string) ");                 // Create the <summary />

                HbmWriterGenerator.FillFindAttributedMembers(hbmWriter.AddMethod("FindAttributedMembers"));
                HbmWriterGenerator.FillGetSortedAttributes(hbmWriter.AddMethod("GetSortedAttributes"));
                HbmWriterGenerator.FillIsNextElement(hbmWriter.AddMethod("IsNextElement"), schema.Items);
                HbmWriterGenerator.FillGetXmlEnumValue(hbmWriter.AddMethod("GetXmlEnumValue"));
                HbmWriterGenerator.FillGetAttributeValue(hbmWriter.AddMethod("GetAttributeValue"));
                HbmWriterGenerator.FillWriteUserDefinedContent(hbmWriter.AddMethod("WriteUserDefinedContent"),
                                                               hbmWriter.AddMethod("WriteUserDefinedContent"));


                log.Info("Browse Schema.Items (Count=" + schema.Items.Count + ")");
                foreach (System.Xml.Schema.XmlSchemaObject obj in schema.Items)
                {
                    if (obj is System.Xml.Schema.XmlSchemaAttributeGroup)
                    {
                        // Ignore (used by Elements: <xs:attributeGroup ref="..." />)
                        log.Debug("Ignore AttributeGroup: " + (obj as System.Xml.Schema.XmlSchemaAttributeGroup).Name + string.Format(", nh-mapping.xsd({0})", obj.LineNumber));
                    }
                    else if (obj is System.Xml.Schema.XmlSchemaGroup)
                    {
                        // Ignore (used by Elements: <xs:group ref="..." />)
                        log.Debug("Ignore Group: " + (obj as System.Xml.Schema.XmlSchemaGroup).Name + string.Format(", nh-mapping.xsd({0})", obj.LineNumber));
                    }
                    else if (obj is System.Xml.Schema.XmlSchemaSimpleType)
                    {
                        System.Xml.Schema.XmlSchemaSimpleType elt = obj as System.Xml.Schema.XmlSchemaSimpleType;
                        log.Debug("Generate Enumeration for SimpleType: " + elt.Name + string.Format(", nh-mapping.xsd({0})", elt.LineNumber));
                        AttributeAndEnumGenerator.GenerateEnumeration(elt, nd.AddEnum(Utils.Capitalize(elt.Name), false));
                    }
                    else if (obj is System.Xml.Schema.XmlSchemaElement)
                    {
                        System.Xml.Schema.XmlSchemaElement     elt  = obj as System.Xml.Schema.XmlSchemaElement;
                        System.Xml.Schema.XmlSchemaComplexType type = null;
                        if (!elt.SchemaTypeName.IsEmpty)                        // eg:  <xs:element name="cache" type="cacheType" />
                        {
                            foreach (System.Xml.Schema.XmlSchemaObject o in schema.Items)
                            {
                                System.Xml.Schema.XmlSchemaComplexType t = o as System.Xml.Schema.XmlSchemaComplexType;
                                if (t != null && t.Name == elt.SchemaTypeName.Name)
                                {
                                    type = t;
                                    break;
                                }
                            }
                        }
                        string eltName = Utils.Capitalize(elt.Name);
                        log.Debug("Generate Attrib and EltWriter for Elt: " + elt.Name + string.Format(", nh-mapping.xsd({0})", elt.LineNumber));
                        AttributeAndEnumGenerator.GenerateAttribute(elt, nd.AddClass(eltName + "Attribute"), type);
                        HbmWriterGenerator.GenerateElementWriter(elt, eltName, hbmWriter.AddMethod("Write" + eltName), type, schema.Items);
                        if (Utils.IsRoot(eltName))
                        {
                            HbmWriterGenerator.FillWriteNestedTypes(eltName, hbmWriter.AddMethod("WriteNested" + eltName + "Types"));
                        }
                    }
                    else if (obj is System.Xml.Schema.XmlSchemaComplexType)
                    {
                        // Ignore (Note: Make sure that it is used by Elements only like this: <xs:element name="XXX" type="YYY" />)
                        System.Xml.Schema.XmlSchemaComplexType elt = obj as System.Xml.Schema.XmlSchemaComplexType;
                        log.Debug("Don't generate ComplexType: " + elt.Name + string.Format(", nh-mapping.xsd({0})", elt.LineNumber));                         // like <query> and <sql-query>
                    }
                    else
                    {
                        log.Warn("Unknown Object: " + obj.ToString() + string.Format(", nh-mapping.xsd({0})", obj.LineNumber));
                    }
                }


                // Generate the source code
                // Note: NameConformer.WordSplit() has been replaced in Refly.
                Refly.CodeDom.CodeGenerator gen = new Refly.CodeDom.CodeGenerator();
                gen.Options.IndentString = "	";                 // Tab
                gen.CreateFolders        = false;
                #region Copyright
                gen.Copyright = string.Format(@"
 NHibernate.Mapping.Attributes
 This product is under the terms of the GNU Lesser General Public License.


------------------------------------------------------------------------------
 <autogenerated>
     This code was generated by a tool.
     Runtime Version: {0}.{1}.{2}.x

     Changes to this file may cause incorrect behavior and will be lost if 
     the code is regenerated.
 </autogenerated>
------------------------------------------------------------------------------


 This source code was auto-generated by Refly, Version={3} (modified).
",
                                              System.Environment.Version.Major, System.Environment.Version.Minor, System.Environment.Version.Build,
                                              gen.GetType().Assembly.GetName(false).Version);
                #endregion

                log.Info("CodeGenerator.GenerateCode()... Classes=" + nd.Classes.Count + ", Enums=" + nd.Enums.Count);
                gen.GenerateCode(@"../../../../NHibernate.Mapping.Attributes", nd);
                log.Info("Done !");
            }
            catch (System.Exception ex)
            {
                log.Error("Unexpected Exception", ex);
            }
        }
Exemple #10
0
 public System.CodeDom.CodeTypeReference GetCodeTypeReference(System.Xml.XmlQualifiedName typeName, System.Xml.Schema.XmlSchemaElement element)
 {
     throw null;
 }
Exemple #11
0
 public bool CanImport(System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.XmlSchemaElement element)
 {
     throw null;
 }
Exemple #12
0
 public System.Xml.XmlQualifiedName? Import(System.Xml.Schema.XmlSchemaSet schemas, System.Xml.Schema.XmlSchemaElement element)
 {
     throw null;
 }
Exemple #13
0
        /// <summary> Add the content of the method IsNextElement(). </summary>
        public static void FillIsNextElement(Refly.CodeDom.MethodDeclaration method, System.Xml.Schema.XmlSchemaObjectCollection schemaItems)
        {
            method.Attributes = System.CodeDom.MemberAttributes.Public | System.CodeDom.MemberAttributes.Overloaded;
            method.Doc.Summary.AddText(" Tells if 'element1' come after 'element2' in rootType's 'sub-elements' order. ");             // Create the <summary />
            method.Signature.Parameters.Add("BaseAttribute", "element1");
            method.Signature.Parameters.Add("BaseAttribute", "baseAttrib");
            method.Signature.Parameters.Add(typeof(System.Type), "typeOfElement2");
            method.Signature.ReturnType = new Refly.CodeDom.TypeTypeDeclaration(typeof(bool));

            method.Body.Add(Refly.CodeDom.Stm.Snippet(
                                @"if( element1 == null )
				return false;"                ));

            foreach (System.Xml.Schema.XmlSchemaObject obj in schemaItems)
            {
                if (obj is System.Xml.Schema.XmlSchemaElement)
                {
                    System.Xml.Schema.XmlSchemaElement elt = obj as System.Xml.Schema.XmlSchemaElement;
                    method.Body.Add(Refly.CodeDom.Stm.Snippet(@"
			if( baseAttrib is "             + Utils.Capitalize(elt.Name) + @"Attribute )
			{"            ));

                    if (elt.SchemaType is System.Xml.Schema.XmlSchemaComplexType)
                    {
                        System.Xml.Schema.XmlSchemaComplexType type = elt.SchemaType as System.Xml.Schema.XmlSchemaComplexType;

                        // Add the elements
                        if (type.Particle is System.Xml.Schema.XmlSchemaSequence)
                        {
                            System.Xml.Schema.XmlSchemaSequence seq     = (elt.SchemaType as System.Xml.Schema.XmlSchemaComplexType).Particle as System.Xml.Schema.XmlSchemaSequence;
                            System.Collections.ArrayList        members = Utils.GetElements(seq.Items, schemaItems);
                            for (int i = 0; i < members.Count; i++)
                            {
                                System.Xml.Schema.XmlSchemaElement member = members[i] as System.Xml.Schema.XmlSchemaElement;
                                if (member.RefName.Name == string.Empty)
                                {
                                    continue;                                                            // Ignore elements like <query> and <sql-query>
                                }
                                string memberName = Utils.Capitalize(member.Name + member.RefName.Name); // One of them is empty

                                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                                sb.Append(
                                    @"	if( typeOfElement2 == typeof("+ memberName + @"Attribute) )
				{
					if( "                    );
                                for (int j = i + 1; j < members.Count; j++)
                                {
                                    System.Xml.Schema.XmlSchemaElement nextMember = members[j] as System.Xml.Schema.XmlSchemaElement;
                                    if (nextMember.RefName.Name == string.Empty)
                                    {
                                        continue;                                                                        // Ignore elements like <query> and <sql-query>
                                    }
                                    string nextMemberName = Utils.Capitalize(nextMember.Name + nextMember.RefName.Name); // One of them is empty
                                    sb.Append("element1 is " + nextMemberName + "Attribute || ");
                                }
                                // Add "typeOfElement2 == null" at the end to handle "||" and empty "if()" without compilation warning
                                sb.Append(@"typeOfElement2 == null )
						return true;
				}"                );
                                method.Body.Add(Refly.CodeDom.Stm.Snippet(sb.ToString()));
                            }
                        }
                    }
                    method.Body.Add(Refly.CodeDom.Stm.Snippet("}"));
                }
            }

            method.Body.Add(Refly.CodeDom.Stm.Snippet("return false;"));
            // -----------------------------------------------------------------
        }
Exemple #14
0
        /// <summary> Generate a Writer method for a XmlSchemaElement. </summary>
        public static void GenerateElementWriter(System.Xml.Schema.XmlSchemaElement schemaElt, string schemaEltName, Refly.CodeDom.MethodDeclaration method, System.Xml.Schema.XmlSchemaComplexType refSchemaType, System.Xml.Schema.XmlSchemaObjectCollection schemaItems)
        {
            bool schemaEltIsRoot = Utils.IsRoot(schemaEltName);

            method.Attributes = System.CodeDom.MemberAttributes.Public | System.CodeDom.MemberAttributes.Overloaded;
            method.Doc.Summary.AddText(" Write a " + schemaEltName + " XML Element from attributes in a " + (schemaEltIsRoot?"type":"member") + ". ");             // Create the <summary />
            method.Signature.Parameters.Add(typeof(System.Xml.XmlWriter), "writer");
            if (schemaEltIsRoot)
            {
                method.Signature.Parameters.Add(typeof(System.Type), "type");
            }
            else
            {
                method.Signature.Parameters.Add(typeof(System.Reflection.MemberInfo), "member");
                method.Signature.Parameters.Add(schemaEltName + "Attribute", "attribute");
                method.Signature.Parameters.Add("BaseAttribute", "parentAttribute");
                method.Signature.Parameters.Add(typeof(System.Type), "mappedClass");
            }

            // Beginning of the method's body
            if (schemaEltIsRoot)
            {
                method.Body.Add(Refly.CodeDom.Stm.Snippet(string.Format(
                                                              @"object[] attributes = {1}.GetCustomAttributes(typeof({0}Attribute), false);
			if(attributes.Length == 0)
				return;
			{0}Attribute attribute = attributes[0] as {0}Attribute;
", schemaEltName, schemaEltIsRoot ? "type" : "member"))); // Note : Root should never allow multiple !
            }
            method.Body.Add(Refly.CodeDom.Stm.Snippet(string.Format(
                                                          "writer.WriteStartElement( \"{0}\" );", schemaElt.Name)));


            System.Xml.Schema.XmlSchemaComplexType type = schemaElt.SchemaType as System.Xml.Schema.XmlSchemaComplexType;
            if (type == null && !schemaElt.SchemaTypeName.IsEmpty)            // eg:  <xs:element name="cache" type="cacheType" />
            {
                type = refSchemaType;
            }

            if (type != null)
            {
                // Add the attributes
                System.Collections.ArrayList attributes = Utils.GetAttributes(type.Attributes);
                log.Debug("Add Attributes: Count=" + attributes.Count);
                foreach (System.Xml.Schema.XmlSchemaAttribute attrib in attributes)
                {
                    string attribName       = attrib.Name + attrib.RefName.Name;               // One is empty
                    string methodAttribName = "attribute." + Utils.Capitalize(attribName);
                    method.Body.Add(Refly.CodeDom.Stm.Comment("Attribute: <" + attribName + ">"));

                    // If the attribute is not explicitly marked required, then we consider it optionnal
                    if (attrib.Use != System.Xml.Schema.XmlSchemaUse.Required)
                    {
                        if ("System.Boolean" == Utils.GetAttributeTypeName(schemaElt, attrib))
                        {
                            method.Body.Add(Refly.CodeDom.Stm.Snippet(
                                                string.Format(@"if( {0} )", methodAttribName + "Specified")));
                        }
                        else
                        {
                            method.Body.Add(Refly.CodeDom.Stm.Snippet(
                                                string.Format(@"if({0} != {1})", methodAttribName,
                                                              Utils.GetUnspecifiedValue(schemaElt, attrib))));
                        }
                    }
                    // Write the value
                    if (attrib.Use == System.Xml.Schema.XmlSchemaUse.Required)
                    {
                        // Here, we use a helper if the field is not specified (mainly used for "name" which is the name of the member)
                        log.Debug("  Create Helper for " + (schemaEltIsRoot ? "ClassType" : "MemberInfo") + " <" + schemaElt.Name + "> <" + attribName + ">");
                        string helper = string.Format(@"{0}=={1} ? DefaultHelper.Get_{2}_{3}_DefaultValue({4}) : ",                          // "typed" method name :)
                                                      methodAttribName, Utils.GetUnspecifiedValue(schemaElt, attrib), schemaEltName,
                                                      Utils.Capitalize(attribName),
                                                      schemaEltIsRoot ? "type" : "member");
                        method.Body.Add(Refly.CodeDom.Stm.Snippet(
                                            string.Format(@"writer.WriteAttributeString(""{0}"", {2}{1});",
                                                          attribName, AttributeToXmlValue(schemaElt, attrib, attribName, schemaEltIsRoot), helper)));
                    }
                    else
                    {
                        method.Body.Add(Refly.CodeDom.Stm.Snippet(
                                            string.Format(@"writer.WriteAttributeString(""{0}"", {1});",
                                                          attribName, AttributeToXmlValue(schemaElt, attrib, attribName, schemaEltIsRoot))));
                        if (schemaEltName == "Property" && attribName == "type")
                        {
                            // Special case to handle Patterns for <property ... type="..." />
                            // Eg: set Nullables.NHibernate.NullableXXXType for Nullables.NullableXXX
                            method.Body.Add(Refly.CodeDom.Stm.Snippet(@"else
			{
				System.Type type = null;
				if(member is System.Reflection.PropertyInfo)
					type = (member as System.Reflection.PropertyInfo).PropertyType;
				else if(member is System.Reflection.FieldInfo)
					type = (member as System.Reflection.FieldInfo).FieldType;
				if(type != null) // Transform using RegularExpressions
				{
					string typeName = HbmWriterHelper.GetNameWithAssembly(type);
					foreach(System.Collections.DictionaryEntry pattern in Patterns)
					{
						if(System.Text.RegularExpressions.Regex.IsMatch(typeName, pattern.Key as string))
						{
							writer.WriteAttributeString( ""type"",
								System.Text.RegularExpressions.Regex.Replace(typeName,
									pattern.Key as string,
									pattern.Value as string) );
							break;
						}
					}
				}
			}"            ));
                        }
                    }
                }

                // Add the elements
                method.Body.Add(Refly.CodeDom.Stm.Snippet(
                                    schemaEltIsRoot ? @"
			WriteUserDefinedContent(writer, type, null, attribute);"             : @"
			WriteUserDefinedContent(writer, member, null, attribute);"
                                    ));

                if (type.Particle is System.Xml.Schema.XmlSchemaSequence)
                {
                    System.Xml.Schema.XmlSchemaSequence seq     = (schemaElt.SchemaType as System.Xml.Schema.XmlSchemaComplexType).Particle as System.Xml.Schema.XmlSchemaSequence;
                    System.Collections.ArrayList        members = Utils.GetElements(seq.Items, schemaItems);
                    if (!schemaEltIsRoot)
                    {
                        method.Body.Add(Refly.CodeDom.Stm.Snippet(string.Format(@"
			System.Collections.ArrayList memberAttribs = GetSortedAttributes(member);
			int attribPos; // Find the position of the {0}Attribute (its <sub-element>s must be after it)
			for(attribPos=0; attribPos<memberAttribs.Count; attribPos++)
				if( memberAttribs[attribPos] is {0}Attribute
					&& ((BaseAttribute)memberAttribs[attribPos]).Position == attribute.Position )
					break; // found
			int i = attribPos + 1;
", schemaEltName)));
                    }

                    foreach (System.Xml.Schema.XmlSchemaElement member in members)
                    {
                        if (member.RefName.Name != null && member.RefName.Name != string.Empty &&
                            member.Name != null && member.Name != string.Empty)
                        {
                            log.Error(string.Format("Both member.RefName.Name({0}) & member.Name({1}) are not empty", member.RefName.Name, member.Name));
                        }
                        string realMemberName = member.Name + member.RefName.Name;                         // One of them should be empty
                        string memberName     = Utils.Capitalize(realMemberName);
                        string listName       = memberName + "List";
                        string attributeName  = memberName + "Attribute";
                        log.Debug(schemaEltName + " Element: <" + realMemberName + ">");
                        method.Body.Add(Refly.CodeDom.Stm.Comment("Element: <" + realMemberName + ">"));
                        // There are three way to treat elements:
                        // if(eltName is root)
                        //     if(memberName is root)
                        //         => They are both root, so we process the nestedTypes (eg. <class> to <sub-class>)
                        //     else
                        //         => It is an element of a root => we add them as element
                        // else
                        //     => They are both members, so we use the member again (eg. <list> to <one-to-many>)
                        if (schemaEltIsRoot)
                        {
                            if (Utils.IsRoot(memberName))
                            {
                                method.Body.Add(Refly.CodeDom.Stm.Snippet(string.Format(
                                                                              @"WriteNested{0}Types(writer, type);", memberName)));
                            }
                            else
                            {
                                method.Body.Add(Refly.CodeDom.Stm.Snippet(string.Format(
                                                                              @"System.Collections.ArrayList {1} = FindAttributedMembers( attribute, typeof({2}), type );
			foreach( System.Reflection.MemberInfo member in {1} )
			"            , memberName, listName, attributeName) + "{"
                                                                          + string.Format(
                                                                              @"
				object[] objects = member.GetCustomAttributes(typeof({2}), false);
				System.Collections.ArrayList memberAttribs = new System.Collections.ArrayList();
				memberAttribs.AddRange(objects);
				memberAttribs.Sort();
" + (Utils.CanContainItself(memberName) ?
     // => Just take the first (others will be inside it)
     @"				Write{0}(writer, member, memberAttribs[0] as {2}, attribute, type);"
                                                                        :
     @"				foreach(object memberAttrib in memberAttribs)
					Write{0}(writer, member, memberAttrib as {2}, attribute, type);"                    ),
                                                                              memberName, listName, attributeName) + @"
			}"            ));
                            }
                            method.Body.Add(Refly.CodeDom.Stm.Snippet(
                                                "WriteUserDefinedContent(writer, type, typeof(" + attributeName + "), attribute);"));
                        }
                        else
                        {
                            method.Body.Add(Refly.CodeDom.Stm.Snippet(
                                                @"for(; i<memberAttribs.Count; i++)
			{
				BaseAttribute memberAttrib = memberAttribs[i] as BaseAttribute;
				if( IsNextElement(memberAttrib, parentAttribute, attribute.GetType())
					|| IsNextElement(memberAttrib, attribute, typeof("                     + attributeName + @")) )
					break; // next attributes are 'elements' of the same level OR for 'sub-elements'"
                                                + (Utils.IsRoot(memberName) ? ""                  // A NotRoot can not contain a Root! eg. [DynComp] can't contain a [Comp] (instead, use [CompProp])
                                                                : @"
				else
				{"
                                                   + (Utils.CanContainItself(memberName) ? "" : @"
					if( memberAttrib is "                     + schemaEltName + @"Attribute )
						break; // Following attributes are for this "                         + schemaEltName) + @"
					if( memberAttrib is "                     + attributeName + @" )
						Write"                         + memberName + @"(writer, member, memberAttrib as " + attributeName + @", attribute, mappedClass);
				}"                ) + @"
			}"            ));
                            method.Body.Add(Refly.CodeDom.Stm.Snippet(
                                                "WriteUserDefinedContent(writer, member, typeof(" + attributeName + "), attribute);"));
                        }
                    }
                }

                if (type.IsMixed)                // used by elements like <param>
                {
                    method.Body.Add(Refly.CodeDom.Stm.Snippet(@"
			// Write the content of this element (mixed=""true"")
			writer.WriteString(attribute.Content);"            ));
                }
            }
            else
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("Unknow Element: ").Append(schemaElt.Name);
                if (schemaElt.SchemaType != null)
                {
                    sb.Append(", SchemaType = ").Append(schemaElt.SchemaType).Append(" - ").Append(schemaElt.SchemaType.Name);
                }
                if (!schemaElt.SchemaTypeName.IsEmpty)
                {
                    sb.Append(", SchemaTypeName = ").Append(schemaElt.SchemaTypeName.Name);
                }
                if (schemaElt.ElementSchemaType != null)
                {
                    sb.Append(", ElementType = ").Append(schemaElt.ElementSchemaType.Name);
                }
                log.Warn(sb.ToString());
            }

            method.Body.Add(Refly.CodeDom.Stm.Snippet(@"
			writer.WriteEndElement();"            ));
        }