Exemplo n.º 1
0
        public string Generate(Interface @interface)
        {
            CodeTypeDeclaration type = GenerateCodeDom(@interface);

            PopulateWithElements(@interface.Symbols, type);

            StringBuilder sb = new StringBuilder();

            sb.AppendLine();
            provider.GenerateCodeFromType(type, new StringWriter(sb), opt);
            sb.AppendLine();

            return(sb.ToString());
        }
Exemplo n.º 2
0
    /// <summary>
    /// 创建C#
    /// </summary>
    static void CreateCsTable()
    {
        if (File.Exists(FilePath))
        {
            File.Delete(FilePath);
        }
        CodeTypeDeclaration myClass = new CodeTypeDeclaration(TabeName); //生成类

        myClass.IsClass        = true;
        myClass.TypeAttributes = TypeAttributes.Public;
        myClass.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference("System.Serializable")));
        for (int j = 0; j < tableClass.Length; j++)
        {
            CodeMemberField member = new CodeMemberField(GetTheType(tableClass[j]), tableTop[j]); //生成字段
            member.Attributes = MemberAttributes.Public;
            myClass.Members.Add(member);                                                          //把生成的字段加入到生成的类中
        }
        CodeDomProvider      provider = CodeDomProvider.CreateProvider("CSharp");
        CodeGeneratorOptions options  = new CodeGeneratorOptions();   //代码生成风格

        options.BracingStyle             = "C";
        options.BlankLinesBetweenMembers = true;
        using (StreamWriter sw = new StreamWriter(FilePath))
        {
            provider.GenerateCodeFromType(myClass, sw, options); //生成文件
        }
    }
Exemplo n.º 3
0
    static void Main()
    {
        // Declare a new type called Class1.
        CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1");

        // Declare a new generated code attribute
        GeneratedCodeAttribute generatedCodeAttribute =
            new GeneratedCodeAttribute("SampleCodeGenerator", "2.0.0.0");

        // Use the generated code attribute members in the attribute declaration
        CodeAttributeDeclaration codeAttrDecl =
            new CodeAttributeDeclaration(generatedCodeAttribute.GetType().Name,
                                         new CodeAttributeArgument(
                                             new CodePrimitiveExpression(generatedCodeAttribute.Tool)),
                                         new CodeAttributeArgument(
                                             new CodePrimitiveExpression(generatedCodeAttribute.Version)));

        class1.CustomAttributes.Add(codeAttrDecl);

        // Create a C# code provider
        CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

        // Generate code and send the output to the console
        provider.GenerateCodeFromType(class1, Console.Out, new CodeGeneratorOptions());
    }
Exemplo n.º 4
0
    static void Main()
    {
        // Declare a new type called Class1.
        CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1");

        // Declares a type constructor that calls a method.
        CodeConstructor constructor1 = new CodeConstructor();

        constructor1.Attributes = MemberAttributes.Public;
        class1.Members.Add(constructor1);

        // Creates a method reference for dict.Init.
        CodeMethodReferenceExpression methodRef1 =
            new CodeMethodReferenceExpression(
                new CodeVariableReferenceExpression("dict"),
                "Init",
                new CodeTypeReference[] {
            new CodeTypeReference("System.Decimal"),
            new CodeTypeReference("System.Int32")
        });

        // Invokes the dict.Init method from the constructor.
        CodeMethodInvokeExpression invoke1 = new CodeMethodInvokeExpression(methodRef1, new CodeParameterDeclarationExpression[] {});

        constructor1.Statements.Add(invoke1);

        // Create a C# code provider
        CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

        // Generate code and send the output to the console
        provider.GenerateCodeFromType(class1, Console.Out, new CodeGeneratorOptions());
    }
