本文整理汇总了C#中Microsoft.CSharp.CSharpCodeProvider.CreateGenerator方法的典型用法代码示例。如果您正苦于以下问题:C# CSharpCodeProvider.CreateGenerator方法的具体用法?C# CSharpCodeProvider.CreateGenerator怎么用?C# CSharpCodeProvider.CreateGenerator使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CSharp.CSharpCodeProvider
的用法示例。
在下文中一共展示了CSharpCodeProvider.CreateGenerator方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateGenerator_ReturnsSame
public void CreateGenerator_ReturnsSame()
{
CSharpCodeProvider provider = new CSharpCodeProvider();
#pragma warning disable 0618
Assert.Same(provider.CreateGenerator(), provider.CreateGenerator());
#pragma warning restore 0618
}
示例2: Ctor_IDictionaryStringString
public void Ctor_IDictionaryStringString(IDictionary<string, string> providerOptions)
{
CSharpCodeProvider provider = new CSharpCodeProvider();
#pragma warning disable 0618
Assert.NotNull(provider.CreateGenerator());
Assert.Same(provider.CreateGenerator(), provider.CreateCompiler());
#pragma warning restore 0618
}
示例3: Ctor_Default
public void Ctor_Default()
{
CSharpCodeProvider provider = new CSharpCodeProvider();
#pragma warning disable 0618
Assert.NotNull(provider.CreateGenerator());
Assert.Same(provider.CreateGenerator(), provider.CreateCompiler());
#pragma warning restore 0618
}
示例4: SetUp
public override void SetUp ()
{
base.SetUp ();
_typeDeclaration = new CodeTypeDeclaration ();
CodeDomProvider provider = new CSharpCodeProvider ();
_codeGenerator = provider.CreateGenerator ();
}
示例5: Generate
public virtual string Generate(Window window)
{
window.ReInitialize(InitializeOption.WithCache);
var stringBuilder = new StringBuilder();
var stringWriter = new StringWriter(stringBuilder);
var cscProvider = new CSharpCodeProvider();
ICodeGenerator codeGenerator = cscProvider.CreateGenerator(stringWriter);
var codeGeneratorOptions = new CodeGeneratorOptions {BlankLinesBetweenMembers = false, VerbatimOrder = false};
codeGenerator.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit(string.Format("using {0};", typeof(UIItem).Namespace)), stringWriter, codeGeneratorOptions);
codeGenerator.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit(string.Format("using {0};", typeof(Window).Namespace)), stringWriter, codeGeneratorOptions);
codeGenerator.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit(string.Format("using {0};", typeof(AppScreen).Namespace)), stringWriter, codeGeneratorOptions);
CodeNamespace codeNamespace = null;
if (S.IsNotEmpty(options.Namespace))
{
codeNamespace = new CodeNamespace(options.Namespace);
}
var classDefinition = new CodeTypeDeclaration
{
IsClass = true,
IsPartial = true,
Name = window.Title.Trim().Replace(" ", string.Empty),
TypeAttributes = TypeAttributes.Public
};
classDefinition.BaseTypes.Add(typeof (AppScreen));
var constructor = new CodeConstructor {Attributes = MemberAttributes.Family};
classDefinition.Members.Add(constructor);
constructor = new CodeConstructor {Attributes = MemberAttributes.Public};
constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Window), "window"));
constructor.Parameters.Add(new CodeParameterDeclarationExpression(typeof (ScreenRepository), "screenRepository"));
constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("window"));
constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("screenRepository"));
classDefinition.Members.Add(constructor);
var visitor = new CodeGenerationVisitor(new WindowCodeGenerationStrategy(options));
window.Visit(visitor);
visitor.Generate(classDefinition);
if (codeNamespace != null)
{
codeNamespace.Types.Add(classDefinition);
codeGenerator.GenerateCodeFromNamespace(codeNamespace, stringWriter, codeGeneratorOptions);
}
else
{
codeGenerator.GenerateCodeFromType(classDefinition, stringWriter, codeGeneratorOptions);
}
stringWriter.Close();
return stringBuilder.ToString();
}
示例6: BuildClass
/// <summary>
/// Main driving routine for building a class
/// </summary>
void BuildClass(string expression)
{
// need a string to put the code into
_source = new StringBuilder();
StringWriter sw = new StringWriter(_source);
//Declare your provider and generator
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeGenerator generator = codeProvider.CreateGenerator(sw);
CodeGeneratorOptions codeOpts = new CodeGeneratorOptions();
CodeNamespace myNamespace = new CodeNamespace("ExpressionEvaluator");
myNamespace.Imports.Add(new CodeNamespaceImport("System"));
myNamespace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
//Build the class declaration and member variables
CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration();
classDeclaration.IsClass = true;
classDeclaration.Name = "Calculator";
classDeclaration.Attributes = MemberAttributes.Public;
classDeclaration.Members.Add(FieldVariable("answer", typeof(string), MemberAttributes.Private));
//default constructor
CodeConstructor defaultConstructor = new CodeConstructor();
defaultConstructor.Attributes = MemberAttributes.Public;
defaultConstructor.Comments.Add(new CodeCommentStatement("Default Constructor for class", true));
defaultConstructor.Statements.Add(new CodeSnippetStatement("//TODO: implement default constructor"));
classDeclaration.Members.Add(defaultConstructor);
//property
classDeclaration.Members.Add(this.MakeProperty("Answer", "answer", typeof(string)));
//Our Calculate Method
CodeMemberMethod myMethod = new CodeMemberMethod();
myMethod.Name = "Calculate";
myMethod.ReturnType = new CodeTypeReference(typeof(string));
myMethod.Comments.Add(new CodeCommentStatement("Calculate an expression", true));
myMethod.Attributes = MemberAttributes.Public;
myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("Object obj"), new CodeSnippetExpression(expression)));
myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("Answer"), new CodeSnippetExpression("obj.ToString()")));
myMethod.Statements.Add(
new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Answer")));
classDeclaration.Members.Add(myMethod);
//write code
myNamespace.Types.Add(classDeclaration);
generator.GenerateCodeFromNamespace(myNamespace, sw, codeOpts);
sw.Flush();
sw.Close();
}
示例7: CreateAssemblyFromDataTable
public static System.Reflection.Assembly CreateAssemblyFromDataTable(DataTable DataValues)
{
System.Random rnd = new Random();
if(DataValues.TableName == null || DataValues.TableName == "") DataValues.TableName = rnd.Next().ToString();
object result = null;
CodeTypeDeclaration classDec = new CodeTypeDeclaration(DataValues.TableName);
classDec.IsClass = true;
CodeConstructor constructor = new CodeConstructor();
constructor.Attributes = MemberAttributes.Public;
classDec.Members.Add(classDec);
foreach(System.Data.DataColumn col in DataValues.Columns)
{
AddPropertyAndField(classDec, col.DataType, "", col.ColumnName);
}
AddPropertyAndField(classDec, null, "System.Collections.Generic.List<" + DataValues.TableName + ">", "ListOf" + DataValues.TableName);
using(CSharpCodeProvider provider = new CSharpCodeProvider())
{
ICodeGenerator generator = provider.CreateGenerator();
CodeNamespace ns = new CodeNamespace("Terminals.Generated");
ns.Types.Add((CodeTypeDeclaration)classDec);
CodeGeneratorOptions options = new CodeGeneratorOptions();
//options.BlankLinesBetweenMembers = true;
string filename = System.IO.Path.GetTempFileName();
using(System.IO.StreamWriter sw = new System.IO.StreamWriter(filename, false))
{
generator.GenerateCodeFromNamespace(ns, sw, options);
ICodeCompiler icc = provider.CreateCompiler();
CompilerParameters compileParams = new CompilerParameters();
compileParams.GenerateExecutable = false;
compileParams.GenerateInMemory = true;
return icc.CompileAssemblyFromSource(compileParams, System.IO.File.ReadAllText(filename)).CompiledAssembly;
}
}
return null;
}
示例8: XsdGen
/// <summary>
/// Constructor for the XsdGen class.
/// </summary>
/// <param name="args">Command-line arguments passed to the program.</param>
private XsdGen(string[] args)
{
this.ParseCommandlineArgs(args);
// show usage information
if (this.showHelp)
{
Console.WriteLine("usage: XsdGen.exe <schema>.xsd <outputFile> <namespace>");
return;
}
// ensure that the schema file exists
if (!File.Exists(this.xsdFile))
{
throw new ApplicationException(String.Format("Schema file does not exist: '{0}'.", this.xsdFile));
}
XmlSchema document = null;
using (StreamReader xsdFileReader = new StreamReader(this.xsdFile))
{
document = XmlSchema.Read(xsdFileReader, new ValidationEventHandler(this.ValidationHandler));
}
CodeCompileUnit codeCompileUnit = StronglyTypedClasses.Generate(document, this.outputNamespace);
using (CSharpCodeProvider codeProvider = new CSharpCodeProvider())
{
ICodeGenerator generator = codeProvider.CreateGenerator();
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BlankLinesBetweenMembers = true;
options.BracingStyle = "C";
options.IndentString = " ";
using (StreamWriter csFileWriter = new StreamWriter(this.outFile))
{
generator.GenerateCodeFromCompileUnit(codeCompileUnit, csFileWriter, options);
}
}
}
示例9: Deny_Unrestricted
public void Deny_Unrestricted ()
{
CSharpCodeProvider csprov = new CSharpCodeProvider ();
Assert.AreEqual ("cs", csprov.FileExtension, "FileExtension");
Assert.IsNotNull (csprov.CreateCompiler (), "CreateCompiler");
Assert.IsNotNull (csprov.CreateGenerator (), "CreateGenerator");
try {
Assert.IsNotNull (csprov.GetConverter (typeof (string)), "GetConverter");
}
catch (NotImplementedException) {
// mono
}
CodeTypeMember ctm = new CodeTypeMember ();
StringWriter sw = new StringWriter ();
CodeGeneratorOptions cgo = new CodeGeneratorOptions ();
try {
csprov.GenerateCodeFromMember (ctm, sw, cgo);
}
catch (NotImplementedException) {
// mono
}
}
示例10: ExportTypeMapping_Field
[Category ("NotWorking")] // TODO: order of DefaultValueAttribute, ...
public void ExportTypeMapping_Field ()
{
CodeNamespace codeNamespace = ExportCode (typeof (Field));
Assert.IsNotNull (codeNamespace, "#1");
StringWriter sw = new StringWriter ();
CodeDomProvider provider = new CSharpCodeProvider ();
ICodeGenerator generator = provider.CreateGenerator ();
generator.GenerateCodeFromNamespace (codeNamespace, sw, new CodeGeneratorOptions ());
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}{0}" +
"/// <remarks/>{0}" +
"[System.CodeDom.Compiler.GeneratedCodeAttribute(\"nunit-lite-console\", \"0.0.0.0\")]{0}" +
"[System.SerializableAttribute()]{0}" +
"[System.Diagnostics.DebuggerStepThroughAttribute()]{0}" +
"[System.ComponentModel.DesignerCategoryAttribute(\"code\")]{0}" +
"[System.Xml.Serialization.XmlRootAttribute(\"field\", Namespace=\"\", IsNullable=true)]{0}" +
"public partial class Field {{{0}" +
" {0}" +
" private MonoTests.System.Xml.TestClasses.FlagEnum flags1Field;{0}" +
" {0}" +
" private MonoTests.System.Xml.TestClasses.FlagEnum flags2Field;{0}" +
" {0}" +
" private MonoTests.System.Xml.TestClasses.FlagEnum flags3Field;{0}" +
" {0}" +
" private MonoTests.System.Xml.TestClasses.FlagEnum flags4Field;{0}" +
" {0}" +
" private MonoTests.System.Xml.TestClasses.MapModifiers modifiersField;{0}" +
" {0}" +
" private MonoTests.System.Xml.TestClasses.MapModifiers modifiers2Field;{0}" +
" {0}" +
" private MonoTests.System.Xml.TestClasses.MapModifiers modifiers3Field;{0}" +
" {0}" +
" private MonoTests.System.Xml.TestClasses.MapModifiers modifiers4Field;{0}" +
" {0}" +
" private MonoTests.System.Xml.TestClasses.MapModifiers modifiers5Field;{0}" +
" {0}" +
" private string[] namesField;{0}" +
" {0}" +
" private string streetField;{0}" +
" {0}" +
" public Field() {{{0}" +
" this.flags1Field = MonoTests.System.Xml.TestClasses.FlagEnum.e1;{0}" +
" this.flags2Field = MonoTests.System.Xml.TestClasses.FlagEnum.e1;{0}" +
" this.flags3Field = (MonoTests.System.Xml.TestClasses.FlagEnum.e1 | MonoTests.System.Xml.TestClasses.FlagEnum.e2);{0}" +
" this.modifiers3Field = MonoTests.System.Xml.TestClasses.MapModifiers.Public;{0}" +
" this.modifiers4Field = MonoTests.System.Xml.TestClasses.MapModifiers.Protected;{0}" +
" this.modifiers5Field = MonoTests.System.Xml.TestClasses.MapModifiers.Public;{0}" +
" }}{0}" +
" {0}" +
" /// <remarks/>{0}" +
" [System.Xml.Serialization.XmlAttributeAttribute(\"flag1\")]{0}" +
" public MonoTests.System.Xml.TestClasses.FlagEnum Flags1 {{{0}" +
" get {{{0}" +
" return this.flags1Field;{0}" +
" }}{0}" +
" set {{{0}" +
" this.flags1Field = value;{0}" +
" }}{0}" +
" }}{0}" +
" {0}" +
" /// <remarks/>{0}" +
" [System.Xml.Serialization.XmlAttributeAttribute(\"flag2\")]{0}" +
" public MonoTests.System.Xml.TestClasses.FlagEnum Flags2 {{{0}" +
" get {{{0}" +
" return this.flags2Field;{0}" +
" }}{0}" +
" set {{{0}" +
" this.flags2Field = value;{0}" +
" }}{0}" +
" }}{0}" +
" {0}" +
" /// <remarks/>{0}" +
" [System.Xml.Serialization.XmlAttributeAttribute(\"flag3\", Form=System.Xml.Schema.XmlSchemaForm.Qualified)]{0}" +
" public MonoTests.System.Xml.TestClasses.FlagEnum Flags3 {{{0}" +
" get {{{0}" +
" return this.flags3Field;{0}" +
" }}{0}" +
" set {{{0}" +
" this.flags3Field = value;{0}" +
" }}{0}" +
" }}{0}" +
" {0}" +
" /// <remarks/>{0}" +
" [System.Xml.Serialization.XmlAttributeAttribute(\"flag4\")]{0}" +
" public MonoTests.System.Xml.TestClasses.FlagEnum Flags4 {{{0}" +
" get {{{0}" +
" return this.flags4Field;{0}" +
" }}{0}" +
" set {{{0}" +
" this.flags4Field = value;{0}" +
" }}{0}" +
" }}{0}" +
" {0}" +
" /// <remarks/>{0}" +
" [System.Xml.Serialization.XmlAttributeAttribute(\"modifiers\")]{0}" +
" public MonoTests.System.Xml.TestClasses.MapModifiers Modifiers {{{0}" +
" get {{{0}" +
//.........这里部分代码省略.........
示例11: ExportTypeMapping_ItemChoiceType
public void ExportTypeMapping_ItemChoiceType ()
{
CodeNamespace codeNamespace = ExportCode (typeof (ItemChoiceType));
Assert.IsNotNull (codeNamespace, "#1");
StringWriter sw = new StringWriter ();
CodeDomProvider provider = new CSharpCodeProvider ();
ICodeGenerator generator = provider.CreateGenerator ();
generator.GenerateCodeFromNamespace (codeNamespace, sw, new CodeGeneratorOptions ());
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}{0}" +
"/// <remarks/>{0}" +
"[System.CodeDom.Compiler.GeneratedCodeAttribute(\"nunit-lite-console\", \"0.0.0.0\")]{0}" +
"[System.SerializableAttribute()]{0}" +
"[System.Xml.Serialization.XmlTypeAttribute(IncludeInSchema=false)]{0}" +
"[System.Xml.Serialization.XmlRootAttribute(Namespace=\"\", IsNullable=false)]{0}" +
"public enum ItemChoiceType {{{0}" +
" {0}" +
" /// <remarks/>{0}" +
" ChoiceZero,{0}" +
" {0}" +
" /// <remarks/>{0}" +
" [System.Xml.Serialization.XmlEnumAttribute(\"ChoiceOne\")]{0}" +
" StrangeOne,{0}" +
" {0}" +
" /// <remarks/>{0}" +
" ChoiceTwo,{0}" +
"}}{0}", Environment.NewLine), sw.ToString (), "#2");
codeNamespace = ExportCode (typeof (ItemChoiceType[]));
Assert.IsNotNull (codeNamespace, "#3");
sw.GetStringBuilder ().Length = 0;
generator.GenerateCodeFromNamespace (codeNamespace, sw, new CodeGeneratorOptions ());
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}{0}" +
"/// <remarks/>{0}" +
"[System.CodeDom.Compiler.GeneratedCodeAttribute(\"nunit-lite-console\", \"0.0.0.0\")]{0}" +
"[System.SerializableAttribute()]{0}" +
"[System.Xml.Serialization.XmlTypeAttribute(IncludeInSchema=false)]{0}" +
"public enum ItemChoiceType {{{0}" +
" {0}" +
" /// <remarks/>{0}" +
" ChoiceZero,{0}" +
" {0}" +
" /// <remarks/>{0}" +
" [System.Xml.Serialization.XmlEnumAttribute(\"ChoiceOne\")]{0}" +
" StrangeOne,{0}" +
" {0}" +
" /// <remarks/>{0}" +
" ChoiceTwo,{0}" +
"}}{0}", Environment.NewLine), sw.ToString (), "#4");
}
示例12: SetUp
public void SetUp ()
{
provider = new CSharpCodeProvider ();
generator = provider.CreateGenerator ();
options = new CodeGeneratorOptions ();
}
示例13: Main
static void Main(string[] args)
{
// Prompt for target language.
Console.Write("Do you want to generate C# or VB .NET code? ");
syntaxTarget = Console.ReadLine();
// Get ICodeGenerator interface.
switch(syntaxTarget.ToUpper())
{
case "C#":
case "CSharp":
case "CS":
syntaxTarget = "cs";
CSharpCodeProvider cdp = new CSharpCodeProvider();
itfCG = cdp.CreateGenerator();
itfCC = cdp.CreateCompiler();
break;
case "VB .NET":
case "VB.NET":
case "VB":
syntaxTarget = "vb";
VBCodeProvider vbdp = new VBCodeProvider();
itfCG = vbdp.CreateGenerator();
itfCC = vbdp.CreateCompiler();
break;
default:
Console.WriteLine("Sorry...can't do it...");
syntaxTarget = null;
break;
}
// Only proceed if they picked a valid language
// supported by System.CodeDOM.
if(syntaxTarget != null)
{
// Now create the file and generate the code!
TextWriter txtWriter = CreateFile(syntaxTarget);
PopulateNamespace(itfCG, txtWriter);
txtWriter.Close();
Console.WriteLine("Done!");
// Now compile the code into a .NET DLL.
Console.WriteLine("Compiling code...");
CompileCode(itfCC, syntaxTarget);
// Now launch the application!
Console.Write("Enter your message: ");
string msg = Console.ReadLine();
LoadAndRunAsm(msg);
Console.WriteLine("Thanks for playing...");
}
}
示例14: GenerateCSharpCode
/// <summary>
/// Generate the actual C# code.
/// </summary>
/// <param name="codeCompileUnit">The code DOM.</param>
/// <param name="destClassFile">Destination C# source file.</param>
public static void GenerateCSharpCode(CodeCompileUnit codeCompileUnit, string destClassFile)
{
// generate the code with the C# code provider
CSharpCodeProvider provider = new CSharpCodeProvider();
// obtain an ICodeGenerator from the CodeDomProvider class
ICodeGenerator gen = provider.CreateGenerator();
// create a TextWriter to a StreamWriter to the output file
using (StreamWriter sw = new StreamWriter(destClassFile))
{
using (IndentedTextWriter tw = new IndentedTextWriter(sw, " "))
{
CodeGeneratorOptions options = new CodeGeneratorOptions();
// code generation options
options.BlankLinesBetweenMembers = true;
options.BracingStyle = "C";
// generate source code using the code generator
gen.GenerateCodeFromCompileUnit(codeCompileUnit, tw, options);
}
}
}
示例15: GenerateFullClass
public static String GenerateFullClass(ICollection<String> references, ICollection<String> imports, String CodeNamespace, String className, string methodBody, String method = "Method")
{
CodeCompileUnit unit = new CodeCompileUnit();
if (references != null)
{
foreach (var item in references)
{
unit.ReferencedAssemblies.Add(item);
}
}
CodeNamespace customEntityRoot = new CodeNamespace(CodeNamespace);//Create a namespace
unit.Namespaces.Add(customEntityRoot);
if (imports != null)
{
foreach (var item in imports)
{
customEntityRoot.Imports.Add(new CodeNamespaceImport(item));
}
}
CodeTypeDeclaration derived = new CodeTypeDeclaration(className);
customEntityRoot.Types.Add(derived);
CodeConstructor derivedClassConstructor = new CodeConstructor();
derivedClassConstructor.Attributes = MemberAttributes.Public;
derived.Members.Add(derivedClassConstructor);
CodeMemberMethod derivedMethod = new CodeMemberMethod();
derivedMethod.Attributes = MemberAttributes.Public ;
derivedMethod.Name = method;
derivedMethod.ReturnType = new CodeTypeReference(typeof(void));
CodeSnippetStatement code = new CodeSnippetStatement(methodBody);
derivedMethod.Statements.Add(code);
derived.Members.Add(derivedMethod);
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeGenerator codeGenerator = codeProvider.CreateGenerator();
StringBuilder generatedCode = new StringBuilder();
StringWriter codeWriter = new StringWriter(generatedCode);
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BracingStyle = "C";
codeGenerator.GenerateCodeFromCompileUnit(unit, codeWriter, options);
return generatedCode.ToString();
}