Beispiel #1
0
		private void GenerateHelper()
		{
			using (GenParamsForm gpf = new GenParamsForm())
			{
				gpf.Namespace = _rootCategory.Name;
				if (gpf.ShowDialog(this) == DialogResult.OK)
				{
					CodeCompileUnit ccu = HelperGenerator.Generate(_rootCategory,
						gpf.Namespace, gpf.IsInternal);
					CSharpCodeProvider cscp = new CSharpCodeProvider();
					CodeGeneratorOptions cgo = new CodeGeneratorOptions();
					cgo.BracingStyle = "C";
					using (StreamWriter sw = new StreamWriter(
							Path.Combine(_directory, _rootCategory.TreeName + ".cs")))
						cscp.GenerateCodeFromCompileUnit(ccu, sw, cgo);
					if (gpf.ShowResult)
						using (ShowResultForm srf = new ShowResultForm())
						using (StringWriter strW = new StringWriter())
						{
							cscp.GenerateCodeFromCompileUnit(ccu, strW, cgo);
							srf.Result = strW.ToString();
							srf.ShowDialog(this);
						}
				}
			}
		}
        public override string CreateOutput()
        {
            RemoveComments = Generators.Any(p => !p.AlwaysRegenerate);

            Namespace = new CodeNamespace(NamespaceName);
            Unit = new CodeCompileUnit();
            Unit.Namespaces.Add(Namespace);
      
            foreach (var codeGenerator in Generators.Where(p=>p.IsValid()))
            {
               // UnityEngine.Debug.Log(codeGenerator.GetType().Name + " is generating");
                codeGenerator.Initialize(this);
            }
            var provider = new CSharpCodeProvider();

            var sb = new StringBuilder();
            var tw1 = new IndentedTextWriter(new StringWriter(sb), "    ");
            provider.GenerateCodeFromCompileUnit(Unit, tw1, new CodeGeneratorOptions());
            tw1.Close();
            if (RemoveComments)
            {
                var removedLines = sb.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.None).Skip(10).ToArray();
                return string.Join(Environment.NewLine, removedLines);
            }
            return sb.ToString();
        }
 public GeneratorResults ParseToCode(string TemplateCode, string defaultnamespace, string defaultclassname, string baseClassFullName)
 {
     GeneratorResults razorResults;
     var host = new RazorEngineHost(new CSharpRazorCodeLanguage());
     host.DefaultBaseClass = baseClassFullName;//typeof(BulaqTemplateForRazorBase).FullName;
     host.DefaultNamespace = defaultnamespace;
     host.DefaultClassName = defaultclassname;
     host.NamespaceImports.Add("System");
     host.NamespaceImports.Add("BulaqCMS.Models");
     host.GeneratedClassContext = new GeneratedClassContext("Execute", "Write", "WriteLiteral");
     var engine = new RazorTemplateEngine(host);
     using (var reader = new StringReader(TemplateCode))
     {
         razorResults = engine.GenerateCode(reader);
         CSharpCodeProvider codeProvider = new CSharpCodeProvider();
         CodeGeneratorOptions options = new CodeGeneratorOptions();
         options.BracingStyle = "C";
         using (StringWriter writer = new StringWriter())
         {
             IndentedTextWriter indentwriter = new IndentedTextWriter(writer, "    ");
             codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, indentwriter, options);
             indentwriter.Flush();
             indentwriter.Close();
             LastGeneratedCode = writer.GetStringBuilder().ToString();
             string codePath = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\code.cs";
             File.WriteAllText(codePath, LastGeneratedCode, Encoding.UTF8);
         }
     }
     return razorResults;
 }
