本文整理汇总了C#中System.CodeDom.CodeCompileUnit类的典型用法代码示例。如果您正苦于以下问题:C# CodeCompileUnit类的具体用法?C# CodeCompileUnit怎么用?C# CodeCompileUnit使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
CodeCompileUnit类属于System.CodeDom命名空间,在下文中一共展示了CodeCompileUnit类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GenerateCode
public static System.Reflection.Assembly GenerateCode(ITextTemplatingEngineHost host, ParsedTemplate pt,
TemplateSettings settings, CodeCompileUnit ccu)
{
CompilerParameters pars = new CompilerParameters ();
pars.GenerateExecutable = false;
if (settings.Debug) {
pars.GenerateInMemory = false;
pars.IncludeDebugInformation = true;
pars.TempFiles.KeepFiles = true;
} else {
pars.GenerateInMemory = true;
pars.IncludeDebugInformation = false;
}
//resolve and add assembly references
HashSet<string> assemblies = new HashSet<string> ();
assemblies.UnionWith (settings.Assemblies);
assemblies.UnionWith (host.StandardAssemblyReferences);
foreach (string assem in assemblies) {
string resolvedAssem = host.ResolveAssemblyReference (assem);
if (!String.IsNullOrEmpty (resolvedAssem)) {
pars.ReferencedAssemblies.Add (resolvedAssem);
} else {
pt.LogError ("Could not resolve assembly reference '" + assem + "'");
return null;
}
}
CompilerResults results = settings.Provider.CompileAssemblyFromDom (pars, ccu);
pt.Errors.AddRange (results.Errors);
if (pt.Errors.HasErrors)
return null;
return results.CompiledAssembly;
}
示例2: InvokeWebService
public static object InvokeWebService(string url, string classname, string methodname, object[] args)
{
string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
if ((classname == null) || (classname == ""))
{
classname = WebServiceProxy.GetWsClassName(url);
}
try
{
//获取WSDL
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(url + "?WSDL");
ServiceDescription sd = ServiceDescription.Read(stream);
ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
sdi.AddServiceDescription(sd, "", "");
CodeNamespace cn = new CodeNamespace(@namespace);
//生成客户端代理类代码
CodeCompileUnit ccu = new CodeCompileUnit();
ccu.Namespaces.Add(cn);
sdi.Import(cn, ccu);
CSharpCodeProvider csc = new CSharpCodeProvider();
ICodeCompiler icc = csc.CreateCompiler();
//设定编译参数
CompilerParameters cplist = new CompilerParameters();
cplist.GenerateExecutable = false;
cplist.GenerateInMemory = true;
cplist.ReferencedAssemblies.Add("System.dll");
cplist.ReferencedAssemblies.Add("System.XML.dll");
cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
cplist.ReferencedAssemblies.Add("System.Data.dll");
//编译代理类
CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
if (true == cr.Errors.HasErrors)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
{
sb.Append(ce.ToString());
sb.Append(System.Environment.NewLine);
}
throw new Exception(sb.ToString());
}
//生成代理实例,并调用方法
System.Reflection.Assembly assembly = cr.CompiledAssembly;
Type t = assembly.GetType(@namespace + "." + classname, true, true);
object obj = Activator.CreateInstance(t);
System.Reflection.MethodInfo mi = t.GetMethod(methodname);
return mi.Invoke(obj, args);
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
}
}
示例3: ProcessGeneratedCode
public override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeNamespace generatedNamespace, CodeTypeDeclaration generatedClass, CodeMemberMethod executeMethod)
{
if (!String.IsNullOrEmpty(_suffix))
{
generatedClass.Name += _suffix;
}
}
示例4: WriteGeneratedCode
internal static void WriteGeneratedCode(string sourceFile, CodeCompileUnit codeCompileUnit)
{
if (!OutputDebuggingEnabled)
{
return;
}
RunTask(() =>
{
string extension = Path.GetExtension(sourceFile);
RazorCodeLanguage language = RazorCodeLanguage.GetLanguageByExtension(extension);
CodeDomProvider provider = CodeDomProvider.CreateProvider(language.LanguageName);
using (var writer = new StringWriter())
{
// Trim the html part of cshtml or vbhtml
string outputExtension = extension.Substring(0, 3);
string outputFileName = Normalize(sourceFile) + "_generated" + outputExtension;
string outputPath = Path.Combine(Path.GetDirectoryName(sourceFile), outputFileName);
// REVIEW: Do these options need to be tweaked?
provider.GenerateCodeFromCompileUnit(codeCompileUnit, writer, new CodeGeneratorOptions());
File.WriteAllText(outputPath, writer.ToString());
}
});
}
示例5: CreateSpecs
public string CreateSpecs(out int specCount)
{
var files = FindSpecFiles().ToArray();
specCount = files.Length;
if (specCount < 1)
return string.Empty;
var compile = new CodeCompileUnit();
var globalns = new CodeNamespace();
globalns.Imports.Add(new CodeNamespaceImport("NUnit.Framework"));
globalns.Imports.Add(new CodeNamespaceImport(config.MyNamespace));
compile.Namespaces.Add(globalns);
var specNamespace = new CodeNamespace(config.TargetNamespace + ".ChutzpahSpecs");
compile.Namespaces.Add(specNamespace);
foreach (var fileInfo in files)
{
AddSpec(specNamespace, fileInfo);
}
//specNamespace.Types.AddRange(files.Select(CreateSpec).ToArray());
var provider = CreateProvider();
var options = new CodeGeneratorOptions { BracingStyle = "C", BlankLinesBetweenMembers = false };
var stringBuilder = new StringBuilder();
using (var writer = new StringWriter(stringBuilder))
{
provider.GenerateCodeFromCompileUnit(compile, writer, options);
writer.Flush();
writer.Close();
}
var result = stringBuilder.ToString();
return result;
}
示例6: CreateCodeObject
public CodeObject CreateCodeObject()
{
var conditions = _types
.Select(CreateNumberSetValueCondition)
.Concat(_types
.Concat(_arrayTypes)
.Select(CreateArraySetValueCondition));
var firstCondition = conditions.First();
var currentCondition = firstCondition;
foreach (var condition in conditions.Skip(1))
{
currentCondition.FalseStatements.Add(condition);
currentCondition = condition;
}
currentCondition.FalseStatements.Add(CodeHelper.Return(CodeHelper.False()));
var type = new CodeTypeDeclaration("AphidObject") { IsPartial = true };
type.Members.Add(TrySetProperty(firstCondition));
var ns = new CodeNamespace();
ns.Imports.Add(new CodeNamespaceImport("System.Linq"));
ns.Name = "Components.Aphid.Interpreter";
ns.Types.Add(type);
var unit = new CodeCompileUnit();
unit.Namespaces.Add(ns);
return unit;
}
示例7: ProcessGeneratedCode
public override void ProcessGeneratedCode(DomainServiceDescription domainServiceDescription, CodeCompileUnit codeCompileUnit, IDictionary<Type, CodeTypeDeclaration> typeMapping)
{
// Get a reference to the entity class
CodeTypeDeclaration codeGenEntity = typeMapping[typeof(TestEntity)];
AppDomain appDomain = AppDomain.CurrentDomain;
AppDomainSetup setup = appDomain.SetupInformation;
string baseDir = appDomain.BaseDirectory;
codeGenEntity.Comments.Add(new CodeCommentStatement("[CodeProcessor] BaseDirectory:" + baseDir));
Configuration cfg = WebConfigurationManager.OpenWebConfiguration(null);
AuthenticationSection authSection = (AuthenticationSection)cfg.GetSection("system.web/authentication");
FormsAuthenticationConfiguration formsAuth = authSection.Forms;
if (formsAuth != null)
{
codeGenEntity.Comments.Add(new CodeCommentStatement("[CodeProcessor] Authentication:forms"));
}
ConnectionStringsSection connSect = cfg.ConnectionStrings;
if (connSect != null)
{
ConnectionStringSettingsCollection connColl = connSect.ConnectionStrings;
foreach (ConnectionStringSettings connSetting in connColl)
{
codeGenEntity.Comments.Add(new CodeCommentStatement("[CodeProcessor] ConnectionString:" + connSetting.ConnectionString));
}
}
}
示例8: CodeSnippetBlankLines
public void CodeSnippetBlankLines ()
{
var opt = new CodeGeneratorOptions () {
BlankLinesBetweenMembers = false,
VerbatimOrder = false
};
var ccu = new CodeCompileUnit ();
var ns = new CodeNamespace ("Foo");
ccu.Namespaces.Add (ns);
var t = new CodeTypeDeclaration ("Bar");
ns.Types.Add (t);
t.Members.Add (new CodeSnippetTypeMember ("#line hidden"));
t.Members.Add (new CodeSnippetTypeMember ("#line hidden2"));
t.Members.Add (new CodeMemberMethod () { Name = "Foo" });
using (var sw = new StringWriter ()) {
new CSharpCodeProvider ().GenerateCodeFromCompileUnit (ccu, sw, opt);
var str = sw.ToString ();
Assert.IsFalse (str.Contains ("hidden2private"), "#0");
Assert.IsTrue (str.Contains( "#line hidden#line hidden2"), "#1");
}
}
示例9: ImportSchemaType
public override string ImportSchemaType(
string name,
string ns,
XmlSchemaObject context,
XmlSchemas schemas,
XmlSchemaImporter importer,
CodeCompileUnit compileUnit,
CodeNamespace mainNamespace,
CodeGenerationOptions options,
CodeDomProvider codeProvider)
{
if (ns != "http://www.w3.org/2001/XMLSchema")
return null;
switch (name)
{
case "anyURI": return "System.Uri";
case "gDay": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDay";
case "gMonth": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonth";
case "gMonthDay": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonthDay";
case "gYear": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapYear";
case "gYearMonth": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapYearMonth";
case "duration": return "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDuration";
default: return null;
}
}
示例10: XsdDataContractImporter
public XsdDataContractImporter (CodeCompileUnit codeCompileUnit)
{
// null argument is ok.
CodeCompileUnit = codeCompileUnit ?? new CodeCompileUnit ();
// Options is null by default
}
示例11: Execute
public override bool Execute ()
{
var provider = CodeDomProvider.CreateProvider (Language);
if (provider == null) {
Log.LogError ("Could not create CodeDOM provider for language '{0}'", Language);
return false;
}
var ccu = new CodeCompileUnit ();
foreach (var addin in AddinReferences) {
//assembly:Mono.Addins.AddinDependency ("::%(Identity)", MonoDevelop.BuildInfo.Version)]
ccu.AssemblyCustomAttributes.Add (
new CodeAttributeDeclaration (
new CodeTypeReference ("Mono.Addins.AddinDependencyAttribute"),
new [] {
new CodeAttributeArgument (new CodePrimitiveExpression ("::" + addin.ItemSpec)),
new CodeAttributeArgument (new CodePrimitiveExpression (addin.GetMetadata ("Version")))
}
)
);
}
Directory.CreateDirectory (Path.GetDirectoryName (Filename));
using (var sw = new StreamWriter (Filename)) {
provider.GenerateCodeFromCompileUnit (ccu, sw, new CodeGeneratorOptions ());
}
return true;
}
示例12: ProcessGeneratedCode
public override void ProcessGeneratedCode(
CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType,
CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod)
{
ExampleDependencyInjectionLogic(buildMethod);
base.ProcessGeneratedCode(codeCompileUnit, baseType, derivedType, buildMethod, dataBindingMethod);
}
示例13: Generate
public CodeCompileUnit Generate(ClassData classData)
{
if (classData == null)
{
throw FxTrace.Exception.ArgumentNull("classData");
}
CodeCompileUnit result = new CodeCompileUnit();
// Add global namespace
CodeNamespace globalNamespace = new CodeNamespace();
result.Namespaces.Add(globalNamespace);
CodeTypeDeclaration classDeclaration = GenerateClass(classData);
if (!String.IsNullOrEmpty(classData.Namespace))
{
// Add namespace the class is defined in
CodeNamespace classNamespace = new CodeNamespace(classData.Namespace);
result.Namespaces.Add(classNamespace);
classNamespace.Types.Add(classDeclaration);
}
else
{
// Add class to global namespace
globalNamespace.Types.Add(classDeclaration);
}
return result;
}
示例14: CompileAndCreateTest
private object CompileAndCreateTest(string fileName, Feature feature)
{
string className = Path.GetFileNameWithoutExtension(fileName);
const string targetNamespace = "Target.Namespace";
// the row test generation has to be set to false, because our verifications support the old style test generation only
SpecFlowUnitTestConverter converter = new SpecFlowUnitTestConverter(CreateUnitTestGeneratorProvider(), new CodeDomHelper(CodeDomProviderLanguage.CSharp), new GeneratorConfiguration { AllowRowTests = false, AllowDebugGeneratedFiles = true });
var codeNamespace = converter.GenerateUnitTestFixture(feature, className, targetNamespace);
var compileUnit = new CodeCompileUnit();
compileUnit.Namespaces.Add(codeNamespace);
Dictionary<string, string> providerOptions = new Dictionary<string, string>();
providerOptions["CompilerVersion"] = "v3.5";
CSharpCodeProvider codeProvider = new CSharpCodeProvider(providerOptions);
CompilerParameters compilerParameters = new CompilerParameters();
compilerParameters.GenerateInMemory = true;
compilerParameters.TempFiles.KeepFiles = true;
compilerParameters.ReferencedAssemblies.Add(
TestFileHelper.GetAssemblyPath(typeof (GeneratedCodeAttribute))); //System
compilerParameters.ReferencedAssemblies.Add(
TestFileHelper.GetAssemblyPath(typeof (TestAttribute))); //NUnit
compilerParameters.ReferencedAssemblies.Add(
TestFileHelper.GetAssemblyPath(typeof (ITestRunner))); //TechTalk.SpecFlow
var results = codeProvider.CompileAssemblyFromDom(compilerParameters, compileUnit);
if (results.NativeCompilerReturnValue != 0)
throw new InvalidOperationException("Test cannot be compiled: " +
string.Join(Environment.NewLine, results.Errors.Cast<CompilerError>().Select(ce => ce.ToString()).ToArray()));
Type testType = results.CompiledAssembly.GetType(targetNamespace + "." + className, true);
return Activator.CreateInstance(testType);
}
示例15: Main
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();
}