本文整理汇总了C#中Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromDom方法的典型用法代码示例。如果您正苦于以下问题:C# CSharpCodeProvider.CompileAssemblyFromDom方法的具体用法?C# CSharpCodeProvider.CompileAssemblyFromDom怎么用?C# CSharpCodeProvider.CompileAssemblyFromDom使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CSharp.CSharpCodeProvider
的用法示例。
在下文中一共展示了CSharpCodeProvider.CompileAssemblyFromDom方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GenerateAssembly
public static Assembly GenerateAssembly(Generator GenerateClassCode, out String errors)
{
CSharpCodeProvider csp = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
foreach (var item in GenerateClassCode.References)
{
cp.ReferencedAssemblies.Add(item);
}
cp.WarningLevel = 3;
cp.IncludeDebugInformation = false;
cp.CompilerOptions = "/target:library /optimize";
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;
CompilerResults results = csp.CompileAssemblyFromDom(cp,GenerateClassCode.CodeCompileUnit);
if (results.Errors.HasErrors)
{
string errorMessage = "";
errorMessage = results.Errors.Count.ToString() + " Errors:";
for (int x = 0; x < results.Errors.Count; x++)
{
errorMessage = errorMessage + "\r\nLine: " +
results.Errors[x].Line.ToString() + " - " + results.Errors[x].ErrorText;
}
errors = errorMessage;
}
else
{
errors = null;
}
return results.CompiledAssembly;
}
示例2: 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);
}
示例3: CompileView
private static Type CompileView(GeneratorResults razorResult, CompilerParameters compilerParameters)
{
var codeProvider = new CSharpCodeProvider(CompilerProperties);
var result = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode);
if (result.Errors != null && result.Errors.HasErrors)
{
throw new RazorCompilerException(result.Errors.OfType<CompilerError>().Where(x => !x.IsWarning));
}
var assembly = Assembly.LoadFrom(compilerParameters.OutputAssembly);
if (assembly == null)
{
throw new RazorCompilerException("Unable to load view assembly.");
}
var type = assembly.GetType(SimpleRazorConfiguration.Namespace + "." + compilerParameters.MainClass);
if (type == null)
{
throw new RazorCompilerException("Unable to load view assembly.");
}
return type;
}
示例4: ToAssembly
public Assembly ToAssembly()
{
var errors = new List<string>();
Assembly generatedAssembly = null;
String[] assemblyNames = {
"System.dll",
"System.Core.dll",
"System.Xml.dll",
typeof(FileTable<>).Assembly.Location,
typeof(HtmlNode).Assembly.Location
};
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters(assemblyNames);
cp.GenerateExecutable = false;
//cp.OutputAssembly = "test";
cp.GenerateInMemory = true;
CompilerResults cr = provider.CompileAssemblyFromDom(cp, _units);
foreach (CompilerError compilerError in cr.Errors)
{
if(!compilerError.IsWarning)
Errors.Add(compilerError + Environment.NewLine);
}
if (!Errors.Any())
generatedAssembly = cr.CompiledAssembly;
return generatedAssembly;
}
示例5: Compile
private static Assembly Compile(CodeCompileUnit codeCompileUnit)
{
var compilerParameters = new CompilerParameters();
compilerParameters.GenerateInMemory = true;
compilerParameters.ReferencedAssemblies.Add("System.dll");
compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
compilerParameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Substring(8));
var codeProvider = new CSharpCodeProvider();
var result = codeProvider.CompileAssemblyFromDom(compilerParameters, codeCompileUnit);
if (result.Errors.HasErrors)
{
foreach (var error in result.Errors)
{
Console.WriteLine(error);
}
return null;
}
return result.CompiledAssembly;
}
示例6: Compile
internal static TemplateCompilationResult Compile(Type templateType, string templateBody, IEnumerable<string> namespaces, string tempDirectory)
{
LoadRuntimeBinder();
string className;
var compileUnit = GetCodeCompileUnit(templateType, namespaces, templateBody, out className);
string sourceCode;
var codeProvider = new CSharpCodeProvider();
var builder = new StringBuilder();
using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture))
{
codeProvider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions());
sourceCode = builder.ToString();
}
var parameters = CreateComplilerParameters(tempDirectory);
var compileResult = codeProvider.CompileAssemblyFromDom(parameters, compileUnit);
if (compileResult.Errors != null && compileResult.Errors.Count > 0)
throw new TemplateCompilationException(compileResult.Errors, sourceCode, templateBody);
var fullClassName = TEMPLATES_NAMESPACE + "." + className;
return new TemplateCompilationResult
{
Type = compileResult.CompiledAssembly.GetType(fullClassName),
SourceCode = sourceCode
};
}
示例7: GetMapperValue
/// <summary>
/// ����ӳ���������ȡCDSSSystemData.GlobalData�г�Ա����
/// ����ֵ���Ͳ�������CDSSSystemData.GlobalData�г�Ա�������;���
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static object GetMapperValue(string strClassName)
{
CodeSnippetCompileUnit unit = ConstructAndCompileCode(strClassName);
ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler();
CompilerParameters para = new CompilerParameters();
para.ReferencedAssemblies.Add(CONST_IMPORT_SYSTEM_DLL);
para.ReferencedAssemblies.Add(CONST_IMPORT_CDSS_SYSTEM_DATA_DLL);
para.GenerateInMemory = true;
para.GenerateExecutable = false;
CompilerResults cr = compiler.CompileAssemblyFromDom(para, unit);
if (cr.Errors.Count > 0)
{
string str = "�����ļ������ " + cr.PathToAssembly + ": \r\n";
foreach (CompilerError ce in cr.Errors)
str = ce.ToString();
return false;
}
else
{
Assembly asm = cr.CompiledAssembly;
Type type = asm.GetType(
CONST_GENERATECODE_NAMESPACE + "." + CONST_GENERATECODE_CLASSNAME);
MethodInfo mi = type.GetMethod(
CONST_GENERATECODE_METHODNAME_OBTAIN_SYSTEM_DATA, BindingFlags.Public | BindingFlags.Instance);
object obj = asm.CreateInstance(
CONST_GENERATECODE_NAMESPACE + "." + CONST_GENERATECODE_CLASSNAME);
return mi.Invoke(obj, null);
}
}
示例8: ParseAndCompileTemplate
/// <summary>
/// This method Parses and compiles the source code into an Assembly and returns it
/// </summary>
/// <param name="baseClassType">The Type of the Base class the generated class descends from</param>
/// <param name="namespaceOfGeneratedClass">The Namespace of the generated class</param>
/// <param name="generatedClassName">The Class Name of the generated class</param>
/// <param name="sourceCodeReader">A Text reader that is a warpper around the "Template" that is to be parsed and compiled</param>
/// <returns>An instance of a generated assembly that contains the generated class</returns>
public Assembly ParseAndCompileTemplate(Type baseClassType, string namespaceOfGeneratedClass, string generatedClassName, TextReader sourceCodeReader)
{
RazorTemplateEngine engine = InitializeRazorEngine(baseClassType, namespaceOfGeneratedClass, generatedClassName);
GeneratorResults razorResults = engine.GenerateCode(sourceCodeReader);
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CodeGeneratorOptions options = new CodeGeneratorOptions();
string generatedCode = null;
using (StringWriter writer = new StringWriter())
{
codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, writer, options);
generatedCode = writer.GetStringBuilder().ToString();
}
var outputAssemblyName = Path.GetTempPath() + Guid.NewGuid().ToString("N") + ".dll";
CompilerParameters compilerParameters = new CompilerParameters(new string[]{}, outputAssemblyName);
compilerParameters.ReferencedAssemblies.Add("System.dll");
compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Substring(8));
compilerParameters.GenerateInMemory = false;
CompilerResults compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResults.GeneratedCode);
if (compilerResults.Errors.Count > 0)
{
var compileErrors = new StringBuilder();
foreach (System.CodeDom.Compiler.CompilerError compileError in compilerResults.Errors)
compileErrors.Append(String.Format("Line: {0}\t Col: {1}\t Error: {2}\r\n", compileError.Line, compileError.Column, compileError.ErrorText));
throw new Exception(compileErrors.ToString() + generatedCode);
}
return compilerResults.CompiledAssembly;
}
示例9: GetTemplateFactory
public ICompiledTemplate GetTemplateFactory(Stream template)
{
var engine = CreateEngine();
GeneratorResults results;
using (var reader = new StreamReader(template))
{
results = engine.GenerateCode(reader);
}
var outputAssemblyName = string.Format("Generated_{0}.dll", Guid.NewGuid().ToString("N"));
var codeProvider = new CSharpCodeProvider();
var thisAssembly = typeof(TemplateBase).Assembly.Location;
codeProvider.CompileAssemblyFromDom(
new CompilerParameters(new[] {thisAssembly}, outputAssemblyName),
results.GeneratedCode);
var newAssembly = Assembly.LoadFrom(outputAssemblyName);
var type = newAssembly.GetType("RazorOutput.Template");
var factory = CreateFactory(type);
return new CompiledTemplate(factory);
}
示例10: GetWebServiceAssembly
/// <summary>
/// get an Assembly according to wsdl path.
/// </summary>
/// <param name="wsdl">wsdl path</param>
/// <param name="nameSpace">namespace</param>
/// <returns>return Assembly</returns>
public static Assembly GetWebServiceAssembly(string wsdl, string nameSpace)
{
try
{
System.Net.WebClient webClient = new System.Net.WebClient();
System.IO.Stream webStream = webClient.OpenRead(wsdl);
ServiceDescription serviceDescription = ServiceDescription.Read(webStream);
ServiceDescriptionImporter serviceDescroptImporter = new ServiceDescriptionImporter();
serviceDescroptImporter.AddServiceDescription(serviceDescription, "", "");
System.CodeDom.CodeNamespace codeNameSpace = new System.CodeDom.CodeNamespace(nameSpace);
System.CodeDom.CodeCompileUnit codeCompileUnit = new System.CodeDom.CodeCompileUnit();
codeCompileUnit.Namespaces.Add(codeNameSpace);
serviceDescroptImporter.Import(codeNameSpace, codeCompileUnit);
System.CodeDom.Compiler.CodeDomProvider codeDom = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters codeParameters = new System.CodeDom.Compiler.CompilerParameters();
codeParameters.GenerateExecutable = false;
codeParameters.GenerateInMemory = true;
codeParameters.ReferencedAssemblies.Add("System.dll");
codeParameters.ReferencedAssemblies.Add("System.XML.dll");
codeParameters.ReferencedAssemblies.Add("System.Web.Services.dll");
codeParameters.ReferencedAssemblies.Add("System.Data.dll");
System.CodeDom.Compiler.CompilerResults compilerResults = codeDom.CompileAssemblyFromDom(codeParameters, codeCompileUnit);
return compilerResults.CompiledAssembly;
}
catch (Exception ex)
{
throw ex;
}
}
示例11: compileToAssembly
static Assembly compileToAssembly(CodeCompileUnit compileUnit)
{
var provider = new CSharpCodeProvider();
var baseAssembly = typeof(RazorHtmlTemplate<>).Assembly;
// todo: autodetect @using header lines and add them.
var parameters = new CompilerParameters(
// path does not work
// csharp.dll is for the use of dynamic
new[] { baseAssembly.Location, "System.Core.dll", "Microsoft.CSharp.dll"},
string.Empty,
false);
dumpGeneratedCode(compileUnit, provider);
var compRes = provider.CompileAssemblyFromDom(parameters, new[] { compileUnit });
if (compRes.Output.Count != 0)
{
#if DEBUG
Log.D("Compilation results:");
foreach (var str in compRes.Output)
Log.D(str);
#endif
if (compRes.Errors.Count != 0)
throw new Exception(compRes.Errors[0].ToString());
}
var assembly = compRes.CompiledAssembly;
return assembly;
}
示例12: InvokeWebService
/// <summary>
/// 实例化WebServices
/// </summary>
/// <param name="url">WebServices地址</param>
/// <param name="methodname">调用的方法</param>
/// <param name="args">把webservices里需要的参数按顺序放到这个object[]里</param>
public static object InvokeWebService(string url, string methodname, object[] args)
{
//这里的namespace是需引用的webservices的命名空间,我没有改过,也可以使用。也可以加一个参数从外面传进来。
string @namespace = "client";
try
{
//获取WSDL
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(url + "?WSDL");
ServiceDescription sd = ServiceDescription.Read(stream);
string classname = sd.Services[0].Name;
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 = csc.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)
{
return ex.Message;
}
}
示例13: BuildAssembly
public virtual List<ExplorerItem> BuildAssembly(IConnectionInfo cxInfo, AssemblyName assemblyToBuild, ref string nameSpace, ref string typeName)
{
var unit = new CodeCompileUnit();
var namespace2 = new CodeNamespace(nameSpace);
namespace2.Imports.Add(new CodeNamespaceImport("System"));
namespace2.Imports.Add(new CodeNamespaceImport("System.Linq"));
namespace2.Imports.Add(new CodeNamespaceImport("Sitecore.ContentSearch"));
namespace2.Imports.Add(new CodeNamespaceImport("Sitecore.ContentSearch.SearchTypes"));
var settings = new SitecoreConnectionSettings();
var mapper = new DriverDataCxSettingsMapper();
mapper.Read(cxInfo, settings);
var selectedType = settings.SearchResultType.GetSelectedType();
namespace2.Imports.Add(new CodeNamespaceImport(selectedType.Namespace));
var declaration = new CodeTypeDeclaration(typeName)
{
IsClass = true,
TypeAttributes = TypeAttributes.Public
};
namespace2.Types.Add(declaration);
unit.Namespaces.Add(namespace2);
var constructor = new CodeConstructor
{
Attributes = MemberAttributes.Public
};
this.AddConstructorCode(constructor, settings);
declaration.Members.Add(constructor);
var indexNames = this.GetIndexNames(cxInfo);
var list = new List<ExplorerItem>();
foreach (var str in indexNames)
{
this.AddIndexAsProperty(str, selectedType, declaration);
var item = new ExplorerItem(str, ExplorerItemKind.QueryableObject, ExplorerIcon.Table)
{
IsEnumerable = false
};
item.DragText = this.GetDragText(item, settings);
list.Add(item);
}
var provider = new CSharpCodeProvider();
var options = new CompilerParameters();
var assemblyFilesToReference = this.GetAssemblyFilesToReference(settings);
foreach (var str2 in assemblyFilesToReference)
{
options.ReferencedAssemblies.Add(str2);
}
options.GenerateInMemory = true;
options.OutputAssembly = assemblyToBuild.CodeBase;
var results = provider.CompileAssemblyFromDom(options, new CodeCompileUnit[] { unit });
if (results.Errors.Count > 0)
{
throw new Exception(string.Concat(new object[] { "Cannot compile typed context: ", results.Errors[0].ErrorText, " (line ", results.Errors[0].Line, ")" }));
}
return list;
}
示例14: InvokeWebService
/// < summary>
/// 动态调用web服务
/// < /summary>
/// < param name="url">WSDL服务地址< /param>
/// < param name="classname">类名< /param>
/// < param name="methodname">方法名< /param>
/// < param name="args">参数< /param>
/// < returns>< /returns>
public static object InvokeWebService(string url, string classname, string methodname, object[] args)
{
string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
if ((classname == null) || (classname == ""))
{
classname = WSHelper.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 icc = new CSharpCodeProvider();
//设定编译参数
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);
// PropertyInfo propertyInfo = type.GetProperty(propertyname);
//return propertyInfo.GetValue(obj, null);
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
}
}
示例15: GetWsProxyType
public static Type GetWsProxyType(string wsUrl, string classname)
{
string name = "ESBasic.WebService.DynamicWebCalling";
if ((classname == null) || (classname == ""))
{
classname = GetWsClassName(wsUrl);
}
string key = wsUrl + "@" + classname;
if (WSProxyTypeDictionary.ContainsKey(key))
{
return WSProxyTypeDictionary[key];
}
WebClient client = new WebClient();
ServiceDescription serviceDescription = ServiceDescription.Read(client.OpenRead(wsUrl + "?WSDL"));
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.AddServiceDescription(serviceDescription, "", "");
CodeNamespace namespace2 = new CodeNamespace(name);
CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
codeCompileUnit.Namespaces.Add(namespace2);
importer.Import(namespace2, codeCompileUnit);
ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler();
CompilerParameters options = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = true
};
options.ReferencedAssemblies.Add("System.dll");
options.ReferencedAssemblies.Add("System.XML.dll");
options.ReferencedAssemblies.Add("System.Web.Services.dll");
options.ReferencedAssemblies.Add("System.Data.dll");
CompilerResults results = compiler.CompileAssemblyFromDom(options, codeCompileUnit);
if (results.Errors.HasErrors)
{
StringBuilder builder = new StringBuilder();
foreach (CompilerError error in results.Errors)
{
builder.Append(error.ToString());
builder.Append(Environment.NewLine);
}
throw new Exception(builder.ToString());
}
Assembly compiledAssembly = results.CompiledAssembly;
compiledAssembly.GetTypes();
Type type2 = compiledAssembly.GetType(name + "." + classname, true, true);
lock (WSProxyTypeDictionary)
{
if (!WSProxyTypeDictionary.ContainsKey(key))
{
WSProxyTypeDictionary.Add(key, type2);
}
}
return type2;
}