Beispiel #4
0
        public void GenerateCode(State rootState, TextWriter output, string namespaceName, UsingList usings, string[] genericArguments)
        {
            _syntaxTypes.Clear();

            var code = new CodeCompileUnit();
            var ns = new CodeNamespace(namespaceName);
            code.Namespaces.Add(ns);
            ns.Imports.Add(new CodeNamespaceImport("System"));

            foreach (var u in usings)
            {
                ns.Imports.Add(new CodeNamespaceImport(u.Namespace));
            }

            GenerateCode(t => ns.Types.Add(t), rootState, new HashSet<string>(), genericArguments);

            ns.Types.Add(new CodeTypeDeclaration(_syntaxEnd)
            {
                Attributes = MemberAttributes.Public,
                TypeAttributes = TypeAttributes.Interface | TypeAttributes.Public,
                IsPartial = true,
            });

            var codeProvider = new CSharpCodeProvider();
            codeProvider.GenerateCodeFromCompileUnit(code, output, new CodeGeneratorOptions
            {
                BracingStyle = "C",
                IndentString = "\t",
            });
        }
        internal static TemplateCompilationResult Compile(Type templateType, string templateBody, IEnumerable<string> namespaces, string tempDirectory)
        {
            LoadRuntimeBinder();

            string className;
            var compileUnit = GetCodeCompileUnit(templateType, namespaces, templateBody, out className);

            string sourceCode;
            var codeProvider = new CSharpCodeProvider();
            var builder = new StringBuilder();

            using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture))
            {
                codeProvider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions());
                sourceCode = builder.ToString();
            }

            var parameters = CreateComplilerParameters(tempDirectory);
            var compileResult = codeProvider.CompileAssemblyFromDom(parameters, compileUnit);
            if (compileResult.Errors != null && compileResult.Errors.Count > 0)
                throw new TemplateCompilationException(compileResult.Errors, sourceCode, templateBody);

            var fullClassName = TEMPLATES_NAMESPACE + "." + className;

            return new TemplateCompilationResult
            {
                Type = compileResult.CompiledAssembly.GetType(fullClassName),
                SourceCode = sourceCode
            };
        }
        public void Run()
        {
            var compileUnit = new CodeCompileUnit();
            var myNamespace = new CodeNamespace("MyNamespace");
            myNamespace.Imports.Add(new CodeNamespaceImport("System"));
            var myClass = new CodeTypeDeclaration("MyClass");
            var start = new CodeEntryPointMethod();
            var cs1 = new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression("Console"),
                "WriteLine", new CodePrimitiveExpression("Hello World!"));

            compileUnit.Namespaces.Add(myNamespace);
            myNamespace.Types.Add(myClass);
            myClass.Members.Add(start);
            start.Statements.Add(cs1);

            var provider = new CSharpCodeProvider();

            using (var sw = new StreamWriter("HelloWorld.cs", false))
            {
                var tw = new IndentedTextWriter(sw, "    ");
                provider.GenerateCodeFromCompileUnit(compileUnit, tw,
                    new CodeGeneratorOptions());
                tw.Close();
            }
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            CodeNamespace myNamespace = new CodeNamespace("MyNamespace");
            myNamespace.Imports.Add(new CodeNamespaceImport("System"));
            CodeTypeDeclaration myClass = new CodeTypeDeclaration("MyClass");
            CodeEntryPointMethod start = new CodeEntryPointMethod();
            CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello World"));
            compileUnit.Namespaces.Add(myNamespace);
            myNamespace.Types.Add(myClass);
            myClass.Members.Add(start);
            start.Statements.Add(cs1);

            CSharpCodeProvider provider = new CSharpCodeProvider();

            using(StreamWriter sw = new StreamWriter("HelloWorld.cs", false))
            {
                IndentedTextWriter tw = new IndentedTextWriter(sw, " ");
                provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions());
                tw.Close();
            }

            Console.WriteLine("HelloWorld.cs generated in .../bin/Debug or .../bin/Release project folders.");

            Console.Write("Press a key to exit");
            Console.ReadKey();
        }
Beispiel #8
0
 /// <summary>
 /// Generates CSharp text from a compile unit and writes it to a text writer with the given options.
 /// </summary>
 /// <param name="compileUnit">The compile unit to generate text from.</param>
 /// <param name="writer">The text writer to write to.</param>
 /// <param name="options">The generation options.</param>
 public static void GenerateCSharpTo(this CodeCompileUnit compileUnit, TextWriter writer, CodeGeneratorOptions options)
 {
     using (var provider = new CSharpCodeProvider())
     {
         provider.GenerateCodeFromCompileUnit(compileUnit, writer, options);
     }
 }
