public MainForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); CodeCompileUnit cu = GeneraCodigo(); CodeDomProvider dp = CodeDomProvider.CreateProvider("CSharp"); //Imprimir el código StringWriter sw = new StringWriter(); System.CodeDom.Compiler.IndentedTextWriter itw = new IndentedTextWriter(sw); CodeGeneratorOptions go = new CodeGeneratorOptions(); go.BlankLinesBetweenMembers = false; dp.GenerateCodeFromCompileUnit(cu,sw,go); this.tbFuenteGenerado.Text = sw.ToString(); //Compilar desde dom CompilerParameters cp = new CompilerParameters(new string[]{},"borrame.dll"); CompilerResults cr = dp.CompileAssemblyFromDom(cp,cu); tbErrores.Text = ""; foreach(CompilerError ce in cr.Errors){ tbErrores.Text += String.Format("{0}){1} in {2} at line {3} column {4} isWarning{5}",ce.ErrorNumber,ce.ErrorText,ce.FileName,ce.Line,ce.Column,ce.IsWarning); } }
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 Dump(IndentedTextWriter w) { w.Write("Bitmap Fill id_" + this.CharacterId + " type: "); w.Write(Enum.GetName(typeof(FillType), this.FillType)); w.Write(" "); Matrix.Dump(w); }
private void GenerateCS() { IMemberOperatorGenerator gen = null; switch (Operator) { case OperatorType.Explicit: gen = new ExplicitOperatorGeneratorCS(); break; case OperatorType.Implicit: gen = new ImplicitOperatorGeneratorCS(); break; default: throw new NotImplementedException(string.Format("Какая-то несанкционированная xуйня")); } using (Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider()) { System.CodeDom.Compiler.CodeGeneratorOptions opts = new System.CodeDom.Compiler.CodeGeneratorOptions(); using (System.CodeDom.Compiler.IndentedTextWriter tw = new System.CodeDom.Compiler.IndentedTextWriter(new StringWriter(), opts.IndentString)) { gen.GenerateDeclaration(tw, provider, opts, ReturnType, Parameters); tw.WriteLine("{"); tw.Indent++; gen.GenerateStatemets(tw, provider, opts, Statements); tw.Indent--; tw.WriteLine("}"); Text = tw.InnerWriter.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; }
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(); }
/// <summary> /// 添加一个 SQL 语句的执行项 /// </summary> /// <param name="sql"></param> protected void AddRun(IndentedTextWriter sql) { this.AddRun(new SqlMigrationRun { Sql = sql.InnerWriter.ToString() }); }
internal override IndentedTextWriter WriteDiffs(IndentedTextWriter writer, HashSet<ValueDiff> written) { if (!written.Add(this.ValueDiff)) { writer.Write("..."); return writer; } if (this.Diffs.Count == 0) { writer.Write($"[{this.Index}] x: {this.X.ToInvariantOrNullString()} y: {this.Y.ToInvariantOrNullString()}"); return writer; } writer.Write($"[{this.Index}]"); writer.Indent++; foreach (var diff in this.Diffs) { writer.WriteLine(); diff.WriteDiffs(writer, written); } writer.Indent--; return writer; }
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 virtual void WriteCode(IndentedTextWriter writer) { writer.Write(TypeName); writer.Write(" MagickScript::Create"); writer.Write(ClassName); writer.WriteLine("(XmlElement^ element)"); WriteStartColon(writer); WriteMethod(writer, Constructors); WriteEndColon(writer); if (!WriteEnumerable) return; writer.Write("Collection<"); writer.Write(TypeName); writer.Write(">^ MagickScript::Create"); writer.Write(ClassName); writer.WriteLine("s(XmlElement^ element)"); WriteStartColon(writer); writer.Write("Collection<"); writer.Write(TypeName); writer.Write(">^ collection = gcnew Collection<"); writer.Write(TypeName); writer.WriteLine(">();"); writer.WriteLine("for each (XmlElement^ elem in element->SelectNodes(\"*\"))"); WriteStartColon(writer); writer.Write("collection->Add(Create"); writer.Write(TypeName.Replace("^", "")); writer.WriteLine("(elem));"); WriteEndColon(writer); writer.WriteLine("return collection;"); WriteEndColon(writer); }
private static void WriteMessages(this StringWriter writer, Exception e) { using (var indentedWriter = new IndentedTextWriter(writer, " ")) { WriteMessages(indentedWriter, e); } }
public override void AppendDDL(IndentedTextWriter textWriter) { if (!string.IsNullOrEmpty(Note)) { textWriter.WriteLine("/*"); textWriter.Write(" "); textWriter.WriteLine(Note); textWriter.WriteLine("*/"); } textWriter.WriteLine($"IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'{ForeignKey.QuotedForeignKeyName}'))"); textWriter.Indent++; textWriter.WriteLine($"ALTER TABLE {ForeignKey.ParentObjectIdentifier}"); textWriter.Indent++; textWriter.Write("ADD "); textWriter.Indent++; ForeignKey.AppendDDL(textWriter); textWriter.WriteLine(";"); textWriter.Indent--; textWriter.Indent--; textWriter.Indent--; textWriter.WriteLine("GO"); }
public static string Convert(string fileName, out SwfCompilationUnit scu, out VexObject v) { v = null; string result = "Failed to convert."; FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); string name = Path.GetFileNameWithoutExtension(fileName); SwfReader r = new SwfReader(br.ReadBytes((int)fs.Length)); scu = new SwfCompilationUnit(r, name); if (scu.IsValid) { result = "\n\n**** Converting to SwfCompilationUnit ****\n"; #if DEBUG StringWriter sw = new StringWriter(); IndentedTextWriter w = new IndentedTextWriter(sw); scu.Dump(w); Debug.WriteLine(sw.ToString()); #endif result += scu.Log.ToString(); SwfToVex s2v = new SwfToVex(); v = s2v.Convert(scu); result += "\n\n**** Converting to Vex ****\n"; result += s2v.Log.ToString(); } return result; }
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(); } }
/// <summary> /// Converts a given coordinate system object to a WKT string. /// </summary> /// <param name="obj">The coordinate system object to convert.</param> /// <returns>A string containing WKT.</returns> public static string Write(object obj) { TextWriter textwriter = new StringWriter(); IndentedTextWriter indentedWriter = new IndentedTextWriter(textwriter); Write(obj, indentedWriter); return textwriter.ToString(); }
/// <summary> /// Initializes a new instance of the <see cref="DataSourceWrapperWriter"/> class. /// </summary> public DataSourceWrapperWriter() { LineCount = 1; strWriter = new StringWriter(); txtWriter = new IndentedTextWriter(strWriter); }
public override void WriteText(IndentedTextWriter writer) { writer.WriteLine("CResourceIntrospectionManifest"); writer.WriteLine("{"); writer.Indent++; writer.WriteLine("uint32 m_nIntrospectionVersion = 0x{0:x8}", IntrospectionVersion); writer.WriteLine("Struct m_ReferencedStructs[{0}] =", ReferencedStructs.Count); writer.WriteLine("["); writer.Indent++; foreach (var refStruct in ReferencedStructs) { refStruct.WriteText(writer); } writer.Indent--; writer.WriteLine("]"); writer.WriteLine("Struct m_ReferencedEnums[{0}] =", ReferencedEnums.Count); writer.WriteLine("["); writer.Indent++; foreach (var refEnum in ReferencedEnums) { refEnum.WriteText(writer); } writer.Indent--; writer.WriteLine("]"); writer.Indent--; writer.WriteLine("}"); }
//=========================================================================================== private void WriteCallIfElse(IndentedTextWriter writer, MethodBase[] methods) { for (int i = 0; i < methods.Length; i++) { ParameterInfo[] parameters = methods[i].GetParameters(); if (i > 0) writer.Write("else "); writer.Write("if ("); if (parameters.Length > 0) { writer.Write("OnlyContains(arguments"); foreach (ParameterInfo parameter in parameters) { writer.Write(", \""); writer.Write(parameter.Name); writer.Write("\""); } writer.Write(")"); } else { writer.Write("arguments->Count == 0"); } writer.WriteLine(")"); writer.Indent++; WriteHashtableCall(writer, methods[i], parameters); writer.Indent--; } }
public override void AppendDDL(IndentedTextWriter textWriter) { if (!string.IsNullOrEmpty(Note)) { textWriter.WriteLine("/*"); textWriter.Write(" "); textWriter.WriteLine(Note); textWriter.WriteLine("*/"); } textWriter.WriteLine($"IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'{ObjectIdentitifer}') AND name = N'{Name}')"); textWriter.WriteLine($"CREATE {(IsUnique ? "UNIQUE " : "")}{(IsClusterd ? "CLUSTERED" : "NONCLUSTERED")} INDEX [{Name}] ON {ObjectIdentitifer} ("); textWriter.Write(" "); textWriter.WriteLine(string.Join("," + Environment.NewLine + " ", KeyColumns)); textWriter.Write(")"); if (IncludedColumns != null && IncludedColumns.Any()) { textWriter.WriteLine(); textWriter.WriteLine("INCLUDE ("); textWriter.Write(" "); textWriter.WriteLine(string.Join("," + Environment.NewLine + " ", IncludedColumns)); textWriter.Write(")"); } if (!string.IsNullOrEmpty(FilterDefinition)) { textWriter.WriteLine(); textWriter.WriteLine("WHERE "); textWriter.Write(FilterDefinition); } textWriter.WriteLine(";"); textWriter.WriteLine("GO"); }
private static void PrintException(IndentedTextWriter iWriter, Exception ex) { if (ex == null) { iWriter.WriteLine("(null)"); return; } iWriter.WriteLine("[{0}]", ex.GetType()); iWriter.Indent++; iWriter.WriteLine("Message: {0}", ex.Message); iWriter.WriteLine("Source: {0}", ex.Source); iWriter.WriteLine("TargetSite: {0}", ex.TargetSite); iWriter.WriteLine("HelpLink: {0}", ex.HelpLink); if (ex.Data.Count > 0) { iWriter.WriteLine("Data:"); iWriter.Indent++; foreach (var key in ex.Data.Keys) { iWriter.WriteLine("• {0} = {1}", key, ex.Data[key]); } iWriter.Indent--; } iWriter.WriteLine("Full Stack Trace:"); iWriter.Indent++; PrintStackTrace(iWriter, new StackTrace(ex, true)); iWriter.Indent--; iWriter.WriteLine("Inner Exception: "); iWriter.Indent++; PrintException(iWriter, ex.InnerException); iWriter.Indent--; }
public static IEModException Exception(Exception innerEx, string message, params object[] args) { Log("!! EXCEPTION !!: " + message, args); args = args ?? new object[] {}; var writer = new IndentedTextWriter(new StringWriter()); PrintStackTrace(writer, new StackTrace(1)); return new IEModException(String.Format(message, args), innerEx); }
public void WriteText(IndentedTextWriter writer) { writer.WriteLine("ResourceEditStringData_t"); writer.WriteLine("{"); writer.Indent++; writer.WriteLine("CResourceString m_Name = \"{0}\"", Name); var lines = Value.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None); if (lines.Length > 1) { writer.Indent++; writer.Write("CResourceString m_String = \""); foreach (var line in lines) { writer.WriteLine(line); } writer.WriteLine("\""); writer.Indent--; } else { writer.WriteLine("CResourceString m_String = \"{0}\"", Value); } writer.Indent--; writer.WriteLine("}"); }
void Write(IndentedTextWriter writer, GmlFormatter formatter, bool semicolon, bool curlyBraces) { Sequence seq; if (curlyBraces) { writer.WriteLine("{"); writer.Indent++; } if (First.Kind == StatementKind.Sequence) { // Write the sequence without curly braces. seq = (Sequence)First; seq.Write(writer, formatter, semicolon, false); } else First.Write(writer, formatter); if (Second.Kind == StatementKind.Sequence) { // Write the sequence without curly braces. seq = (Sequence)Second; seq.Write(writer, formatter, semicolon, false); } else Second.Write(writer, formatter); if (curlyBraces) { writer.Indent--; writer.WriteLine("}"); } }
public void Dump(IndentedTextWriter w) { w.Write("Line ["); w.Write("dx: " + this.DeltaX + ", "); w.Write("dy: " + this.DeltaY); w.Write("]"); }
public void WriteText(IndentedTextWriter writer) { writer.WriteLine(); writer.WriteLine("{0:F4} {1:F4} {2:F4} {3:F4}", field0, field1, field2, field3); writer.WriteLine("{0:F4} {1:F4} {2:F4} {3:F4}", field4, field5, field6, field7); writer.WriteLine("{0:F4} {1:F4} {2:F4} {3:F4}", field8, field9, field10, field11); }
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; }
//=========================================================================================== protected override void WriteSet(IndentedTextWriter writer, PropertyInfo property) { writer.Write("image->"); writer.Write(property.Name); writer.Write(" = "); WriteGetValue(writer, property); }
//=========================================================================================== private void WriteExceptions(IndentedTextWriter writer) { foreach (Type type in _Exceptions) { if (type.IsSealed) writer.Write("public sealed class "); else writer.Write("public class "); WriteType(writer, type); writer.Write(" : "); WriteType(writer, type.BaseType); WriteStartColon(writer); writer.Write("internal "); WriteType(writer, type); writer.WriteLine("(Exception exception)"); writer.Indent++; writer.Write(": base("); if (type.BaseType == typeof(Exception)) writer.Write("exception.Message, "); writer.WriteLine("exception)"); writer.Indent--; WriteStartColon(writer); WriteEndColon(writer); WriteEndColon(writer); } }
//=========================================================================================== private void WriteHelper(IndentedTextWriter writer) { writer.WriteLine("public static class ExceptionHelper"); WriteStartColon(writer); writer.WriteLine("public static Exception Create(Exception exception)"); WriteStartColon(writer); writer.WriteLine("if (ReferenceEquals(exception, null))"); writer.Indent++; writer.WriteLine("return null;"); writer.Indent--; writer.WriteLine("switch(exception.GetType().Name)"); WriteStartColon(writer); foreach (Type exception in _Exceptions) { writer.Write("case \""); writer.Write(exception.Name); writer.WriteLine("\":"); writer.Indent++; writer.Write("return new "); writer.Write(exception.Name); writer.WriteLine("(exception);"); writer.Indent--; } writer.WriteLine("default:"); writer.Indent++; writer.WriteLine("return exception;"); writer.Indent--; WriteEndColon(writer); WriteEndColon(writer); WriteEndColon(writer); }
public override void AppendDDL(IndentedTextWriter textWriter) { if (Note.Length > 0) { textWriter.WriteLine("/*"); textWriter.Write(" "); textWriter.WriteLine(Note); textWriter.WriteLine("*/"); } textWriter.WriteLine($"IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'{ObjectIdentifier}'))"); textWriter.WriteLine($"CREATE TABLE {ObjectIdentifier} ("); textWriter.Indent++; foreach (var column in Columns) { column.AppendDDL(textWriter, includeConstraints: true); textWriter.WriteLine(","); } foreach (var constraint in Constraints) { constraint.AppendDDL(textWriter); textWriter.WriteLine(","); } textWriter.Indent--; textWriter.WriteLine(");"); textWriter.WriteLine("GO"); }
protected override void WriteCase(IndentedTextWriter writer, string name) { writer.Write("return Create"); writer.Write(name[0].ToString().ToUpperInvariant()); writer.Write(name.Substring(1)); writer.WriteLine("(element);"); }
private void WriteFileTrailer(IndentedTextWriter writer) { writer.Indent -= 2; while (!template.EndOfStream) writer.WriteLine(template.ReadLine()); }
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(); } } }
internal Indentation(IndentedTextWriter writer, int indent) { this.writer = writer; this.indent = indent; s = null; }
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(); }
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(); } } }