本文整理汇总了C#中System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromDom方法的典型用法代码示例。如果您正苦于以下问题:C# CodeDomProvider.CompileAssemblyFromDom方法的具体用法?C# CodeDomProvider.CompileAssemblyFromDom怎么用?C# CodeDomProvider.CompileAssemblyFromDom使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.CodeDom.Compiler.CodeDomProvider
的用法示例。
在下文中一共展示了CodeDomProvider.CompileAssemblyFromDom方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GenerateRazorView
private RazorViewBase GenerateRazorView(CodeDomProvider codeProvider, GeneratorResults razorResult)
{
// Compile the generated code into an assembly
string outputAssemblyName = String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N"));
CompilerResults results = codeProvider.CompileAssemblyFromDom(
new CompilerParameters(new string[] {
GetAssemblyPath(typeof(Microsoft.CSharp.RuntimeBinder.Binder)),
GetAssemblyPath(typeof(System.Runtime.CompilerServices.CallSite)),
GetAssemblyPath(Assembly.GetExecutingAssembly()) }, outputAssemblyName),
razorResult.GeneratedCode);
if (results.Errors.HasErrors) {
CompilerError err = results.Errors
.OfType<CompilerError>()
.Where(ce => !ce.IsWarning)
.First();
var error = String.Format("Error Compiling Template: ({0}, {1}) {2})",
err.Line, err.Column, err.ErrorText);
return new ErrorView(error);
}
else {
// Load the assembly
Assembly assembly = Assembly.LoadFrom(outputAssemblyName);
if (assembly == null) {
string error = "Error loading template assembly";
return new ErrorView(error);
}
else {
// Get the template type
Type type = assembly.GetType("RazorOutput.RazorView");
if (type == null) {
string error = String.Format("Could not find type RazorOutput.Template in assembly {0}", assembly.FullName);
return new ErrorView(error);
}
else {
RazorViewBase view = Activator.CreateInstance(type) as RazorViewBase;
if (view == null) {
string error = "Could not construct RazorOutput.Template or it does not inherit from RazorViewBase";
return new ErrorView(error);
}
else {
return view;
}
}
}
}
}
示例2: SoapHelper
/// <summary>
/// 动态 WebService 构造函数
/// </summary>
/// <param name="pUrl">WebService 地址</param>
/// <param name="pClassname">类名,可省略,可空</param>
public SoapHelper(string pUrl, string pClassname = null)
{
if (String.IsNullOrEmpty(pClassname))
WebServiceClassname = GetWsClassName(pUrl);
else
WebServiceClassname = pClassname;
WebServiceNamespace = "LiveAzure.Utility";
try
{
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(pUrl + "?WSDL");
ServiceDescription sd = ServiceDescription.Read(stream);
ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
sdi.AddServiceDescription(sd, "", "");
sdi.ProtocolName = "Soap";
sdi.Style = ServiceDescriptionImportStyle.Client;
sdi.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
CodeNamespace cn = new CodeNamespace(this.WebServiceNamespace);
SoapCompileUnit = new CodeCompileUnit();
SoapCompileUnit.Namespaces.Add(cn);
sdi.Import(cn, SoapCompileUnit);
CSharpCodeProvider csc = new CSharpCodeProvider();
SoapCodeProvider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters cparam = new CompilerParameters();
cparam.GenerateExecutable = false;
cparam.GenerateInMemory = true;
cparam.ReferencedAssemblies.Add("System.dll");
cparam.ReferencedAssemblies.Add("System.XML.dll");
cparam.ReferencedAssemblies.Add("System.Web.Services.dll");
cparam.ReferencedAssemblies.Add("System.Data.dll");
SoapCompilerResults = SoapCodeProvider.CompileAssemblyFromDom(cparam, SoapCompileUnit);
if (SoapCompilerResults.Errors.HasErrors)
{
StringBuilder sb = new StringBuilder();
foreach (CompilerError ce in SoapCompilerResults.Errors)
{
sb.Append(ce.ToString());
sb.Append(Environment.NewLine);
}
throw new Exception(sb.ToString());
}
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
}
}
示例3: SaveAsAssembly
public void SaveAsAssembly(CodeDomProvider provider, GLSLAssembly assembly)
{
// Build the parameters for source compilation.
var cp = new CompilerParameters();
// Add an assembly reference.
cp.ReferencedAssemblies.Add( "System.dll" );
cp.ReferencedAssemblies.Add ("System.Runtime.InteropServices.dll");
if (assembly.ReferencedAssemblies != null)
{
foreach (var assemblyName in assembly.ReferencedAssemblies)
{
cp.ReferencedAssemblies.Add( assemblyName );
}
}
// Generate an executable instead of
// a class library.
cp.GenerateExecutable = false;
// Set the assembly file name to generate.
cp.OutputAssembly = System.IO.Path.Combine(assembly.Path,assembly.OutputAssembly);
// Save the assembly as a physical file.
cp.GenerateInMemory = false;
var contentUnit = InitialiseCompileUnit (assembly);
// Invoke compilation.
CompilerResults cr = provider.CompileAssemblyFromDom(cp, contentUnit);
if (cr.Errors.Count > 0)
{
Debug.WriteLine(string.Format("Source built into {0} unsuccessfully.", cr.PathToAssembly));
// Display compilation errors.
foreach (CompilerError ce in cr.Errors)
{
Debug.WriteLine(" {0}", ce.ToString());
}
}
else
{
Debug.WriteLine(string.Format("Source built into {0} successfully.", cr.PathToAssembly));
}
}
示例4: GenerateRazorViewFactory
private Func<INancyRazorView> GenerateRazorViewFactory(CodeDomProvider codeProvider, GeneratorResults razorResult, Assembly referencingAssembly, IEnumerable<string> rendererSpecificAssemblies, Type passedModelType, ViewLocationResult viewLocationResult)
{
var outputAssemblyName = Path.Combine(Path.GetTempPath(), String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N")));
var modelType = FindModelType(razorResult.Document, passedModelType);
var assemblies = new List<string>
{
GetAssemblyPath(typeof(System.Runtime.CompilerServices.CallSite)),
GetAssemblyPath(typeof(IHtmlString)),
GetAssemblyPath(Assembly.GetExecutingAssembly()),
GetAssemblyPath(modelType)
};
if (referencingAssembly != null)
{
assemblies.Add(GetAssemblyPath(referencingAssembly));
}
assemblies = assemblies
.Union(rendererSpecificAssemblies)
.ToList();
if (this.razorConfiguration != null)
{
var assemblyNames = this.razorConfiguration.GetAssemblyNames();
if (assemblyNames != null)
{
assemblies.AddRange(assemblyNames.Select(Assembly.Load).Select(GetAssemblyPath));
}
if (this.razorConfiguration.AutoIncludeModelNamespace)
{
AddModelNamespace(razorResult, modelType);
}
}
var compilerParameters = new CompilerParameters(assemblies.ToArray(), outputAssemblyName);
CompilerResults results;
lock (this.compileLock)
{
results = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode);
}
if (results.Errors.HasErrors)
{
var output = new string[results.Output.Count];
results.Output.CopyTo(output, 0);
var outputString = string.Join("\n", output);
var fullTemplateName = viewLocationResult.Location + "/" + viewLocationResult.Name + "." + viewLocationResult.Extension;
var templateLines = GetViewBodyLines(viewLocationResult);
var errors = results.Errors.OfType<CompilerError>().Where(ce => !ce.IsWarning).ToArray();
var errorMessages = BuildErrorMessages(errors);
MarkErrorLines(errors, templateLines);
var errorDetails = string.Format(
"Error compiling template: <strong>{0}</strong><br/><br/>Errors:<br/>{1}<br/><br/>Details:<br/>{2}",
fullTemplateName,
errorMessages,
templateLines.Aggregate((s1, s2) => s1 + "<br/>" + s2));
return () => new NancyRazorErrorView(errorDetails);
}
var assembly = Assembly.LoadFrom(outputAssemblyName);
if (assembly == null)
{
const string error = "Error loading template assembly";
return () => new NancyRazorErrorView(error);
}
var type = assembly.GetType("RazorOutput.RazorView");
if (type == null)
{
var error = String.Format("Could not find type RazorOutput.Template in assembly {0}", assembly.FullName);
return () => new NancyRazorErrorView(error);
}
if (Activator.CreateInstance(type) as INancyRazorView == null)
{
const string error = "Could not construct RazorOutput.Template or it does not inherit from INancyRazorView";
return () => new NancyRazorErrorView(error);
}
return () => (INancyRazorView)Activator.CreateInstance(type);
}
示例5: Run
/// <summary>
/// This overrides the CodeDomTest Run method that does verification
/// on the tree provided in the BuildTree method you provide.
/// </summary>
/// <param name="provider">Provider to test.</param>
/// <returns>True if the tree builds, compiles, searches and passes
/// assembly verification. False if any of these fails.</returns>
public override bool Run (CodeDomProvider provider) {
bool fail = false;
// build the tree
LogMessageIndent ();
LogMessage ("- Generating tree.");
CodeCompileUnit cu = new CodeCompileUnit ();
LogMessageIndent ();
BuildTree (provider, cu);
LogMessageUnindent ();
// validate tree using 'experimental' subset tester
// but only if the test believes its in the subset
if ((TestType & TestTypes.Subset) != 0) {
SubsetConformance subsConf = new SubsetConformance ();
LogMessage ("- Checking tree subset conformance.");
if (!subsConf.ValidateCodeCompileUnit (cu))
LogMessage ("Failed subset tester: {0}",
subsConf.ToString ());
}
// realize source
StringWriter sw = new StringWriter (CultureInfo.InvariantCulture);
#if WHIDBEY
provider.GenerateCodeFromCompileUnit (cu, sw, GetGeneratorOptions (provider));
#else
ICodeGenerator generator = provider.CreateGenerator ();
generator.GenerateCodeFromCompileUnit (cu, sw, GetGeneratorOptions (provider));
#endif
// only continue if the source could be realized into a string.
if (!fail) {
string source = sw.ToString ();
if (saveSourceFileName.Length > 0) {
LogMessage ("- Saving source into '" + saveSourceFileName + "'");
// save this source to a file
DumpStringToFile (source, saveSourceFileName);
}
// log the source code
//LogMessage (source);
// search the source if the test case asks us to
if (ShouldSearch) {
LogMessageIndent ();
Search (provider, source);
LogMessageUnindent ();
}
// continue only if the test case wants to compile or verify
if (ShouldCompile || ShouldVerify) {
// ask the test case which compiler parameters it would like to use
CompilerParameters parms = GetCompilerParameters (provider);
#if FSHARP
// If the generated code has entrypoint, then F# requires us to generate EXE
bool hasEntryPoint = false;
foreach(CodeNamespace ns in cu.Namespaces)
foreach (CodeTypeDeclaration ty in ns.Types)
foreach(CodeTypeMember mem in ty.Members)
if (mem is CodeEntryPointMethod) { hasEntryPoint = true; }
// If the output file name is specified then it should be EXE
if (hasEntryPoint && parms.GenerateExecutable == false)
{
parms.GenerateExecutable = true;
if (saveAssemblyFileName.ToLower().EndsWith(".dll"))
saveAssemblyFileName = saveAssemblyFileName.Substring(0, saveAssemblyFileName.Length - 4) + ".exe";
}
#endif
// add the appropriate compiler parameters if the user asked us
// to save assemblies to file
if (saveAssemblyFileName.Length > 0) {
parms.OutputAssembly = saveAssemblyFileName;
LogMessage ("- Compiling to '" + saveAssemblyFileName + "'.");
}
// always generate in memory for verification purposes
parms.GenerateInMemory = true;
// compile!
#if WHIDBEY
CompilerResults results = provider.CompileAssemblyFromDom (parms, cu);
#else
ICodeCompiler compiler = provider.CreateCompiler ();
CompilerResults results = compiler.CompileAssemblyFromDom (parms, cu);
#endif
if (results.NativeCompilerReturnValue != 0) {
//.........这里部分代码省略.........
示例6: GenerateRazorViewFactory
private Func<NancyRazorViewBase> GenerateRazorViewFactory(CodeDomProvider codeProvider, GeneratorResults razorResult, Assembly referencingAssembly, IEnumerable<string> rendererSpecificAssemblies, Type passedModelType)
{
var outputAssemblyName = Path.Combine(Path.GetTempPath(), String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N")));
var modelType = FindModelType(razorResult.Document, passedModelType);
var assemblies = new List<string>
{
GetAssemblyPath(typeof(System.Runtime.CompilerServices.CallSite)),
GetAssemblyPath(typeof(IHtmlString)),
GetAssemblyPath(Assembly.GetExecutingAssembly()),
GetAssemblyPath(modelType)
};
if (referencingAssembly != null)
assemblies.Add(GetAssemblyPath(referencingAssembly));
assemblies = assemblies
.Union(rendererSpecificAssemblies)
.ToList();
if (this.razorConfiguration != null)
{
var assemblyNames = this.razorConfiguration.GetAssemblyNames();
if (assemblyNames != null)
{
assemblies.AddRange(assemblyNames.Select(Assembly.Load).Select(GetAssemblyPath));
}
if (this.razorConfiguration.AutoIncludeModelNamespace)
{
AddModelNamespace(razorResult, modelType);
}
}
var compilerParameters = new CompilerParameters(assemblies.ToArray(), outputAssemblyName);
var results = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode);
if (results.Errors.HasErrors)
{
var err = results.Errors
.OfType<CompilerError>()
.Where(ce => !ce.IsWarning)
.Select(error => String.Format("Error Compiling Template: ({0}, {1}) {2})", error.Line, error.Column, error.ErrorText))
.Aggregate((s1, s2) => s1 + "<br/>" + s2);
return () => new NancyRazorErrorView(err);
}
var assembly = Assembly.LoadFrom(outputAssemblyName);
if (assembly == null)
{
const string error = "Error loading template assembly";
return () => new NancyRazorErrorView(error);
}
var type = assembly.GetType("RazorOutput.RazorView");
if (type == null)
{
var error = String.Format("Could not find type RazorOutput.Template in assembly {0}", assembly.FullName);
return () => new NancyRazorErrorView(error);
}
if (Activator.CreateInstance(type) as NancyRazorViewBase == null)
{
const string error = "Could not construct RazorOutput.Template or it does not inherit from RazorViewBase";
return () => new NancyRazorErrorView(error);
}
return () => (NancyRazorViewBase)Activator.CreateInstance(type);
}
示例7: ImportSchemasAsClasses
private static void ImportSchemasAsClasses(CodeDomProvider codeProvider, System.IO.Stream xsdStream, string ns, string uri, CodeGenerationOptions options, IList elements, StringCollection schemaImporterExtensions)
{
XmlSchemas userSchemas = new XmlSchemas();
Hashtable uris = new Hashtable();
XmlSchema schema = ReadSchema(xsdStream);
Uri uri2 = new Uri("http://www.w3.org/2001/XMLSchema/temp");
uris.Add(schema, uri2);
userSchemas.Add(schema, uri2);
Hashtable includeSchemas = new Hashtable();
Compile(userSchemas, uris, includeSchemas);
try
{
CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
CodeNamespace namespace2 = new CodeNamespace(ns);
codeCompileUnit.Namespaces.Add(namespace2);
GenerateVersionComment(namespace2);
XmlCodeExporter codeExporter = new XmlCodeExporter(namespace2, codeCompileUnit, codeProvider, options, null);
XmlSchemaImporter schemaImporter = new XmlSchemaImporter(userSchemas, options, codeProvider, new ImportContext(new CodeIdentifiers(), false));
schemaImporter.Extensions.Add(new System.Data.DataSetSchemaImporterExtension());
{
StringEnumerator enumerator2 = schemaImporterExtensions.GetEnumerator();
{
while (enumerator2.MoveNext())
{
Type type = Type.GetType(enumerator2.Current.Trim(), true, false);
schemaImporter.Extensions.Add(type.FullName, type);
}
}
}
AddImports(namespace2, GetNamespacesForTypes(new Type[] { typeof(XmlAttributeAttribute) }));
for (int i = 0; i < userSchemas.Count; i++)
{
ImportSchemaAsClasses(userSchemas[i], uri, elements, schemaImporter, codeExporter);
}
foreach (XmlSchema schema2 in includeSchemas.Values)
{
ImportSchemaAsClasses(schema2, uri, elements, schemaImporter, codeExporter);
}
CompilerParameters compilePrams = new CompilerParameters();
CompilerResults compileResults = codeProvider.CompileAssemblyFromDom(compilePrams, codeCompileUnit);
if (compileResults.Errors.Count > 0)
{
throw new ArgumentException("Compile Error of " + compileResults.Errors[0].ToString());
}
// Feng.Windows.Utils.ReflectionHelper.CreateInstanceFromType(compileResults.CompiledAssembly.GetTypes()[0])
//CodeTypeDeclarationCollection types = namespace2.Types;
//CodeGenerator.ValidateIdentifiers(namespace2);
//TextWriter writer = this.CreateOutputWriter(outputdir, fileName, fileExtension);
//codeProvider.GenerateCodeFromCompileUnit(codeCompileUnit, writer, null);
//writer.Close();
}
catch (Exception ex)
{
throw new ArgumentException("Compile Xsd Error!", ex);
}
}
示例8: CompileCode
private CompilerResults CompileCode(CodeDomProvider provider, CodeCompileUnit unit, string outputAssemblyPath = null)
{
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.AddRange(GetReferenceAssemblyPaths(this._serviceInterface).ToArray());
cp.ReferencedAssemblies.AddRange(GetReferenceAssemblyPaths(typeof(HttpRestClient<>)).ToArray());
cp.GenerateInMemory = outputAssemblyPath == null;
if (!string.IsNullOrEmpty(outputAssemblyPath))
{
cp.OutputAssembly = outputAssemblyPath;
}
CompilerResults results = provider.CompileAssemblyFromDom(cp, unit);
if (results.Errors.Count > 0)
{
throw new CompileException("Compilation failed: Please look at the CompilerErrors property for more details!", results);
}
return results;
}
示例9: ToAssemblyFile
public void ToAssemblyFile(CodeCompileUnit compileunit, CodeDomProvider provider, string fileName)
{
#if NET2
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");
cp.GenerateInMemory = false;
cp.OutputAssembly = fileName;
CompilerResults cr = provider.CompileAssemblyFromDom(cp, compileunit);
#else
ICodeCompiler compiler = provider.CreateCompiler();
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add( "System.dll" );
cp.GenerateInMemory = false;
cp.OutputAssembly = fileName;
CompilerResults cr = compiler.CompileAssemblyFromDom(cp, compileunit);
#endif
}