-
Notifications
You must be signed in to change notification settings - Fork 224
/
CommonUtilities.cs
60 lines (52 loc) · 1.9 KB
/
CommonUtilities.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.VisualStudio.Web.CodeGeneration.DotNet;
namespace Microsoft.VisualStudio.Web.CodeGeneration
{
public static class CommonUtilities
{
public static CompilationResult GetAssemblyFromCompilation(
ICodeGenAssemblyLoadContext loader,
CodeAnalysis.Compilation compilation)
{
using (var ms = new MemoryStream())
{
var result = compilation.Emit(ms, pdbStream: null);
if (!result.Success)
{
var formatter = new DiagnosticFormatter();
var errorMessages = result.Diagnostics
.Where(IsError)
.Select(d => formatter.Format(d));
return CompilationResult.FromErrorMessages(errorMessages);
}
ms.Seek(0, SeekOrigin.Begin);
Assembly assembly;
try
{
assembly = loader.LoadStream(ms, symbols: null);
}
catch (Exception ex)
{
var v = ex;
while (v.InnerException != null)
{
v = v.InnerException;
}
throw ex;
}
return CompilationResult.FromAssembly(assembly);
}
}
private static bool IsError(Diagnostic diagnostic)
{
return diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error;
}
}
}