Assembly CompileFromSource(CodeDomProvider provider, string searchPattern)
{
var compilerParameters = new CompilerParameters();
compilerParameters.GenerateExecutable = false;
// Necessary for stack trace line numbers etc
compilerParameters.IncludeDebugInformation = true;
compilerParameters.GenerateInMemory = false;
#if RELEASE
if(!compilationParameters.ForceDebugInformation)
{
compilerParameters.GenerateInMemory = true;
compilerParameters.IncludeDebugInformation = false;
}
#endif
if(!compilerParameters.GenerateInMemory)
{
var assemblyPath = Path.Combine(PathUtils.TempFolder, string.Format("CompiledScripts_{0}.dll", searchPattern.Replace("*.", "")));
if(File.Exists(assemblyPath))
{
try
{
File.Delete(assemblyPath);
}
catch(Exception ex)
{
if(ex is UnauthorizedAccessException || ex is IOException)
assemblyPath = Path.ChangeExtension(assemblyPath, "_" + Path.GetExtension(assemblyPath));
else
throw;
}
}
compilerParameters.OutputAssembly = assemblyPath;
}
var scripts = new List<string>();
var scriptsDirectory = PathUtils.ScriptsFolder;
if(Directory.Exists(scriptsDirectory))
{
foreach (var script in Directory.GetFiles(scriptsDirectory, searchPattern, SearchOption.AllDirectories))
scripts.Add(script);
}
else
Debug.LogAlways("Scripts directory could not be located");
CompilerResults results;
using(provider)
{
var referenceHandler = new AssemblyReferenceHandler();
compilerParameters.ReferencedAssemblies.AddRange(referenceHandler.GetRequiredAssembliesFromFiles(scripts));
results = provider.CompileAssemblyFromFile(compilerParameters, scripts.ToArray());
}
return ScriptCompiler.ValidateCompilation(results);
}