Beispiel #9
0
        public static String GenerateCSharpCode(CodeCompileUnit compileunit)
        {
            // Generate the code with the C# code provider.
            CSharpCodeProvider provider = new CSharpCodeProvider();

            // Build the output file name.
            String sourceFile;
            if (provider.FileExtension[0] == '.')
            {
                sourceFile = "HelloWorld" + provider.FileExtension;
            }
            else
            {
                sourceFile = "HelloWorld." + provider.FileExtension;
            }

            // Create a TextWriter to a StreamWriter to the output file.
            IndentedTextWriter tw = new IndentedTextWriter(
                    new StreamWriter(sourceFile, false), "    ");

            // Generate source code using the code provider.
            provider.GenerateCodeFromCompileUnit(compileunit, tw,
                    new CodeGeneratorOptions());

            // Close the output file.
            tw.Close();

            return sourceFile;
        }
        /// <summary>
        /// This method Parses and compiles the source code into an Assembly and returns it
        /// </summary>
        /// <param name="baseClassType">The Type of the Base class the generated class descends from</param>
        /// <param name="namespaceOfGeneratedClass">The Namespace of the generated class</param>
        /// <param name="generatedClassName">The Class Name of the generated class</param>
        /// <param name="sourceCodeReader">A Text reader that is a warpper around the "Template" that is to be parsed and compiled</param>
        /// <returns>An instance of a generated assembly that contains the generated class</returns>
        public Assembly ParseAndCompileTemplate(Type baseClassType, string namespaceOfGeneratedClass, string generatedClassName, TextReader sourceCodeReader)
        {
            RazorTemplateEngine engine = InitializeRazorEngine(baseClassType, namespaceOfGeneratedClass, generatedClassName);
            GeneratorResults razorResults = engine.GenerateCode(sourceCodeReader);

            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            CodeGeneratorOptions options = new CodeGeneratorOptions();

            string generatedCode = null;
            using (StringWriter writer = new StringWriter())
            {
                codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, writer, options);
                generatedCode = writer.GetStringBuilder().ToString();
            }

            var outputAssemblyName = Path.GetTempPath() + Guid.NewGuid().ToString("N") + ".dll";
            CompilerParameters compilerParameters = new CompilerParameters(new string[]{}, outputAssemblyName);
            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
            compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Substring(8));
            compilerParameters.GenerateInMemory = false;

            CompilerResults compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResults.GeneratedCode);
            if (compilerResults.Errors.Count > 0)
            {
                var compileErrors = new StringBuilder();
                foreach (System.CodeDom.Compiler.CompilerError compileError in compilerResults.Errors)
                    compileErrors.Append(String.Format("Line: {0}\t Col: {1}\t Error: {2}\r\n", compileError.Line, compileError.Column, compileError.ErrorText));

                throw new Exception(compileErrors.ToString() + generatedCode);
            }

            return compilerResults.CompiledAssembly;
        }
        private async Task<CompilationResult> CompileCore(IFileInfo file)
        {
            var host = new MvcRazorHost();
            var engine = new RazorTemplateEngine(host);
            GeneratorResults results;
            using (TextReader rdr = new StreamReader(file.CreateReadStream()))
            {
                results = engine.GenerateCode(rdr, '_' + Path.GetFileNameWithoutExtension(file.Name), "Asp", file.PhysicalPath ?? file.Name);
            }

            string generatedCode;

            using (var writer = new StringWriter())
            using (var codeProvider = new CSharpCodeProvider())
            {
                codeProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, new CodeGeneratorOptions());
                generatedCode = writer.ToString();
            }

            if (!results.Success) 
            {
                return CompilationResult.Failed(generatedCode, results.ParserErrors.Select(e => new CompilationMessage(e.Message)));
            }

            Directory.CreateDirectory(_tempPath);
            string tempFile = Path.Combine(_tempPath, Path.GetRandomFileName() + ".cs");

            File.WriteAllText(tempFile, generatedCode);

            _tempFileSystem.TryGetFileInfo(tempFile, out file);
            return await _baseCompilationService.Compile(file);
        }
Beispiel #12
0
        private static string GenerateCodeFromRazorTemplate(WebPageRazorHost host, string virtualPath)
        {

            // Create Razor engine and use it to generate a CodeCompileUnit
            var engine = new RazorTemplateEngine(host);
            GeneratorResults results = null;
            VirtualFile file = HostingEnvironment.VirtualPathProvider.GetFile(virtualPath);
            using (var stream = file.Open())
            {
                using (TextReader reader = new StreamReader(stream))
                {
                    results = engine.GenerateCode(reader, className: null, rootNamespace: null, sourceFileName: host.PhysicalPath);
                }
            }

            if (!results.Success)
            {
                throw CreateExceptionFromParserError(results.ParserErrors.Last(), virtualPath);
            }

            // Use CodeDom to generate source code from the CodeCompileUnit
            var codeDomProvider = new CSharpCodeProvider();
            var srcFileWriter = new StringWriter();
            codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, srcFileWriter, new CodeGeneratorOptions());

            return srcFileWriter.ToString();
        }
