С 1 января 2020 года учитывается стоимость каждой посылки или каждого прохода границы в отдельности.
2-clause BSD license
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MakeAssembly();
}
public static void MakeAssembly()
{
var code = @"
using System;
public class ExampleClass {
private readonly string _message;
public ExampleClass()
{
_message = ""Hello World"";
}
public string getMessage()
{
return _message;
}
}";
CreateAssemblyDefinition(code, "test.dll");
}
// Package Management console
// Install-Package Microsoft.CodeAnalysis.CSharp.Workspaces
// Install-Package Mono.Cecil
// Install-Package System.ValueTuple
public static void CreateAssemblyDefinition(string code, string filename)
{
var sourceLanguage = new CSharpLanguage();
var syntaxTree = sourceLanguage.ParseText(code, SourceCodeKind.Regular);
var _references = new MetadataReference[]
{
};
var compilation = sourceLanguage
.CreateLibraryCompilation(assemblyName: "InMemoryAssembly", enableOptimisations: false)
.AddReferences(_references)
.AddSyntaxTrees(syntaxTree);
var stream = new MemoryStream();
var emitResult = compilation.Emit(stream);
if (emitResult.Success)
{
stream.Seek(0, SeekOrigin.Begin);
var assembly = Mono.Cecil.AssemblyDefinition.ReadAssembly(stream);
assembly.Write(filename);
}
}
}
public interface ILanguageService
{
SyntaxTree ParseText(string code, SourceCodeKind kind);
Compilation CreateLibraryCompilation(string assemblyName, bool enableOptimisations);
}
public class CSharpLanguage : ILanguageService
{
private readonly IReadOnlyCollection<MetadataReference> _references = new[] {
MetadataReference.CreateFromFile(typeof(Binder).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(ValueTuple<>).GetTypeInfo().Assembly.Location)
};
private static readonly LanguageVersion MaxLanguageVersion = Enum
.GetValues(typeof(LanguageVersion))
.Cast<LanguageVersion>()
.Max();
public SyntaxTree ParseText(string sourceCode, SourceCodeKind kind)
{
var options = new CSharpParseOptions(kind: kind, languageVersion: MaxLanguageVersion);
// Return a syntax tree of our source code
return CSharpSyntaxTree.ParseText(sourceCode, options);
}
public Compilation CreateLibraryCompilation(string assemblyName, bool enableOptimisations)
{
var options = new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
optimizationLevel: enableOptimisations ? OptimizationLevel.Release : OptimizationLevel.Debug,
allowUnsafe: true);
return CSharpCompilation.Create(assemblyName, options: options, references: _references);
}
}
}