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 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(); } }
public void Main() { 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 CodeTypeReferenceExpression("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)) { System.CodeDom.Compiler.IndentedTextWriter tw = new System.CodeDom.Compiler.IndentedTextWriter(sw, " "); provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions()); tw.Close(); } }
public void WriteMigrationFile() { // check if migration context base class exists string context = String.Format("{0}\\{1}.cs", Globals.Settings.Paths.Migration, Globals.Settings.Names.MigrationContext); if (!File.Exists(context)) { WriteMigrationContextFile(); } string migrationClass = String.Format(migrationName, Globals.Settings.Names.Database); string path = String.Format("{0}\\{1}.cs", Globals.Settings.Paths.Migration, Migration.ClassFile); var template = Activator.CreateInstance<DatabaseMigrationTemplate>(); var session = new TextTemplatingSession(); // add variables session["migrationClass"] = Migration.ClassFile; session["namespce"] = Globals.Settings.Namespaces.Migration; session["databaseName"] = Globals.Settings.Names.Database; session["connection"] = Globals.BasicConnectionString; template.Session = session; template.Initialize(); // generate the source file string source = template.TransformText(); // Create a StreamWriter to the output file. using (StreamWriter sw = new StreamWriter(path, false)) { IndentedTextWriter writer = new IndentedTextWriter(sw); writer.Write(source); writer.Close(); } }
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(); }
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; }
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; }
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(); } }
private static void GenerateViaCodeDOM(string outputFileName, System.CodeDom.Compiler.CodeDomProvider provider, System.CodeDom.CodeCompileUnit compileUnit) { System.CodeDom.Compiler.ICodeGenerator gen = provider.CreateGenerator(); System.CodeDom.Compiler.IndentedTextWriter tw; tw = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFileName, false), " "); System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions(); options.BracingStyle = "C"; gen.GenerateCodeFromCompileUnit(compileUnit, tw, options); tw.Flush(); tw.Close(); }
internal string GenerateSource(CodeDomProvider codeProvider) { StringBuilder sb = new StringBuilder(); TextWriter tWriter = new IndentedTextWriter(new StringWriter(sb)); CodeCompileUnit ccu = GenerateCode(); codeProvider.GenerateCodeFromCompileUnit(ccu, tWriter, new CodeGeneratorOptions()); codeProvider.Dispose(); tWriter.Close(); return sb.ToString(); }
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 void GenerateCodeUsingCodeDOM(CodeCompileUnit codeCompileUnit, string outputFile) { var options = new CodeGeneratorOptions { BracingStyle = "JS" }; var codeDomProvider = new TypescriptCodeProvider(); using (var textWriter = new IndentedTextWriter(new StreamWriter(outputFile))) { codeDomProvider.GenerateCodeFromCompileUnit(codeCompileUnit, textWriter, options); textWriter.Close(); } }
public void GenerateClass() { IndentedTextWriter writer = new IndentedTextWriter(new StreamWriter(this.fileName)); Console.WriteLine("Generating " + this.fileName); WriteFileHeader(writer); foreach (Stanza stanza in SyntaxInfo.Instance) { stanza.Generate(writer, this.className, isStatic); } WriteFileTrailer(writer); writer.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; }
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); }
public static void GenerateCode(string fileName, System.CodeDom.Compiler.CodeDomProvider provider, System.CodeDom.CodeCompileUnit compileUnit) { System.CodeDom.Compiler.ICodeGenerator gen = provider.CreateGenerator(); System.CodeDom.Compiler.IndentedTextWriter tw = null; try { tw = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(fileName, false), " "); gen.GenerateCodeFromCompileUnit(compileUnit, tw, new System.CodeDom.Compiler.CodeGeneratorOptions()); } finally { if (tw != null) { tw.Flush(); tw.Close(); } } }
public void Generate(CodeCompileUnit targetUnit) { CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BracingStyle = "C"; options.IndentString = " "; options.BlankLinesBetweenMembers = true; if (Directory.Exists(destinationPath) && ConfigurationApp.GetProperty("IsGeneratedSolutionDirectoryPurged") != "true") { Directory.Delete(destinationPath, true); ConfigurationApp.SaveProperty("IsGeneratedSolutionDirectoryPurged", "true"); } Directory.CreateDirectory(destinationPath); // Build the output file name. foreach (CodeNamespace namespaceUnit in targetUnit.Namespaces) { var namespaceName = namespaceUnit.Name; string sourceFile; if (provider.FileExtension[0] == '.') { sourceFile = this.PathFromNamespace(destinationPath, namespaceName) + "/" + namespaceUnit.Types[0].Name + provider.FileExtension; } else { sourceFile = this.PathFromNamespace(destinationPath, namespaceName) + "/" + namespaceUnit.Types[0].Name + "." + provider.FileExtension; } using (StreamWriter sw = new StreamWriter(sourceFile, false)) { IndentedTextWriter tw = new IndentedTextWriter(sw, " "); provider.GenerateCodeFromNamespace(namespaceUnit, tw, options); tw.Close(); } Console.WriteLine(sourceFile + " has been generated"); } }
static void Main(string[] args) { CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace myNamespace = new CodeNamespace("TestNamespace"); 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!")); CodeMemberField memberField = new CodeMemberField(); memberField.Type = new CodeTypeReference(typeof(float)); CodeMemberProperty memberPropery = new CodeMemberProperty(); //memberPropery.ha CodeConditionStatement cond = new CodeConditionStatement(); 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(); } }
// generate code to save on disk public void GenerateCode(CodeDomProvider provider, CodeCompileUnit compileUnit, string fileName) { // Build the source file name with the appropriate // language extension. String sourceFile; if (provider.FileExtension[0] == '.') { sourceFile = fileName + provider.FileExtension; } else { sourceFile = fileName + "." + provider.FileExtension; } // Create an IndentedTextWriter, constructed with // a StreamWriter to the source file. IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter(sourceFile, true), " "); // Generate source code using the code generator. provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions()); // Close the output file. tw.Close(); }
public void GenerateProxyClass() { EndpointAddress metadataAddress = new EndpointAddress("http://localhost/Sofka.Automation.Dummy.Wcf/Loan.svc?wsdl"); //string = "http://localhost/Sofka.Automation.Dummy.Wcf/Loan.svc"; string outputFile = @"d:\dev\Sofka\Test\TempFiles"; MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress); mexClient.ResolveMetadataReferences = false; MetadataSet metaDocs = mexClient.GetMetadata(); WsdlImporter importer = new WsdlImporter(metaDocs); ServiceContractGenerator generator = new ServiceContractGenerator(); // Add our custom DCAnnotationSurrogate // to write XSD annotations into the comments. object dataContractImporter; XsdDataContractImporter xsdDCImporter; if (!importer.State.TryGetValue(typeof(XsdDataContractImporter), out dataContractImporter)) { Console.WriteLine("Couldn't find the XsdDataContractImporter! Adding custom importer."); xsdDCImporter = new XsdDataContractImporter(); xsdDCImporter.Options = new ImportOptions(); importer.State.Add(typeof(XsdDataContractImporter), xsdDCImporter); } else { xsdDCImporter = (XsdDataContractImporter)dataContractImporter; if (xsdDCImporter.Options == null) { Console.WriteLine("There were no ImportOptions on the importer."); xsdDCImporter.Options = new ImportOptions(); } } //xsdDCImporter.Options.DataContractSurrogate = new DCAnnotationSurrogate(); // Uncomment the following code if you are going to do your work programmatically rather than add // the WsdlDocumentationImporters through a configuration file. /* * // The following code inserts a custom WsdlImporter without removing the other * // importers already in the collection. * System.Collections.Generic.IEnumerable<IWsdlImportExtension> exts = importer.WsdlImportExtensions; * System.Collections.Generic.List<IWsdlImportExtension> newExts * = new System.Collections.Generic.List<IWsdlImportExtension>(); * foreach (IWsdlImportExtension ext in exts) * { * Console.WriteLine("Default WSDL import extensions: {0}", ext.GetType().Name); * newExts.Add(ext); * } * newExts.Add(new WsdlDocumentationImporter()); * System.Collections.Generic.IEnumerable<IPolicyImportExtension> polExts = importer.PolicyImportExtensions; * importer = new WsdlImporter(metaDocs, polExts, newExts); */ System.Collections.ObjectModel.Collection <ContractDescription> contracts = importer.ImportAllContracts(); importer.ImportAllEndpoints(); foreach (ContractDescription contract in contracts) { generator.GenerateServiceContractType(contract); } if (generator.Errors.Count != 0) { throw new Exception("There were errors during code compilation."); } // Write the code dom System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions(); options.BracingStyle = "C"; System.CodeDom.Compiler.CodeDomProvider codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("C#"); System.CodeDom.Compiler.IndentedTextWriter textWriter = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile)); codeDomProvider.GenerateCodeFromCompileUnit( generator.TargetCompileUnit, textWriter, options ); textWriter.Close(); }
private void codeGeneration(List<Type> models) { // Kod üretecek c# derleyici ünitesi. var compileUnit = new CodeCompileUnit(); // Sınıfın üretileceği assembly. var assembly = Assembly.GetCallingAssembly(); // Sınıfın üretileceği namespace. var ns = new CodeNamespace(assembly.GetType().Namespace); // Namespace Assembly'e eklenir. compileUnit.Namespaces.Add(ns); // Oluşturulacak sınıf. var type = new CodeTypeDeclaration("AutoContext"); // Sınıf özellikleri ayarlanır. type.TypeAttributes = TypeAttributes.Class | TypeAttributes.Public; // Sınıf Namespace'e eklenir. ns.Types.Add(type); CodeMemberProperty prop = new CodeMemberProperty(); prop.Attributes = MemberAttributes.Public; prop.Name = "propName"; prop.Type = new CodeTypeReference(Type.GetType("DAI.Orm.Test.Category, DAI.Orm.Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")); type.Members.Add(prop); var provider = new CSharpCodeProvider(); String sourceFile; if (provider.FileExtension[0] == '.') { sourceFile = "AutoContext" + provider.FileExtension; } else { sourceFile = "AutoContext." + provider.FileExtension; } CodeGeneratorOptions cp = new CodeGeneratorOptions(); IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter(sourceFile, false), " "); provider.GenerateCodeFromCompileUnit(compileUnit, tw, cp); tw.Close(); }
private void TouchEverything (IndentedTextWriter itw) { Assert.AreSame (writer.Encoding, itw.Encoding, "Encoding"); Assert.AreEqual (0, itw.Indent, "Indent"); itw.Indent = 1; Assert.AreSame (writer, itw.InnerWriter, "InnerWriter"); Assert.AreEqual (writer.NewLine, itw.NewLine, "NewLine"); itw.Write (true); itw.Write (Char.MinValue); itw.Write (Path.InvalidPathChars); // char[] itw.Write (Double.MinValue); itw.Write (Int32.MinValue); itw.Write (Int64.MaxValue); itw.Write (new object ()); itw.Write (Single.MinValue); itw.Write (String.Empty); itw.Write ("{0}", String.Empty); itw.Write ("{0}{1}", Int32.MinValue, Int32.MaxValue); itw.Write ("{0}{1}{2}", Int32.MinValue, 0, Int32.MaxValue); itw.Write (Path.InvalidPathChars, 0, Path.InvalidPathChars.Length); itw.WriteLine (); itw.WriteLine (true); itw.WriteLine (Char.MinValue); itw.WriteLine (Path.InvalidPathChars); // char[] itw.WriteLine (Double.MinValue); itw.WriteLine (Int32.MinValue); itw.WriteLine (Int64.MaxValue); itw.WriteLine (new object ()); itw.WriteLine (Single.MinValue); itw.WriteLine (String.Empty); itw.WriteLine (UInt32.MaxValue); itw.WriteLine ("{0}", String.Empty); itw.WriteLine ("{0}{1}", Int32.MinValue, Int32.MaxValue); itw.WriteLine ("{0}{1}{2}", Int32.MinValue, 0, Int32.MaxValue); itw.WriteLine (Path.InvalidPathChars, 0, Path.InvalidPathChars.Length); itw.WriteLineNoTabs (String.Empty); itw.Flush (); itw.Close (); }
private static void GenerateCode(CodeCompileUnit ccu, string fileName, CodeDomProvider codeDomProvider = null) { CompilerParameters cp = new CompilerParameters(); String sourceFile; if (codeDomProvider == null) { codeDomProvider = new CSharpCodeProvider(); } if (codeDomProvider.FileExtension[0] == '.') { sourceFile = fileName + codeDomProvider.FileExtension; } else { sourceFile = fileName + "." + codeDomProvider.FileExtension; } IndentedTextWriter tw1 = new IndentedTextWriter(new StreamWriter(sourceFile, false), "\t"); codeDomProvider.GenerateCodeFromCompileUnit(ccu, tw1, new CodeGeneratorOptions()); tw1.Close(); //cp.GenerateExecutable = true; //cp.OutputAssembly = "CSharpSample.exe"; //cp.GenerateInMemory = false; //cr = csharpcodeprovider.CompileAssemblyFromDom(cp, ccu); }
/** * Hier wird aus einer vorgefertigten CodeCompileUnit ein C# SourceFile generiert */ public string GenerateCSharpCode(CodeCompileUnit compileunit) { // Create a StringWriter StringWriter sw = new StringWriter(); IndentedTextWriter tw = new IndentedTextWriter(sw, " "); // Generate source code using the code provider. provider.GenerateCodeFromCompileUnit(compileunit, tw, new CodeGeneratorOptions()); tw.Close(); sw.Close(); return sw.ToString(); }
public void WriteSourceFile() { string path = String.Format("{0}\\{1}.cs", Globals.Settings.Paths.Context, Globals.Settings.Names.Context); var template = Activator.CreateInstance<DatabaseTemplate>(); var session = new TextTemplatingSession(); // add variables session["namespce"] = Globals.Settings.Namespaces.Context; session["modelNamespace"] = Globals.Settings.Namespaces.Model; session["className"] = Globals.Settings.Names.Context; session["connection"] = Globals.InitialConnectionString; session["tables"] = Migration.ModelTableMap; template.Session = session; template.Initialize(); // generate the source file string source = template.TransformText(); // Create a StreamWriter to the output file. using (StreamWriter sw = new StreamWriter(path, false)) { IndentedTextWriter writer = new IndentedTextWriter(sw); writer.Write(source); writer.Close(); } }
private static void GenerateCode(string sourceFileName, CodeDomProvider provider, CodeCompileUnit compileunit) { var tw = new IndentedTextWriter(new StreamWriter(sourceFileName, false), " "); provider.GenerateCodeFromCompileUnit(compileunit, tw, new CodeGeneratorOptions()); tw.Close(); }
public void Produce(ClassStructureModel model) { CodeNamespace theNamespace = new CodeNamespace(model.NamespeceName); unit.Namespaces.Add(theNamespace); CodeNamespaceImport SystemImport = new CodeNamespaceImport("System"); theNamespace.Imports.Add(SystemImport); CodeNamespaceImport collectionsImport = new CodeNamespaceImport("System.Collections.Generic"); theNamespace.Imports.Add(collectionsImport); CodeTypeDeclaration mClass = new CodeTypeDeclaration(model.ClassName); mClass.IsClass = true; mClass.TypeAttributes = TypeAttributes.Public; theNamespace.Types.Add(mClass); //通过snippet 生成属性 if (model.PropertyCollection != null) { foreach (var item in model.PropertyCollection) { CodeSnippetTypeMember snippet = new CodeSnippetTypeMember(); //snippet.Comments.Add(new CodeCommentStatement("this is integer property", false)); snippet.Text = item.PropertyText; mClass.Members.Add(snippet); } } /* * .net 2.0 时代属性生成方式 CodeMemberField myField = new CodeMemberField("System.Int32", "_age"); mClass.Members.Add(myField); //属性 CodeMemberProperty ageAtrr = new CodeMemberProperty(); ageAtrr.Name = "Age"; ageAtrr.Type = new CodeTypeReference("System.Int32"); ageAtrr.Attributes = MemberAttributes.Public | MemberAttributes.Final; ageAtrr.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_age"))); ageAtrr.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_age"), new CodePropertySetValueReferenceExpression())); mClass.Members.Add(ageAtrr); * */ if (!System.IO.Directory.Exists(model.FileDirPath)) { Directory.CreateDirectory(model.FileDirPath); } if (!model.FileDirPath.EndsWith("/")) { model.FileDirPath = model.FileDirPath + "/"; } IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter(string.Format("{0}{1}.cs",model.FileDirPath,model.ClassName), false), " "); CodeDomProvider provide = new CSharpCodeProvider(); provide.GenerateCodeFromCompileUnit(unit, tw, new CodeGeneratorOptions()); tw.Close(); }
int DoDebugCodegen (Dictionary<string,CodeCompileUnit> units) { IndentedTextWriter itw = new IndentedTextWriter(Console.Out, "\t"); CodeGeneratorOptions opts = new CodeGeneratorOptions(); foreach (string name in units.Keys) { Console.WriteLine ("### Source: {0}", name); Console.WriteLine (); try { prov.GenerateCodeFromCompileUnit(units[name], itw, opts); } catch (Exception e) { Console.WriteLine ("Caught exception trying to generate code: {0}", e); return 1; } } itw.Close(); return 0; }
private void GenerateCode(string dummyFile, string srcFile) { // Add a source file containing the following line: string dummyClass = "namespace Microsoft.Research.DryadLinq { public static partial class " + ExtensionClassName + " { } }"; using (StreamWriter srcWriter = new StreamWriter(dummyFile)) { srcWriter.Write(dummyClass); srcWriter.Close(); } // Generate code for dryadUnit and store in srcFile: CSharpCodeProvider provider = new CSharpCodeProvider(); CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BracingStyle = "C"; using (IndentedTextWriter srcWriter = new IndentedTextWriter(new StreamWriter(srcFile), " ")) { provider.GenerateCodeFromCompileUnit(this.m_dryadLinqUnit, srcWriter, options); srcWriter.Close(); } }
private string CreateDslCode(List<List<SetMember>> states) { // Create the output string var sb = new StringBuilder(); var output = new IndentedTextWriter(new StringWriter(sb)); // This is so common that we might as well print it out to start with output.WriteLine("using System;"); output.WriteLine("using System.ComponentModel;"); if (type.Namespace != outputNamespace) { output.WriteLine(string.Format("using {0};", type.Namespace)); output.WriteLine(); } output.WriteLine(string.Format("namespace {0}", outputNamespace)); output.WriteLine("{"); output.Indent++; output.WriteLine("[EditorBrowsable(EditorBrowsableState.Never)]"); output.WriteLine("public interface IHide{0}ObjectMembers", syntaxStateClassname); output.WriteLine("{"); output.Indent++; output.WriteLine("[EditorBrowsable(EditorBrowsableState.Never)]"); output.WriteLine("Type GetType();"); output.WriteLine(""); output.WriteLine("[EditorBrowsable(EditorBrowsableState.Never)]"); output.WriteLine("int GetHashCode();"); output.WriteLine(""); output.WriteLine("[EditorBrowsable(EditorBrowsableState.Never)]"); output.WriteLine("string ToString();"); output.WriteLine(""); output.WriteLine("[EditorBrowsable(EditorBrowsableState.Never)]"); output.WriteLine("bool Equals(object obj);"); output.Indent--; output.WriteLine("}"); output.WriteLine(); for (int i = 0; i < states.Count; ++i) { var state = states[i]; if (state != null) // && state.Count > 0) { var className = string.Format("{0}{1}", syntaxStateClassname, i == 0 ? "" : i.ToString()); output.WriteLine(string.Format("public class {0} : IHide{1}ObjectMembers", className, syntaxStateClassname)); output.WriteLine("{"); output.Indent++; // Create a member called builder that accepts the underlying builder class // and a matching constructor output.WriteLine("private readonly {0} builder;", type.Name); output.WriteLine(); output.WriteLine("internal {0}({1} builder) {{ this.builder = builder; }}", className, type.Name); foreach (var setMember in state) { output.WriteLine(); foreach (var docLine in setMember.Documentation.Split('\n')) { output.WriteLine(docLine.Trim()); } output.Write(@"public {1}{0} ", setMember.NextState == 0 ? "" : setMember.NextState.ToString(), syntaxStateClassname); output.WriteLine(String.Format(setMember.Content, syntaxStateClassname, setMember.NextState == 0 ? "" : setMember.NextState.ToString())); } output.Indent--; output.WriteLine("}"); output.WriteLine(); } } output.Indent--; output.WriteLine("}"); output.Close(); return sb.ToString(); }
public void WriteSourceFile(string location) { string path = String.Format("{0}\\{1}.cs", location, ClassName); var template = Activator.CreateInstance<ModelTemplate>(); var session = new TextTemplatingSession(); // add the namespace session["namespce"] = Namespace; // add the class name session["className"] = ClassName; // add the table name session["tableName"] = TableName; // add the properties session["properties"] = PropertyMap; template.Session = session; template.Initialize(); // generate the source file string source = template.TransformText(); // Create a StreamWriter to the output file. using (StreamWriter sw = new StreamWriter(path, false)) { IndentedTextWriter writer = new IndentedTextWriter(sw); writer.Write(source); writer.Close(); } }
public static void GenerateOutput(string outputFile, System.Xml.XmlDocument xmlMetaData, string tableName) { System.CodeDom.Compiler.IndentedTextWriter writer = null; //System.Xml.XmlNode node; System.Xml.XmlNodeList nodeList; try { writer = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile)); nodeList = xmlMetaData.SelectNodes("/DataSet/Table[@Name='" + tableName + "']/Column"); writer.WriteLine("using System;"); writer.WriteLine(""); writer.WriteLine("/// <summary>"); writer.WriteLine("/// "); writer.WriteLine("/// </summar>"); writer.WriteLine("public class TargetOutput"); writer.WriteLine("{"); writer.Indent++; writer.WriteLine("#region Class level declarations"); foreach (System.Xml.XmlNode node in nodeList) { writer.WriteLine("private " + node.Attributes["Type"].Value + " m_" + node.Attributes["Name"].Value + ";"); } writer.WriteLine("#endregion"); writer.WriteLine(""); writer.WriteLine("#region Public Methods and Properties"); foreach (System.Xml.XmlNode node in nodeList) { writer.WriteLine("public " + node.Attributes["Type"].Value + " " + node.Attributes["Name"].Value); writer.WriteLine("{"); writer.Indent++; writer.WriteLine("get"); writer.WriteLine("{"); writer.Indent++; writer.WriteLine("return m_" + node.Attributes["Name"].Value + ";"); writer.Indent--; writer.WriteLine("}"); writer.WriteLine("set"); writer.WriteLine("{"); writer.Indent++; writer.WriteLine("m_" + node.Attributes["Name"].Value + " = value;"); writer.Indent--; writer.WriteLine("}"); writer.Indent--; writer.WriteLine("}"); writer.WriteLine(""); } writer.WriteLine("#endregion"); writer.WriteLine(""); writer.Indent--; writer.WriteLine("}"); } finally { if (writer != null) { writer.Flush(); writer.Close(); } } }
/// <summary> /// Generates the given service saving to the outputFile in the language passed in. /// </summary> public static void GenerateService(string serviceName, string version, string clientNamespace, string language, string outputFile) { // Generate the discovery URL for that service string url = string.Format(GoogleDiscoveryURL, serviceName, version); var discovery = CreateDefaultCachingDiscovery(url); // Build the service based on discovery information. var service = discovery.GetService(DiscoveryVersion.Version_1_0); var generator = new GoogleServiceGenerator(service, clientNamespace); var generatedCode = generator.GenerateCode(); var provider = CodeDomProvider.CreateProvider(language); using (StreamWriter sw = new StreamWriter(outputFile, false)) { IndentedTextWriter tw = new IndentedTextWriter(sw, " "); // Generate source code using the code provider. provider.GenerateCodeFromCompileUnit(generatedCode, tw, new CodeGeneratorOptions()); // Close the output file. tw.Close(); } }
/// <summary> /// Writes the class file. This method actually creates the physical /// class file and populates it accordingly. /// </summary> /// <param name="className">Name of the class file to be written.</param> /// <param name="codenamespace">The <see cref="CodeNamespace"/> which represents the /// file to be written.</param> private void WriteClassFile(string className, CodeNamespace codenamespace) { var csharpCodeProvider = new CSharpCodeProvider(); string sourceFile = this.OutputDirectory + this.buildSystem.DirectorySeparatorChar + className + "." + csharpCodeProvider.FileExtension; sourceFile = Utility.ScrubPathOfIllegalCharacters(sourceFile); var indentedTextWriter = new IndentedTextWriter(this.buildSystem.GetTextWriter(sourceFile, false), " "); var codeGenerationOptions = new CodeGeneratorOptions { BracingStyle = "C" }; csharpCodeProvider.GenerateCodeFromNamespace( codenamespace, indentedTextWriter, codeGenerationOptions); indentedTextWriter.Flush(); indentedTextWriter.Close(); }