Exemplo n.º 5
0
        public void GenerateCodeFromType(CodeTypeDeclaration e, TextWriter w, CodeGeneratorOptions o)
        {
            if (Language == Language.CSharp)
            {
                provider.AddCSharpStaticClassSupport(e, ref w);
            }
            else if (Language == Language.VisualBasic)
            {
                provider.AddVBModuleSupport(e);
            }

            provider.GenerateCodeFromType(e, w, o);
        }
Exemplo n.º 6
0
        /// <summary>Called when extension shall process generated code</summary>
        /// <param name="code">The code</param>
        /// <param name="provider">CodeDOM provider (the language)</param>
        /// <version version="1.5.3">Parameter <c>Provider</c> renamed to <c>provider</c></version>
        public void PostProcess(ref string code, CodeDomProvider provider)
        {
            System.IO.StringWriter tw = new System.IO.StringWriter();
            provider.GenerateCodeFromStatement(new CodeCommentStatement(FirtsLineOfAccessor), tw, new System.CodeDom.Compiler.CodeGeneratorOptions());
            string srch = tw.GetStringBuilder().ToString();

            if (srch.EndsWith("\r\n"))
            {
                srch = srch.Substring(0, srch.Length - 2);
            }
            else if (srch.EndsWith("\r") || srch.EndsWith("\n"))
            {
                srch = srch.Substring(0, srch.Length - 1);
            }
            tw = new System.IO.StringWriter();
            CodeTypeDeclaration foo = new CodeTypeDeclaration("foo");

            foo.CustomAttributes.Add(NewAttribute);
            provider.GenerateCodeFromType(foo, tw, new System.CodeDom.Compiler.CodeGeneratorOptions());
            string attr = new System.IO.StringReader(tw.GetStringBuilder().ToString()).ReadLine();

            System.IO.StringReader sr    = new System.IO.StringReader(code);
            List <String>          Lines = new List <string>();

            do
            {
                string line = sr.ReadLine();
                if (line == null)
                {
                    break;
                }
                if (line.EndsWith(srch))
                {
                    Lines[Lines.Count - 1] = attr + "\r\n" + Lines[Lines.Count - 1];
                }
                else
                {
                    Lines.Add(line);
                }
            } while (true);
            System.Text.StringBuilder b = new System.Text.StringBuilder();
            foreach (string line in Lines)
            {
                b.AppendLine(line);
            }
            code = b.ToString();
        }
Exemplo n.º 7
0
    static void Main()
    {
        // Declare a new type called Class1.
        CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1");

        // Declare a new code attribute
        CodeAttributeDeclaration codeAttrDecl = new CodeAttributeDeclaration(
            "System.CLSCompliantAttribute",
            new CodeAttributeArgument(new CodePrimitiveExpression(false)));

        class1.CustomAttributes.Add(codeAttrDecl);

        // Create a C# code provider
        CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

        // Generate code and send the output to the console
        provider.GenerateCodeFromType(class1, Console.Out, new CodeGeneratorOptions());
    }
Exemplo n.º 8
0
        //static String GetSpace(Int32 n)
        //{
        //    return new String(' ', n);
        //}

        //static String GetTabSpace(Int32 n)
        //{
        //    return GetSpace(n * 4);
        //}
        #endregion

        #region 生成代码
        /// <summary>生成C#代码</summary>
        /// <returns></returns>
        public String GenerateCSharpCode()
        {
            CodeDomProvider      provider = CodeDomProvider.CreateProvider("CSharp");
            CodeGeneratorOptions options  = new CodeGeneratorOptions();

            options.BracingStyle  = "C";
            options.VerbatimOrder = true;
            using (StringWriter writer = new StringWriter())
            {
                provider.GenerateCodeFromType(Class, writer, options);
                //return writer.ToString();

                String str = writer.ToString();

                // 去掉头部
                //str = str.Substring(str.IndexOf("using"));
                Type dt = typeof(DateTime);
                str = str.Replace(dt.ToString(), dt.Name);

                return(str);
            }
        }