Beispiel #13
0
        static void Main(string[] args)
        {
            Uri wsdlLocation = new Uri(Directory.GetCurrentDirectory() + "\\..\\..\\..\\OrderService.wsdl");

            Console.WriteLine("Beginning schema import.");
            Console.WriteLine();

            DiscoveryClientProtocol client = new DiscoveryClientProtocol();

            client.AllowAutoRedirect = true;
            DiscoveryDocument doc = client.DiscoverAny(wsdlLocation.ToString());

            client.ResolveAll();

            WebReferenceCollection references = new WebReferenceCollection();

            //add 1st web reference document
            WebReference wr = new WebReference(client.Documents, new CodeNamespace("Microsoft.Samples"));

            references.Add(wr);

            //add other web reference documents if needed

            CodeDomProvider codeProvider = new
                                           Microsoft.CSharp.CSharpCodeProvider();
            CodeCompileUnit Ccu = new CodeCompileUnit();

            Ccu.Namespaces.Add(wr.ProxyCode);
            try
            {
                //This is the new API call
                ServiceDescriptionImporter.GenerateWebReferences(
                    references,
                    codeProvider, Ccu, new WebReferenceOptions());
            }
            catch (Exception ex)
            {
                //do exception handling
                Console.WriteLine("An exception occured during importation:\n {0}", ex.ToString());
            }

            StreamWriter writer = new StreamWriter("OrderProxy.cs", false,
                                                   new System.Text.UTF8Encoding(true));

            codeProvider.GenerateCodeFromCompileUnit(Ccu, writer, new CodeGeneratorOptions());
            writer.Close();


//			importer.Import(new CodeNamespace("Microsoft.Samples"), compileUnit);
            Console.WriteLine();
            Console.WriteLine("Schema import completed.");

            //reader.Close();

            Console.WriteLine("Finished. Press any key to continue...");
            Console.ReadLine();

            System.Diagnostics.Process.Start("notepad", "OrderProxy.cs");
        }
        private static string DeclToString(CodeCompileUnit decl)
        {
            var provider = new CSharpCodeProvider();
            var opts = new CodeGeneratorOptions { IndentString = "    ", BracingStyle = "C" };

            var writer = new StringWriter();
            provider.GenerateCodeFromCompileUnit(decl, writer, opts);
            return writer.GetStringBuilder().ToString();
        }
        public string Generate(GenerationOptions options)
        {
            var compileUnit = this.GenerateUnit(options);

            var provider = new CSharpCodeProvider();
            using (var sw = new StringWriter())
            {
                provider.GenerateCodeFromCompileUnit(compileUnit, sw, new CodeGeneratorOptions {});
                string codeText = sw.GetStringBuilder().ToString();
                return SugarUp(codeText.Substring(codeText.IndexOf("using", System.StringComparison.Ordinal)));
            }
        }
        public static void Main()
        {
            CSharpCodeProvider cs = new CSharpCodeProvider();

            CodeGenerator cg = new CodeGenerator();
            using (StreamWriter sw=new StreamWriter("HelloWorld.cs",false))
            {
                IndentedTextWriter tw = new IndentedTextWriter(sw, "      ");
                cs.GenerateCodeFromCompileUnit(cg.GetCompierUnit(), tw, new CodeGeneratorOptions());
                tw.Close();
            }
        }
        private void GenerateFile()
        {
            CSharpCodeProvider provider = new CSharpCodeProvider();

            using (StreamWriter sw = new StreamWriter("HelloWorld.cs", false))
            {
                IndentedTextWriter tw = new IndentedTextWriter(sw, " ");
                provider.GenerateCodeFromCompileUnit(GenerateHelloWorldCode(), tw, new CodeGeneratorOptions());
                tw.Close();

            }
        }
        public static string ToCSharp(this CodeCompileUnit unit)
        {
            using (var stream = new MemoryStream())
            {
                var csharp = new CSharpCodeProvider();

                var writer = new IndentedTextWriter(new StreamWriter(stream));
                csharp.GenerateCodeFromCompileUnit(unit, writer, new CodeGeneratorOptions());
                writer.Flush();

                return stream.ReadToEnd();
            }
        }
Beispiel #19
0
 public void Parse()
 {
     string testScript = "alias test {\n  echo -a Hallo $left($me, 1) $+ .\n }\nalias -l coolHu { echo -a private! }";
     StringBuilder csharpCode = new StringBuilder();
     TextReader reader = new StringReader(testScript);
     TextWriter writer = new StringWriter(csharpCode);
     Parser p = new Parser();
     CodeCompileUnit result = p.Parse(reader);
     ICodeGenerator csharpGen = new CSharpCodeProvider().CreateGenerator(writer);
     csharpGen.GenerateCodeFromCompileUnit(result, writer, null);
     Console.WriteLine(csharpCode.ToString());
     Console.Out.Flush();
 }
Beispiel #20
0
        static void Main(string[] args)
        {
            CodeCompileUnit ccu = HelloWorldCodeDOM();

            CSharpCodeProvider provider = new CSharpCodeProvider();

            using(StreamWriter sw = new StreamWriter("HelloWorld.cs", false))
            {
                IndentedTextWriter tw = new IndentedTextWriter(sw, "    ");
                provider.GenerateCodeFromCompileUnit(ccu, tw, new CodeGeneratorOptions());
                tw.Close();
            }
        }
		private static string generateCSharpCode(CodeCompileUnit compileunit)
		{
			var provider = new CSharpCodeProvider();
			var stream = new MemoryStream();
			using (var sw = new StreamWriter(stream))
			{
				var tw = new IndentedTextWriter(sw, "    ");
				provider.GenerateCodeFromCompileUnit(compileunit, tw, new CodeGeneratorOptions());
				sw.Flush();
				stream.Position = 0;
				return new StreamReader(stream).ReadToEnd();
			}
		}
Beispiel #22
0
        /// <summary>
        /// Load a new engine instance and setup it up, parse template and generate code
        /// on a string form (only to get the source)
        /// </summary>
        /// <param name="template"></param>
        /// <returns></returns>
        public static string GenerateSourceCode(string template)
        {
            GeneratorResults razorResult = GenerateSourceCodeResult(template);

            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            string result = string.Empty;

            using (StringWriter sw = new StringWriter())
            {
                codeProvider.GenerateCodeFromCompileUnit(razorResult.GeneratedCode, sw, new CodeGeneratorOptions());
                result = sw.GetStringBuilder().ToString();
            }
            return result;
        }
