本文整理汇总了C#中Microsoft.CSharp.CSharpCodeProvider.GenerateCodeFromMember方法的典型用法代码示例。如果您正苦于以下问题:C# CSharpCodeProvider.GenerateCodeFromMember方法的具体用法?C# CSharpCodeProvider.GenerateCodeFromMember怎么用?C# CSharpCodeProvider.GenerateCodeFromMember使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CSharp.CSharpCodeProvider
的用法示例。
在下文中一共展示了CSharpCodeProvider.GenerateCodeFromMember方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: PostProcessGeneratedCodeAddsApplicationInstanceProperty
public void PostProcessGeneratedCodeAddsApplicationInstanceProperty() {
const string expectedPropertyCode = @"
protected Foo.Bar ApplicationInstance {
get {
return ((Foo.Bar)(Context.ApplicationInstance));
}
}
";
// Arrange
CodeCompileUnit generatedCode = new CodeCompileUnit();
CodeNamespace generatedNamespace = new CodeNamespace();
CodeTypeDeclaration generatedClass = new CodeTypeDeclaration();
CodeMemberMethod executeMethod = new CodeMemberMethod();
WebPageRazorHost host = new WebPageRazorHost("Foo.cshtml") {
GlobalAsaxTypeName = "Foo.Bar"
};
// Act
host.PostProcessGeneratedCode(generatedCode, generatedNamespace, generatedClass, executeMethod);
// Assert
CodeMemberProperty property = generatedClass.Members[0] as CodeMemberProperty;
Assert.IsNotNull(property);
CSharpCodeProvider provider = new CSharpCodeProvider();
StringBuilder builder = new StringBuilder();
using(StringWriter writer = new StringWriter(builder)) {
provider.GenerateCodeFromMember(property, writer, new CodeDom.Compiler.CodeGeneratorOptions());
}
Assert.AreEqual(expectedPropertyCode, builder.ToString());
}
示例2: CreateStaticDataType
public static string CreateStaticDataType(Guid dataTypeId)
{
DataTypeDescriptor dataTypeDescriptor;
DynamicTypeManager.TryGetDataTypeDescriptor(dataTypeId, out dataTypeDescriptor);
var codeTypeDeclaration = Reflection.CallStaticMethod<CodeTypeDeclaration>("Composite.Data.GeneratedTypes.InterfaceCodeGenerator", "CreateCodeTypeDeclaration", dataTypeDescriptor);
var csCompiler = new CSharpCodeProvider();
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
{
csCompiler.GenerateCodeFromMember(codeTypeDeclaration, sw, new CodeGeneratorOptions());
}
return sb.ToString();
}
示例3: Compile
/// <summary>
/// Compile the parse tree to CSharp.
/// </summary>
/// <returns></returns>
private string Compile()
{
// this.buf = ['var interp'];
_buf = new CodeEntryPointMethod();
if (_pp)
// _buf.Push("/* var __indent = []; */");
_buf.Statements.Add(new CodeVariableDeclarationStatement("string[]", "__indent"));
_lastBufferedIdx = 1;
Visit(_node);
var gen = new CSharpCodeProvider();
var writer = new StringWriter();
gen.GenerateCodeFromMember(_buf, writer, null);
return writer.ToString();
}
示例4: GenerateCode
private void GenerateCode()
{
keys.ToObservable();
var cgo = new CodeGeneratorOptions
{
BracingStyle = "C",
BlankLinesBetweenMembers = false
};
using (var provider = new CSharpCodeProvider())
{
var method = new CodeMemberMethod
{
Name = "KeyStream",
ReturnType = new CodeTypeReference(typeof(IObservable<InterceptKeyEventArgs>))
};
var player =
new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(KeyPlayer)), "keys",
new CodeObjectCreateExpression(typeof(KeyPlayer)));
method.Statements.Add(player);
foreach (var interceptKeyEventArgse in keys)
{
var key = new CodeObjectCreateExpression(new CodeTypeReference(typeof(InterceptKeyEventArgs)),
new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(Keys)), interceptKeyEventArgse.Key.ToString()),
new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(KeyDirection)), interceptKeyEventArgse.KeyDirection.ToString()),
new CodePrimitiveExpression(interceptKeyEventArgse.AltPressed),
new CodePrimitiveExpression(interceptKeyEventArgse.ControlPressed),
new CodePrimitiveExpression(interceptKeyEventArgse.ShiftPressed));
var keyPress = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("keys"), "Add", key);
method.Statements.Add(keyPress);
}
method.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("keys")));
var sb = new StringBuilder();
using(var stringWriter = new StringWriter(sb))
{
provider.GenerateCodeFromMember(method, stringWriter, cgo);
}
textBox.Text = sb.ToString();
}
}
示例5: GenerateCode
public static string GenerateCode(CodeObject codeObj)
{
var provider = new CSharpCodeProvider();
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
{
if (codeObj is CodeCompileUnit)
{
provider.GenerateCodeFromCompileUnit(codeObj as CodeCompileUnit, writer, null);
}
else if (codeObj is CodeExpression)
{
provider.GenerateCodeFromExpression(codeObj as CodeExpression, writer, null);
}
else if (codeObj is CodeStatement)
{
provider.GenerateCodeFromStatement(codeObj as CodeStatement, writer, null);
}
else if (codeObj is CodeTypeMember)
{
provider.GenerateCodeFromMember(codeObj as CodeTypeMember, writer, null);
}
else if (codeObj is CodeNamespace)
{
provider.GenerateCodeFromNamespace(codeObj as CodeNamespace, writer, null);
}
else
{
throw new InvalidOperationException();
}
writer.Flush();
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
示例6: 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
}
}
示例7: GenerateField
string GenerateField(CodeMemberField newField)
{
StringWriter writer = new StringWriter();
var provider = new CSharpCodeProvider();
provider.GenerateCodeFromMember(newField, writer, new CodeGeneratorOptions());
return writer.ToString().Trim();
}
示例8: CompileToString
private string CompileToString(CodeMemberMethod method)
{
var codeProvider = new CSharpCodeProvider();
using (var stringWriter = new StringWriter())
{
using (var indentedTextWriter = new IndentedTextWriter(stringWriter))
{
var options = new CodeGeneratorOptions();
options.BracingStyle = "C";
codeProvider.GenerateCodeFromMember(method, indentedTextWriter, options);
}
var builder = stringWriter.GetStringBuilder();
return SanitizeCodeForComparison(builder.ToString());
}
}
示例9: GenerateCSharpTo
/// <summary>
/// Generates CSharp text from a type member and writes it to a text writer with the given options.
/// </summary>
/// <param name="typeMember">The expression 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 CodeTypeMember typeMember, TextWriter writer, CodeGeneratorOptions options)
{
using (var provider = new CSharpCodeProvider())
{
provider.GenerateCodeFromMember(typeMember, writer, options);
}
}
示例10: CheckAgainsAppCode
private static CompatibilityCheckResult CheckAgainsAppCode(DataTypeDescriptor dataTypeDescriptorToTest, bool includeDataTypeDescriptor)
{
List<string> filesToCompile = GetAppCodeFiles().ToList();
if (filesToCompile.Count == 0) return new CompatibilityCheckResult();
CSharpCodeProvider csCompiler = new CSharpCodeProvider();
List<Assembly> referencedAssemblies = new List<Assembly>();
Dictionary<string, List<CodeTypeDeclaration>> codeTypeDeclarations = new Dictionary<string, List<CodeTypeDeclaration>>();
foreach (DataTypeDescriptor dataTypeDescriptor in DataMetaDataFacade.GeneratedTypeDataTypeDescriptors)
{
if (!includeDataTypeDescriptor && (dataTypeDescriptor.DataTypeId == dataTypeDescriptorToTest.DataTypeId)) continue;
DataTypeDescriptor dataTypeDescriptorToUse = dataTypeDescriptor;
if (includeDataTypeDescriptor && (dataTypeDescriptor.DataTypeId == dataTypeDescriptorToTest.DataTypeId)) dataTypeDescriptorToUse = dataTypeDescriptorToTest;
referencedAssemblies.AddRange(InterfaceCodeGenerator.GetReferencedAssemblies(dataTypeDescriptorToUse));
CodeTypeDeclaration codeTypeDeclaration = InterfaceCodeGenerator.CreateCodeTypeDeclaration(dataTypeDescriptorToUse);
List<CodeTypeDeclaration> declarations;
if (!codeTypeDeclarations.TryGetValue(dataTypeDescriptorToUse.Namespace, out declarations))
{
declarations = new List<CodeTypeDeclaration>();
codeTypeDeclarations.Add(dataTypeDescriptorToUse.Namespace, declarations);
}
declarations.Add(codeTypeDeclaration);
string tempFilePath = GetTempFileName(dataTypeDescriptorToUse);
filesToCompile.Add(tempFilePath);
using (FileStream file = File.Create(tempFilePath))
{
using (var sw = new StreamWriter(file))
{
CodeNamespace codeNamespace = new CodeNamespace(dataTypeDescriptorToUse.Namespace);
codeNamespace.Types.Add(codeTypeDeclaration);
csCompiler.GenerateCodeFromNamespace(codeNamespace, sw, new CodeGeneratorOptions());
}
StringBuilder sb = new StringBuilder();
using (var sw = new StringWriter(sb))
{
csCompiler.GenerateCodeFromMember(codeTypeDeclaration, sw, new CodeGeneratorOptions());
}
}
}
filesToCompile.Sort();
CompilerParameters compilerParameters = new CompilerParameters();
compilerParameters.GenerateExecutable = false;
compilerParameters.GenerateInMemory = true;
compilerParameters.ReferencedAssemblies.AddRangeIfNotContained(referencedAssemblies.Select(f => f.Location).ToArray());
compilerParameters.ReferencedAssemblies.AddRangeIfNotContained(CodeGenerationManager.CompiledAssemblies.Select(f => f.Location).ToArray());
compilerParameters.AddAssemblyLocationsFromBin();
compilerParameters.AddLoadedAssemblies(false);
compilerParameters.AddCommonAssemblies();
compilerParameters.RemoveGeneratedAssemblies();
CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
foreach (var kvp in codeTypeDeclarations)
{
CodeNamespace codeNamespace = new CodeNamespace(kvp.Key);
codeNamespace.Types.AddRange(kvp.Value.ToArray());
codeCompileUnit.Namespaces.Add(codeNamespace);
}
CSharpCodeProvider compiler = new CSharpCodeProvider();
CompilerResults compileResult = compiler.CompileAssemblyFromFile(compilerParameters, filesToCompile.ToArray());
if (compileResult.Errors.Count == 0) return new CompatibilityCheckResult();
// Checking for a missing assembly error, if it is present, that means that App_Code check isn't applicable due to circular reference
foreach (CompilerError error in compileResult.Errors)
{
if (error.ErrorNumber == "CS0012" && error.ErrorText.Contains("Composite.Generated"))
{
return new CompatibilityCheckResult();
}
}
return new CompatibilityCheckResult(compileResult);
}
示例11: PostProcessGeneratedCodeAddsApplicationInstanceProperty
public void PostProcessGeneratedCodeAddsApplicationInstanceProperty()
{
const string expectedPropertyCode = @"
protected Foo.Bar ApplicationInstance {
get {
return ((Foo.Bar)(Context.ApplicationInstance));
}
}
";
// Arrange
WebPageRazorHost host = new WebPageRazorHost("Foo.cshtml")
{
GlobalAsaxTypeName = "Foo.Bar"
};
CodeGeneratorContext context = CodeGeneratorContext.Create(
host,
() => new CSharpCodeWriter(),
"TestClass",
"TestNs",
"TestFile.cshtml",
shouldGenerateLinePragmas: true);
// Act
host.PostProcessGeneratedCode(context);
// Assert
CodeMemberProperty property = context.GeneratedClass.Members[0] as CodeMemberProperty;
Assert.NotNull(property);
CSharpCodeProvider provider = new CSharpCodeProvider();
StringBuilder builder = new StringBuilder();
using (StringWriter writer = new StringWriter(builder))
{
provider.GenerateCodeFromMember(property, writer, new CodeGeneratorOptions());
}
Assert.Equal(expectedPropertyCode, builder.ToString());
}
示例12: GenerateCode
public void GenerateCode(CodeDomGenerator.Language language)
{
switch (language)
{
case CodeDomGenerator.Language.CSharp:
using (CSharpCodeProvider provider = new CSharpCodeProvider())
{
CodeGeneratorOptions opts = new CodeGeneratorOptions();
StringBuilder sb = new StringBuilder();
using (IndentedTextWriter tw = new IndentedTextWriter(new StringWriter(sb), opts.IndentString))
{
provider.GenerateCodeFromMember(Event, tw, opts);
sb.Replace(";",string.Empty);
tw.WriteLine("{");
tw.Indent++;
GenrateMeth(opts, provider, tw, AddMethod.GetStatements, "add");
GenrateMeth(opts, provider, tw, RemoveMethod.GetStatements, "remove");
tw.Indent--;
tw.WriteLine("}");
}
Text = sb.ToString();
}
break;
case CodeDomGenerator.Language.VB:
using (Microsoft.VisualBasic.VBCodeProvider provider = new Microsoft.VisualBasic.VBCodeProvider())
{
CodeGeneratorOptions opts = new CodeGeneratorOptions();
var args = new StringWriter();
provider.GenerateCodeFromExpression(new CodeParameterDeclarationExpression(Event.Type, "value"), args, opts);
StringBuilder sb = new StringBuilder();
using (IndentedTextWriter tw = new IndentedTextWriter(new StringWriter(sb), opts.IndentString))
{
provider.GenerateCodeFromMember(Event, tw, opts);
sb.Replace(" Event ", " Custom Event ");
tw.Indent++;
tw.WriteLine("AddHandler({0})", args.GetStringBuilder());
tw.Indent++;
foreach (CodeStatement statement in AddMethod.GetStatements)
{
provider.GenerateCodeFromStatement(statement, tw, opts);
}
tw.Indent--;
tw.WriteLine("End AddHandler");
tw.WriteLine("RemoveHandler({0})", args.GetStringBuilder());
tw.Indent++;
foreach (CodeStatement statement in RemoveMethod.GetStatements)
{
provider.GenerateCodeFromStatement(statement, tw, opts);
}
tw.Indent--;
tw.WriteLine("End RemoveHandler");
//args = new StringWriter();
//provider.GenerateCodeFromMember(RaiseMethod, args, opts);
//StringReader sr = new StringReader(args.GetStringBuilder().ToString());
//string line = sr.ReadLine();
//while (string.IsNullOrEmpty(line))
// line = sr.ReadLine();
//int idx = line.IndexOf(" " + RaiseMethod.Name);
//args.GetStringBuilder().Replace(line, "RaiseEvent" + line.Substring(idx + RaiseMethod.Name.Length + 1));
//tw.Write(args.GetStringBuilder().ToString());
tw.Write("RaiseEvent(");
for (int i = 0; i < RaiseMethod.Parameters.Count;i++)
{
if (i > 0)
tw.Write(", ");
provider.GenerateCodeFromExpression(RaiseMethod.Parameters[i], tw, opts);
}
tw.WriteLine(")");
tw.Indent++;
foreach (CodeStatement statement in RaiseMethod.Statements)
{
provider.GenerateCodeFromStatement(statement, tw, opts);
}
tw.Indent--;
tw.WriteLine("End RaiseEvent");
tw.Indent--;
tw.WriteLine("End Event");
}
Text = sb.ToString();
}
break;
default:
throw new NotImplementedException(language.ToString());
}
}
示例13: GenerateCode
private static string GenerateCode(CodeTypeMember cmm)
{
StringBuilder sb;
using (var csp = new CSharpCodeProvider())
{
sb = new StringBuilder();
using (var sw = new StringWriter(sb, CultureInfo.CurrentCulture))
{
var options = new CodeGeneratorOptions();
csp.GenerateCodeFromMember(cmm, sw, options);
}
}
var decl = sb.ToString().Trim();
decl = CleanupDeclarationString(decl);
return decl;
}
示例14: CanCreateActiveRecordFromTable
public void CanCreateActiveRecordFromTable()
{
CodeMemberMethod method = new CodeMemberMethod();
method.Name = "Find";
method.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
method.ReturnType = new CodeTypeReference("UserProfile");
method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "id"));
method.Statements.Add(new CodeVariableDeclarationStatement(typeof(bool), "doNotThrowExceptionIfNotFound", new CodeSnippetExpression("false")));
method.Statements.Add(
new CodeMethodReturnStatement(
new CodeMethodInvokeExpression(null, "FindByPrimaryKey", new CodeExpression[] { new CodeArgumentReferenceExpression("id"), new CodeVariableReferenceExpression("doNotThrowExceptionIfNotFound") })));
CodeDomProvider provider = new CSharpCodeProvider();
provider.GenerateCodeFromMember(method, Console.Out, new CodeGeneratorOptions());
}