Exemplo n.º 9
0
    static void Main()
    {
        // Declare a new type called Class1.
        CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1");

        // Use attributes to mark the class as serializable and obsolete.
        CodeAttributeDeclaration codeAttrDecl =
            new CodeAttributeDeclaration("System.Serializable");

        class1.CustomAttributes.Add(codeAttrDecl);

        CodeAttributeArgument codeAttr =
            new CodeAttributeArgument(new CodePrimitiveExpression("This class is obsolete."));

        codeAttrDecl = new CodeAttributeDeclaration("System.Obsolete", codeAttr);
        class1.CustomAttributes.Add(codeAttrDecl);

        // Create a C# code provider
        CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

        // Generate code and send the output to the console
        provider.GenerateCodeFromType(class1, Console.Out, new CodeGeneratorOptions());
    }
Exemplo n.º 10
0
        private static string GenerateCode(CodeObject c, CodeDomProvider provider)
        {
            var sb      = new StringBuilder();
            var writer  = new StringWriter(sb);
            var options = new CodeGeneratorOptions();

            if (c is CodeStatement)
            {
                provider.GenerateCodeFromStatement((CodeStatement)c, writer, options);
            }
            else if (c is CodeCompileUnit)
            {
                provider.GenerateCodeFromCompileUnit((CodeCompileUnit)c, writer, options);
            }
            else if (c is CodeExpression)
            {
                provider.GenerateCodeFromExpression((CodeExpression)c, writer, options);
            }
            else if (c is CodeTypeMember)
            {
                provider.GenerateCodeFromMember((CodeTypeMember)c, writer, options);
            }
            else if (c is CodeTypeDeclaration)
            {
                provider.GenerateCodeFromType((CodeTypeDeclaration)c, writer, options);
            }
            else if (c is CodeNamespace)
            {
                provider.GenerateCodeFromNamespace((CodeNamespace)c, writer, options);
            }
            else
            {
                throw new ArgumentException($"Tests not set up for unexpected type: {c.GetType()}");
            }

            return(sb.ToString());
        }