Beispiel #23
0
        /// <summary>
        /// 创建类实体文件
        /// </summary>
        /// <param name="table">数据表实体</param>
        /// <param name="codeEntParam">实体参数</param>
        public void CreateCodeFile(Table table, CodeEntityParameter codeEntParam)
        {
            string className = string.Empty;
            CodeDomHelper codeDomHelper = new CodeDomHelper();

            className = GetClassName(table, codeEntParam);
            var codeCompileUnit = codeDomHelper.GetCodeCompileUnit(codeEntParam.NameSpace, className, string.IsNullOrWhiteSpace(table.Comment) ? table.Name : table.Comment);
            var codeTypeDeclaration = codeCompileUnit.Namespaces[0].Types[0];
            foreach (var column in table.Columns)
            {
                codeTypeDeclaration.Members.Add(codeDomHelper.CreateAutoProperty(column.Type, column.Name, column.Comment));
            }

            CodeDomProvider provider = new CSharpCodeProvider();
            CodeGeneratorOptions options = new CodeGeneratorOptions();
            options.BracingStyle = "C";
            var stringBuilder = new StringBuilder();
            using (provider)
            {
                var stringWriter = new StringWriter(stringBuilder);
                provider.GenerateCodeFromCompileUnit(codeCompileUnit, stringWriter, new CodeGeneratorOptions());
            }
            string tmpPath = string.IsNullOrWhiteSpace(codeEntParam.Suffix) ? "Entity" : codeEntParam.Suffix;
            string path = codeEntParam.SavePath;
            if (! codeEntParam.SavePath.EndsWith(tmpPath))
            {
                path = Path.Combine(codeEntParam.SavePath, tmpPath);
            }

            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                string filePath = Path.Combine(path, className + ".cs");
                File.WriteAllText(filePath, CleanupCode(stringBuilder.ToString()), Encoding.UTF8);
            }
            catch (IOException ioEx)
            {
                throw ioEx;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #24
0
 public void ShouldCreateCompleteCompileUnit()
 {
     var applicationPreferences = new ApplicationPreferences
                                      {
                                          NameSpace = "someNamespace",
                                          TableName = "someTableName"
                                      };
     var codeGenerator = new CodeGenerator(applicationPreferences, new ColumnDetails());
     CodeCompileUnit pkClass;
     var codeCompileUnit = codeGenerator.GetCompileUnit(out pkClass);
     var cSharpCodeProvider = new CSharpCodeProvider();
     var stringBuilder = new StringBuilder();
     cSharpCodeProvider.GenerateCodeFromCompileUnit(codeCompileUnit, new StringWriter(stringBuilder), new CodeGeneratorOptions());
     Assert.IsTrue(stringBuilder.ToString().Contains("namespace someNamespace"));
     Assert.IsTrue(stringBuilder.ToString().Contains("public class someTableName"));
     Assert.IsTrue(stringBuilder.ToString().Contains("public someTableName()"));
 }
		string GenerateCode(CodeCompileUnit compileUnit)
		{
			CSharpCodeProvider provider = new CSharpCodeProvider();
			
			TextWriter stringWriter = new StringWriter();
			
			CodeGeneratorOptions options = new CodeGeneratorOptions();
			options.BlankLinesBetweenMembers = true;
			options.BracingStyle = "C";
			options.ElseOnClosing = true;
			options.IndentString = "\t";
			options.VerbatimOrder = true;
			
			provider.GenerateCodeFromCompileUnit(compileUnit, stringWriter, options);
			
			return stringWriter.ToString();
		}
        public static string CreatePublicApiForAssembly(AssemblyDefinition assembly, Func<TypeDefinition, bool> shouldIncludeType, bool shouldIncludeAssemblyAttributes)
        {
            var publicApiBuilder = new StringBuilder();
            var cgo = new CodeGeneratorOptions
            {
                BracingStyle = "C",
                BlankLinesBetweenMembers = false,
                VerbatimOrder = false,
                IndentString = "    "
            };

            using (var provider = new CSharpCodeProvider())
            {
                var compileUnit = new CodeCompileUnit();
                if (shouldIncludeAssemblyAttributes && assembly.HasCustomAttributes)
                {
                    PopulateCustomAttributes(assembly, compileUnit.AssemblyCustomAttributes);
                }

                var publicTypes = assembly.Modules.SelectMany(m => m.GetTypes())
                    .Where(t => !t.IsNested && ShouldIncludeType(t) && shouldIncludeType(t))
                    .OrderBy(t => t.FullName);
                foreach (var publicType in publicTypes)
                {
                    var @namespace = compileUnit.Namespaces.Cast<CodeNamespace>()
                        .FirstOrDefault(n => n.Name == publicType.Namespace);
                    if (@namespace == null)
                    {
                        @namespace = new CodeNamespace(publicType.Namespace);
                        compileUnit.Namespaces.Add(@namespace);
                    }

                    var typeDeclaration = CreateTypeDeclaration(publicType);
                    @namespace.Types.Add(typeDeclaration);
                }

                using (var writer = new StringWriter())
                {
                    provider.GenerateCodeFromCompileUnit(compileUnit, writer, cgo);
                    var typeDeclarationText = NormaliseGeneratedCode(writer);
                    publicApiBuilder.AppendLine(typeDeclarationText);
                }
            }
            return NormaliseLineEndings(publicApiBuilder.ToString().Trim());
        }
 private string GetSourceFromCCU(CodeCompileUnit CCU)
 {
     CSharpCodeProvider cscp = new CSharpCodeProvider();
     StringBuilder sb = new StringBuilder();
     System.IO.StringWriter sw = new System.IO.StringWriter(sb);
     CodeGeneratorOptions options = new CodeGeneratorOptions();
     options.BracingStyle = "C";
     options.BlankLinesBetweenMembers = false;
     if (Generated)
     {
         cscp.GenerateCodeFromCompileUnit(CCU, sw, options);
     }
     else
     {
         cscp.GenerateCodeFromNamespace(CCU.Namespaces[0], sw, options);
     }
     return sb.ToString();
 }
Beispiel #28
0
        public static void GenerateCode(string xsdFilepath, string codeOutPath, string nameSpace)
        {
            FileStream stream = File.OpenRead(xsdFilepath);
            XmlSchema xsd = XmlSchema.Read(stream, ValidationCallbackOne);

            // Remove namespaceattribute from schema
            xsd.TargetNamespace = null;

            XmlSchemas xsds = new XmlSchemas { xsd };
            XmlSchemaImporter imp = new XmlSchemaImporter(xsds);
            //imp.Extensions.Add(new CustomSchemaImporterExtension());

            CodeNamespace ns = new CodeNamespace(nameSpace);
            XmlCodeExporter exp = new XmlCodeExporter(ns);

            foreach (XmlSchemaObject item in xsd.Items)
            {
                if (!(item is XmlSchemaElement))
                    continue;

                XmlSchemaElement xmlSchemaElement = (XmlSchemaElement)item;
                XmlQualifiedName xmlQualifiedName = new XmlQualifiedName(xmlSchemaElement.Name, xsd.TargetNamespace);
                XmlTypeMapping map = imp.ImportTypeMapping(xmlQualifiedName);

                exp.ExportTypeMapping(map);
            }

            // Remove all the attributes from each type in the CodeNamespace, except
            // System.Xml.Serialization.XmlTypeAttribute
            RemoveAttributes(ns);

            ToProperties(ns);

            CodeCompileUnit compileUnit = new CodeCompileUnit();

            compileUnit.Namespaces.Add(ns);
            CSharpCodeProvider provider = new CSharpCodeProvider();

            using (StreamWriter sw = new StreamWriter(codeOutPath, false))
            {
                CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions();
                provider.GenerateCodeFromCompileUnit(compileUnit, sw, codeGeneratorOptions);
            }
        }
Beispiel #29
0
Datei: test.cs Projekt: mono/gert
		static void Main (string[] args)
		{
			CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions ();
			codeGeneratorOptions.BlankLinesBetweenMembers = true;
			codeGeneratorOptions.BracingStyle = "C";
			codeGeneratorOptions.ElseOnClosing = false;
			codeGeneratorOptions.IndentString = "\t";

			// create the root of our compilation graph
			CodeCompileUnit ccu = new CodeCompileUnit ();

			// prepare the main namespace for the classes to generate
			CodeNamespace cn = new CodeNamespace ("MyNamespace");

			cn.Imports.Add (new CodeNamespaceImport ("System"));
			cn.Imports.Add (new CodeNamespaceImport ("System.Collections.Generic"));
			cn.Imports.Add (new CodeNamespaceImport ("System.Data"));

			// now link our namespace to the root of the compilation unit
			ccu.Namespaces.Add (cn);

			// prepare a test class
			CodeTypeDeclaration testClass = new CodeTypeDeclaration ("MyClass");
			testClass.IsClass = true;

			// prepare a field
			CodeMemberField field = new CodeMemberField (typeof (int?),
														"myField");

			testClass.Members.Add (field);

			cn.Types.Add (testClass);

			// now prepare the writer
			CSharpCodeProvider provider = new CSharpCodeProvider ();

			StreamWriter sw = new StreamWriter ("test-generated.cs");

			provider.GenerateCodeFromCompileUnit (ccu,
												 sw,
												 codeGeneratorOptions);

			sw.Close ();
		}
        public Assembly BuildAssembly()
        {
            GetReferencedTypes().ForEach(AddAssemblyReference);

            CSharpCodeProvider provider =
              new CSharpCodeProvider();
            ICodeCompiler compiler = provider.CreateCompiler();
            CompilerResults results =
               compiler.CompileAssemblyFromDom(CompilerParameters, this);
            if (results.Errors.HasErrors)
            {
                StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
                foreach (CompilerError error in results.Errors)
                {
                    errors.AppendFormat("Line {0},{1}\t: {2}\n",
                           error.Line, error.Column, error.ErrorText);
                }
                var buffer = new StringBuilder();
                using(var writer = new StringWriter(buffer))
                {
                    using (var textWriter = new IndentedTextWriter(writer))
                    {
                        provider.GenerateCodeFromCompileUnit(this, textWriter, new CodeGeneratorOptions());
                        textWriter.Close();
                    }
                }

                var source = new StringBuilder();
                var lines = buffer.ToString().Split(new string[] {Environment.NewLine}, StringSplitOptions.None);
                for(int i = 0; i < lines.Length; i++)
                {
                    source.AppendLine(i + lines[i]);
                }
                throw new Exception(
                    errors.ToString()
                    + Environment.NewLine
                    + Environment.NewLine
                    + "CODE:"
                    + Environment.NewLine
                    + source);
            }

            return results.CompiledAssembly;
        }
Beispiel #31
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            CSharpCodeProvider provider = new CSharpCodeProvider();

            using (StreamWriter sw = new StreamWriter("HelloWorld.cs", false))
            {
                IndentedTextWriter tw = new IndentedTextWriter(sw, "   ");
                provider.GenerateCodeFromCompileUnit(GetCode(), tw, new CodeGeneratorOptions());
                tw.Close();
            }

            Func<int, int, int> addFunc = (x, y) => x + y;
            Console.WriteLine(addFunc(2, 3));

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
Beispiel #32
0
    static void ImportSchemas(XmlSchemaSet schemas)
    {
        Console.WriteLine("Now doing schema import.");
        // The following code demonstrates schema import with
        // a surrogate. The surrogate is used to indicate that
        // the Person class already exists and that there is no
        // need to generate a new class when importing the
        // PersonSurrogated data contract. If the surrogate
        // was not used, schema import would generate a
        // PersonSurrogated class, and the person field
        // of Employee would be imported as
        // PersonSurrogated and not Person.
        XsdDataContractImporter xsdimp = new XsdDataContractImporter();

        xsdimp.Options = new ImportOptions();
        xsdimp.Options.DataContractSurrogate = new LegacyPersonTypeSurrogate();
        xsdimp.Import(schemas);

        // Write out the imported schema to a C-Sharp file.
        // The code contains data contract types.
        FileStream fs4 = new FileStream("sample.cs", FileMode.Create);

        try
        {
            StreamWriter tw = new StreamWriter(fs4);
            Microsoft.CSharp.CSharpCodeProvider cdp = new Microsoft.CSharp.CSharpCodeProvider();
            cdp.GenerateCodeFromCompileUnit(xsdimp.CodeCompileUnit, tw, null);
            tw.Flush();
        }
        finally
        {
            fs4.Dispose();
        }


        Console.WriteLine("\t  To see the results of schema export and import,");
        Console.WriteLine(" see SAMPLE.XSD and SAMPLE.CS.");

        Console.WriteLine(" Press ENTER to terminate the sample.");
        Console.ReadLine();
    }
Beispiel #33
0
        public void SaveDesignerClass(string outdir, string className, string ns)
        {
            var designerCsPath = Path.Combine(outdir, $"{className}.Designer.cs");

            string[] errors;
            var      codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
            var      data         = _data.ToDictionary(d => d.Key, d => d.Value.Value);
            var      code         = StronglyTypedResourceBuilder.Create(data, className, ns, codeProvider, false, out errors);

            if (errors.Length > 0)
            {
                foreach (var error in errors)
                {
                    Console.WriteLine(error);
                }
            }
            using (StreamWriter writer = new StreamWriter(designerCsPath, false, System.Text.Encoding.UTF8))
            {
                codeProvider.GenerateCodeFromCompileUnit(code, writer, new CodeGeneratorOptions());
            }
        }
Beispiel #34
0
    public void Test()
    {
        //声明代码的部分
        CodeCompileUnit compunit = new CodeCompileUnit();
        CodeNamespace   sample   = new CodeNamespace("WorpClasses");

        compunit.Namespaces.Add(sample);
        //引用命名空间
        sample.Imports.Add(new CodeNamespaceImport("System"));      //导入System命名空间
        sample.Imports.Add(new CodeNamespaceImport("System.Linq")); //导入System.Linq命名空间
        //在命名空间下添加一个类
        CodeTypeDeclaration wrapProxyClass = new CodeTypeDeclaration("类名");

        //wrapProxyClass.BaseTypes.Add(baseType);// 如果需要的话 在这里声明继承关系 (基类 , 接口)
        wrapProxyClass.CustomAttributes.Add(new CodeAttributeDeclaration("Serializable")); //添加一个Attribute到class上
        sample.Types.Add(wrapProxyClass);                                                  //把这个类添加到命名空间 ,待会儿才会编译这个类
        //为这个类添加一个无参构造函数  其实不添加也没事的, 只是做个demo而已
        CodeConstructor constructor = new CodeConstructor();

        constructor.Attributes = MemberAttributes.Public;
        wrapProxyClass.Members.Add(constructor);
        //为这个类添加一个方法   public override int 方法名(string str);
        CodeMemberMethod method = new CodeMemberMethod();

        method.Name       = "方法名";
        method.Attributes = MemberAttributes.Override | MemberAttributes.Public;              //声明方法是公开 并且override的
        method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "str")); //这个方法添加一个输入参数
        method.ReturnType = new CodeTypeReference(typeof(int));                               //声明返回值的类型
        method.Statements.Add(new CodeSnippetStatement(" return 1; "));                       //方法体里面很简单 直接返回 一个1;

        Microsoft.CSharp.CSharpCodeProvider cprovider = new Microsoft.CSharp.CSharpCodeProvider();
        StringBuilder fileContent = new StringBuilder();

        using (StringWriter sw = new StringWriter(fileContent))
        {
            cprovider.GenerateCodeFromCompileUnit(compunit, sw, new System.CodeDom.Compiler.CodeGeneratorOptions());//想把生成的代码保存为cs文件
        }
    }
