I use CSScriptLibrary.dll to execute C# code in my application which runs on both Windows and Linux. Problem is, right now, I need to use #pragma disable warning
to disable all kinds of warnings that may arise in order to get the scripts to compile on Mono which is a very ugly hack.
// the following simple script will not execute on Mono due to a warning that a is not used.
var code = "public class Script { public object Run() { var a=1; return 2+3; }}"
// here is how the script is executed using CsScriptLibrary
try
{
var asm = new AsmHelper(CSScript.LoadCode(code, "cs", null, true));
// if we reach that point, the script compiled
var obj = asm.CreateAndAlignToInterface<IScript>("*");
// now run it:
var result=obj.Run();
}
catch (CompilerException e)
{
// on .net compiler exceptions are only raised when there are errors
// on mono I get an exception here, even for warnings like unused variable
}
I already tried to set the default compiler parameters of CSScript to instruct the mono compiler to disregard warnings. Here is what I tried (based on documentation of compiler switches of Mono compiler:
CSScript.GlobalSettings.DefaultArguments = "-warn:0 -warnaserror-";
But I had no success and I am not even sure if this is the right way to go. Anyway, for the sake of completeness I note here that CSScript.GlobalSettings.DefaultArguments
defaults to /c /sconfig /co:/warn:0
in CSScript.
Does anyone know how to get CSScript.LoadCode
to disregard warnings on Mono or at least not treat them as errors?
Here are two solutions (found with help of Oleg Shilo). You can either include the desired compiler option directly in the script:
//css_co -warn:0
using System;
...
or you can substitute CSScript.LoadCode
with LoadWithConfig
, which allows passing compiler options directly. Something like this:
static public Assembly LoadCode(string scriptText, bool debugBuild, params string[] refAssemblies)
{
string tempFile = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() +".cs";
try
{
using (StreamWriter sw = new StreamWriter(tempFile))
sw.Write(scriptText);
return LoadWithConfig(scriptFile, null, debugBuild, CSScript.GlobalSettings, "-warn:0", refAssemblies);
}
finally
{
if (!debugBuild)
{
//delete temp file
}
}
}
It should be noted, that the second solution will bypass the built in assembly caching performed in LoadCode. It is easy enough to cache the compiled script object though.