Exemplo n.º 11
0
        private static string GenerateCode(CodeObject c, CodeDomProvider provider)
        {
            var sb      = new StringBuilder();
            var writer  = new StringWriter(sb);
            var options = new CodeGeneratorOptions();

            if (c is CodeStatement)
            {
                provider.GenerateCodeFromStatement((CodeStatement)c, writer, options);
            }
            else if (c is CodeCompileUnit)
            {
                provider.GenerateCodeFromCompileUnit((CodeCompileUnit)c, writer, options);
            }
            else if (c is CodeExpression)
            {
                provider.GenerateCodeFromExpression((CodeExpression)c, writer, options);
            }
            else if (c is CodeTypeMember)
            {
                provider.GenerateCodeFromMember((CodeTypeMember)c, writer, options);
            }
            else if (c is CodeTypeDeclaration)
            {
                provider.GenerateCodeFromType((CodeTypeDeclaration)c, writer, options);
            }
            else if (c is CodeNamespace)
            {
                provider.GenerateCodeFromNamespace((CodeNamespace)c, writer, options);
            }
            else
            {
                Assert.False(true, $"Unknown type: {c.GetType()}");
            }

            return(sb.ToString());
        }
        public string Convert(CodeDomProvider codeProvider)
        {
            StringBuilder           code          = new StringBuilder();
            List <XmlQualifiedName> arrayTypeList = BuildDataContractArrayTypeList();

            try
            {
                CodeCompileUnit compileUnit = new CodeCompileUnit();
                CodeNamespace   namespace2  = new CodeNamespace();
                compileUnit.Namespaces.Add(namespace2);

                XmlCodeExporter codeExporter = new XmlCodeExporter(namespace2, compileUnit, codeProvider, CodeGenerationOptions.GenerateProperties, null);

                // XmlSchemaImporter needs XmlSchemas and not XmlSchemaSet
                XmlSchemas userSchemas = new XmlSchemas();
                foreach (XmlSchema schema in schemas.Schemas())
                {
                    userSchemas.Add(schema);
                }

                XmlSchemaImporter schemaImporter = new XmlSchemaImporter(userSchemas, CodeGenerationOptions.GenerateProperties, codeProvider, new ImportContext(new CodeIdentifiers(), false));

                foreach (XmlSchema schema in userSchemas)
                {
                    if (schema != null)
                    {
                        foreach (XmlSchemaElement element in schema.Elements.Values)
                        {
                            // Don't generate code for abstract elements or array types
                            if (!element.IsAbstract && !arrayTypeList.Contains(element.QualifiedName))
                            {
                                XmlTypeMapping mapping = schemaImporter.ImportTypeMapping(element.QualifiedName);
                                codeExporter.ExportTypeMapping(mapping);
                            }
                        }
                    }
                }

                CodeTypeDeclarationCollection types = namespace2.Types;
                if ((types == null) || (types.Count == 0))
                {
                    //RtlAwareMessageBox.Show(
//                        PublicDI.log.error("The XML instance or XML Schema is valid, but no classes could be generated to match. Please ensure it contains a root element with some nested elements inside of it.");
                    //, "Error",
                    //    MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0);
                }
                else
                {
                    CodeGenerator.ValidateIdentifiers(namespace2);

                    // Now we have to run Silverlight-specific fix-up

                    //DC
//                    ServiceContractGenerator generator = new ServiceContractGenerator(compileUnit);
//                    WcfSilverlightCodeGenerationExtension fixupExtension = new WcfSilverlightCodeGenerationExtension();
//                    fixupExtension.ClientGenerated(generator);

                    using (StringWriter writer = new StringWriter(code, CultureInfo.CurrentCulture))
                    {
                        foreach (CodeTypeDeclaration type in namespace2.Types)
                        {
                            codeProvider.GenerateCodeFromType(type, writer, null);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException))
                {
                    throw;
                }
                //RtlAwareMessageBox.Show(  //DC
//                PublicDI.log.error("The XML instance or XML Schema is valid, but no classes could be generated to match." + Environment.NewLine + Environment.NewLine + exception.Message);
                //, "Error",
                //    MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0);
            }

            return(code.ToString());
        }
 protected override void ProcessRecord()
 {
     if (CompileUnit != null && CompileUnit.Length > 0)
     {
         foreach (CodeCompileUnit compileUnit in CompileUnit)
         {
             if (compileUnit != null)
             {
                 _provider.GenerateCodeFromCompileUnit(compileUnit, _indentedWriter, Options);
             }
         }
     }
     else if (Expression != null && Expression.Length > 0)
     {
         foreach (CodeExpression expr in Expression)
         {
             if (expr != null)
             {
                 _provider.GenerateCodeFromExpression(expr, _indentedWriter, Options);
             }
         }
     }
     else if (Member != null && Member.Length > 0)
     {
         foreach (CodeTypeMember member in Member)
         {
             if (member != null)
             {
                 _provider.GenerateCodeFromMember(member, _indentedWriter, Options);
             }
         }
     }
     else if (NS != null && NS.Length > 0)
     {
         foreach (CodeNamespace ns in NS)
         {
             if (ns != null)
             {
                 _provider.GenerateCodeFromNamespace(ns, _indentedWriter, Options);
             }
         }
     }
     else if (Statement != null && Statement.Length > 0)
     {
         foreach (CodeStatement st in Statement)
         {
             if (st != null)
             {
                 _provider.GenerateCodeFromStatement(st, _indentedWriter, Options);
             }
         }
     }
     else if (Type != null && Type.Length > 0)
     {
         foreach (CodeTypeDeclaration t in Type)
         {
             if (t != null)
             {
                 _provider.GenerateCodeFromType(t, _indentedWriter, Options);
             }
         }
     }
 }