Beispiel #35
0
        public static object GetDbInfo(System.Data.DataSet ds)
        {
            // Get a code provider object.
            System.CodeDom.Compiler.CodeDomProvider cdp = new Microsoft.CSharp.CSharpCodeProvider();

            // Create the namespace and import the default "System" namespace.
            System.CodeDom.CodeNamespace nmspc = new System.CodeDom.CodeNamespace("DataExplorer");
            nmspc.Imports.Add(new System.CodeDom.CodeNamespaceImport("System"));
            nmspc.Imports.Add(new System.CodeDom.CodeNamespaceImport("System.ComponentModel"));

            // Create a class object.
            System.CodeDom.CodeTypeDeclaration clsDbInfo = new System.CodeDom.CodeTypeDeclaration("DbInfo");
            clsDbInfo.IsClass = true;
            nmspc.Types.Add(clsDbInfo);

            // Add fields to the class for each value returned.
            List <string> fldNms = new List <string>();

            for (int i = 0; i < ds.Tables.Count; i++)
            {
                for (int j = 0; j < ds.Tables[i].Columns.Count; j++)
                {
                    string fldNm = "_" + ds.Tables[i].Columns[j].ColumnName.ToLower();
                    if (!fldNms.Contains(fldNm))
                    {
                        System.CodeDom.CodeMemberField fld = new System.CodeDom.CodeMemberField(typeof(System.String), fldNm);
                        fld.Attributes = System.CodeDom.MemberAttributes.Public;
                        clsDbInfo.Members.Add(fld);
                        fldNms.Add(fldNm);
                    }
                }
            }

            // Add properties for the class to access each field.
            List <string> propNms = new List <string>();

            for (int i = 0; i < ds.Tables.Count; i++)
            {
                for (int j = 0; j < ds.Tables[i].Columns.Count; j++)
                {
                    string
                        fldNm  = "_" + ds.Tables[i].Columns[j].ColumnName.ToLower(),
                        propNm = ds.Tables[i].Columns[j].ColumnName;

                    if (!propNms.Contains(propNm))
                    {
                        System.CodeDom.CodeMemberProperty prop = new System.CodeDom.CodeMemberProperty();
                        prop.Attributes = System.CodeDom.MemberAttributes.Public;
                        prop.Name       = propNm;
                        prop.Type       = new System.CodeDom.CodeTypeReference(typeof(System.String));
                        System.CodeDom.CodeVariableReferenceExpression retExp    = new System.CodeDom.CodeVariableReferenceExpression(fldNm);
                        System.CodeDom.CodeMethodReturnStatement       getReturn = new System.CodeDom.CodeMethodReturnStatement(retExp);
                        prop.GetStatements.Add(getReturn);
                        prop.HasGet = true;
                        prop.HasSet = false;
                        string catName = (ds.Tables[i].TableName.EndsWith("1")) ? "File Group" : "Database";
                        System.CodeDom.CodeAttributeDeclaration attrCat = new System.CodeDom.CodeAttributeDeclaration("Category", new System.CodeDom.CodeAttributeArgument(new System.CodeDom.CodePrimitiveExpression(catName)));
                        prop.CustomAttributes.Add(attrCat);
                        // Add the property to our class.
                        clsDbInfo.Members.Add(prop);
                        propNms.Add(propNm);
                    }
                }
            }

            // Add a constructor to the class
            System.CodeDom.CodeConstructor clsDbInfoConstr = new System.CodeDom.CodeConstructor();
            clsDbInfoConstr.Attributes = System.CodeDom.MemberAttributes.Public;
            clsDbInfo.Members.Add(clsDbInfoConstr);

            // Create a CompileUnit for this new type.
            System.CodeDom.CodeCompileUnit cu = new System.CodeDom.CodeCompileUnit();
            cu.ReferencedAssemblies.Add("system.dll");
            cu.Namespaces.Add(nmspc);

            // Now, we're ready to generate some code!
#if DEBUG
            // If we're running in DEBUG mode, I want to see the generated code.
            using (System.IO.FileStream fs = new System.IO.FileStream("dbinfo.cs", System.IO.FileMode.Create, System.IO.FileAccess.Write))
                using (System.IO.StreamWriter sr = new System.IO.StreamWriter(fs))
                    cdp.GenerateCodeFromCompileUnit(cu, sr, null);
#endif
            System.CodeDom.Compiler.CompilerParameters cp = new System.CodeDom.Compiler.CompilerParameters();
            cp.ReferencedAssemblies.Add("system.dll");
            cp.GenerateExecutable      = false;
            cp.IncludeDebugInformation = false;
            cp.GenerateInMemory        = false;
            //cp.OutputAssembly = _outputName;
            System.CodeDom.Compiler.CompilerResults cr = cdp.CompileAssemblyFromDom(cp, cu);

            if (!cr.Errors.HasErrors)
            {
                System.Reflection.Assembly asm = cr.CompiledAssembly;
                object dbInfo = asm.CreateInstance("DataExplorer.DbInfo");
                return(dbInfo);
            }
            else
            {
                return(null);
            }
        }