oleg-shilo / cs-script Goto Github PK
View Code? Open in Web Editor NEWC# scripting platform
Home Page: http://www.cs-script.net
License: MIT License
C# scripting platform
Home Page: http://www.cs-script.net
License: MIT License
Hi Oleg,
Another thing I encountered (related to issue #24):
Resources are built into \obj\Debug or \obj\Release or other directories, depending on the build configurations of a project. Thus, a script using these resources must be able to choose among the directories. This could be achieved as follows:
#if (DEBUG)
//css_resource ..\obj\Debug\MyProject.Properties.Resources.resources;
//css_resource ..\obj\Debug\MyProject.MyForm.resources;
#else
//css_resource ..\obj\Release\MyProject.Properties.Resources.resources;
//css_resource ..\obj\Release\MyProject.MyForm.resources;
#endif
Or:
//css_conditional_if(DEBUG)
//css_resource ..\obj\Debug\MyProject.Properties.Resources.resources;
//css_resource ..\obj\Debug\MyProject.MyForm.resources;
//css_conditional_else
//css_resource ..\obj\Release\MyProject.Properties.Resources.resources;
//css_resource ..\obj\Release\MyProject.MyForm.resources;
//css_conditional_endif
Or (following the .NET ConditionalAttribute):
//css_conditional(DEBUG) css_resource ..\obj\Debug\MyProject.Properties.Resources.resources;
//css_conditional(RELEASE) css_resource ..\obj\Release\MyProject.Properties.Resources.resources;
//css_conditional(DEBUG) css_resource ..\obj\Debug\MyProject.MyForm.resources;
//css_conditional(RELEASE) css_resource ..\obj\Release\MyProject.MyForm.resources;
Thanks & Best regards,
Matthias
As of mono 4.4 there's no way to use named mutexes on linux (it used to be disabled by default but could be enabled using MONO_ENABLE_SHM). The cs-script caching mechanism depends on this functionality so therefore is broken.
Reference: https://bugzilla.xamarin.com/show_bug.cgi?id=39836
Unfortunately, it doesn't appear .NET Core will help any time soon:
Will .NET core will be supported?
When downloading the source and compiling, it complains:
Source file "C:\Ablage\cs-script-master\Source\Tests\Properties\AssemblyInfo.cs" was not found.
Probably this one is still missing.
//css_reference should support relative paths as //css_import and //css_resource are doing.
Rationale: Referencing an own .dll located in a different project/folder than the script itself.
Just installed through nuget into my solution and I can see it added also reference to Mono.CSharp. I don't use Mono at all. Does it have to be there?
Sequence:
try
{
helper = new AsmHelper(assemblyFilePath, "ScriptDomain", true);
scriptResult = (int)helper.Invoke(scriptMainMethod, new object[] { scriptStartArgs });
}
finally
{
if (helper != null)
helper.Dispose();
}
All works fine as long the scriptMainMethod() properly returns. However, in case that method throws, two things go wrong:
As a consequence, my hosting application cannot subsequently start a script that throws. In such case, the user has to exit the application and then start the script again. This is somewhat cumbersome.
I know this issue only occurs in case a script throws. Therefore I consider this issue low priority. Still this limitation is a bit annoying as it is hard to make people understand this and as it limits automated testing capabilities.
dir-
|- scriptC.cs
\- scriptD.cs
scriptA.cs
scriptB.cs
main.cs
Problem: if main.cs
includes scriptC.cs
containing //css *.cs, the scripts from the root directory will also be included (A and B). This is not a problem as such as the current directory has the highest priority when resolving wildcards and curr dir in this case is the root.
Though improvement can be make by dynamically substituting './' with the parent directory of the script containing the directive. Thus ./*.cs
will be converted into dir/*.cs
and *.cs
will remain the same.
LoadFiles is plenty fast but Load, CreateFunc, LoadMethod, LoadScript all seem very slow.
Wouldn't avoiding creating temporary files and also avoid creating an assembly file increase speed by a lot?
Auto-class decoration should allow conditional injection of using static dbg;
for transpaent use of Python-like print
:
//css_args -ac
using System;
using System.IO;
void main()
{
print(Directory.GetFiles(".", "*"));
}
The algorithm also need to detect class-full scripts and disable the decoration. This in urn will allow having the auto-class decoration enabled system wide (with -ac
switch).
Hi Oleg, sorry for requesting yet another thing, but I have gotten very motivated in significantly improving the CSScript's integration into my hosting application and have therefore extended the automated test environment. This has resulted in this very request.
I have created a bunch of test scripts that contain certain conditional code guarded with #if TEST. I need to load those scripts with and without "//css_co /define:TEST;\n", i.e. cannot place this into the scripts, but rather need specifying this when invoking CSScript.Load() or CSScript.LoadFile(). Unfortunately, this isn't directly possible and I have to read the file, prepend "//css_co /define:TEST;\n", save the file again, and then load it. Somewhat cumbersome.
I'd prefer if CSScript.Load() or CSScript.LoadFile() provided an additional parameter that allows specifying a list of additional compiler options. I agree this is kind of nice to have, I fully understand if this request is handled with low priority.
run css_config.exe is error!
i write a cs file,name is Builder.cs,and copy Builder.cs to inc path and lib path.
write a test.cs file:
//css_import Builder.cs
using System;
using Build.CppBuild;
namespace testDll
{
public class host
{
public static void Main(String[] d)
{
Console.WriteLine(CppModule.Version);
Console.ReadLine();
}
}
}
Hi Oleg,
There is one thing of #26 remaining, and I came to the conclusion that's because neither AsmHelper nor Compiling provides the additional directories specified by //css_searchdir. Here's the situation:
My test script 'RefTest.cs' references a library 'RefRedir.dll' using //css_reference. Now, that 'RefRedir.dll' references another assembly located in a different folder. Of course this cannot work, how shall .NET find that folder when loading the assemblies. To fix this, I have added the assembly's folder to the top-level 'RefTest.cs' script, using //css_searchdir, assuming that either AsmHelper or Compiling would detect the additional directories. But it seems that neither does, or at least doesn't provide this information.
I am pretty sure that either AsmHelper or Compiling actually parses the //css_searchdir directive. Could you pass that information to either AsmHelper.ProbingDirs or CompilingInfo? Thanks.
Best regards,
Matthias
Chocolatey seems to be the current recommended means of installing cs-script, but as far as I can tell installing it that way does not include the extension pack and there is currently no way, using chocolatey commands, to get the extension pack.
The workaround is simple, download the extension pack from the releases page here on github and extract the archive to your chocolatey install location (most likely C:\ProgramData\chocolatey\lib\cs-script\tools\cs-script).
But, in order to make things a little easier for others, I'd suggest that either the main choco installer should install the extension pack, or there should be a second chocolately package with the extension pack, or there should at least be a note in the releases page (and in the package desc on chocolately's website) explaining how to get the extension pack.
Personally, I find it super useful to be able to easily specify that a given script should always run elevated by adding "//css_pre elevate()" at the beginning, which is my main use for the extension pack since it gives you the elevate library.
Hi,
I have a problem when using :
"//css_reference System.Runtime.InteropServices.dll;"
or simply "using System.Runtime.InteropServices; "
the compiler doesn't recognize this struct and throw an error.
[StructLayout(LayoutKind.Explicit, Size =64 )] public struct asteckMaterialVertexConstants { [FieldOffset(0)] public Matrix ViewProj; }
error :
(12,9): error CS0589: Internal compiler error during parsingSystem.ArgumentNullException: Value cannot be null. Parameter name: source at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable
1 source, Func2 predicate) at Mono.CSharp.Undo.AddTypeContainer(TypeContainer current_container, TypeDefinition tc) at Mono.CSharp.CSharpParser.push_current_container(TypeDefinition tc, Object partial_token) at Mono.CSharp.CSharpParser.case_104() at Mono.CSharp.CSharpParser.yyparse(yyInput yyLex) at Mono.CSharp.CSharpParser.parse()
Wondering if it's a bug or interop is not supported.
thanks
Hi,
is it possible to generate Xml Documention too?
Calling Process.GetProcessById throws if the process with the given id is not running.
cf.
https://github.com/oleg-shilo/cs-script/blob/master/Source/Utils.cs#L288
wrapping the call inside a try/catch block should do the trick...
Using the latest version 3.23.0.0, I get a warning/error in the "wsdl.cs" that ships within the extension pack:
Error: Specified file could not be compiled.
System.ApplicationException: Script \myserver\myshare\cs-script\lib\wsdl.cs cannot be executed. ---> csscript.CompilerException: \myserver\myshare\cs-script\lib\wsdl.cs(95,70): error CS0619: 'csscript.CSSEnvironment.PrimaryScriptFile' is obsolete: 'This member may not work correctly in the hosted and cached scenarios. Use alternative techniques demonstrated in the ReflectScript.cs sample.Including environment variable 'EntryScript' and AssemblyDescriptionAttribute (of the script assembly) containing the full path of the script file.'
The "wsdl.cs" file is back from 2009.
In addition, I am unable to locate the "wsdl.cs" file in your repository.
My question:
Can you please help me to get "wsdl.cs" working with the latest version of CS Script?
The injected attribute contains the path of the original script file being executed. Useful for debugging and troubleshooting.
The are a few minor problems associated with injection of script assembly attributes.
A NullReferenceException occurs when calling AsmHelper.Invoke() with a 'null' value (e.g. Invoke("MyProperty", someObj) where someObj unfortunately is 'null'). Stack trace:
System.NullReferenceException was caught
Message="Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt." ("object reference not set to an instance of an object")
Source="mscorlib"
StackTrace:
Server stack trace:
Instead of simply forwarding the values (resulting in that NullReferenceException) I suggest to check the arguments higher up in the call sequence and throw an ArgumentNullException with a more comprehensive error message instead.
Hey Guys,
I may be totally missing something, but it seems to me that persistent caching is broken if using any of the LoadCodeFrom methods. The first thing this method does is read all the code from the file and then save it to a temporary file whose name is based on a uuid.
Is there a reason for this?
Thanks,
Joey
When I try to add nuget package to ASP Core project with full .NET I receive exception:
An exception of type 'System.IO.FileLoadException' occurred in Microsoft.AspNetCore.Mvc.Razor.dll but was not handled in user code
Additional information: Could not load file or assembly 'Microsoft.CodeAnalysis, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
My configuration:
"frameworks": {
"net461": {
"dependencies": {
"Visiology.VA.DAL": {
"target": "project"
},
"Visiology.VA.DAL.CsDataService.Shared": {
"target": "project"
},
"Visiology.VA.DAL.Interfaces": {
"target": "project"
}
}
}
}
Dependencies:
"dependencies": {
"Autofac.Extensions.DependencyInjection": "4.0.0",
"CS-Script.bin": "3.18.1",
"Microsoft.AspNetCore.Mvc": "1.1.0",
"Microsoft.AspNetCore.Routing": "1.1.0",
"Microsoft.AspNetCore.Server.IISIntegration": "1.1.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.0",
"Microsoft.Extensions.Configuration.FileExtensions": "1.1.0",
"Microsoft.Extensions.Configuration.Json": "1.1.0",
"Microsoft.Extensions.Logging": "1.1.0",
"Microsoft.Extensions.Logging.Console": "1.1.0",
"Microsoft.Extensions.Logging.Debug": "1.1.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.0",
"MongoDB.Driver": "2.3.0",
"Serilog.Extensions.Logging": "1.3.1",
"Seterlund.CodeGuard": "2.3.4",
"SSH.NET": "2016.0.0"
}
The assembly \lib\Bin\NET 3.5\CSScriptLibrary.dll which got renamed from CSScriptLibrary.v3.5.dll unfortunately is still called "CSScriptLibrary.v3.5", e.g. see CSScriptLibrary.xml:
<assembly>
<name>CSScriptLibrary.v3.5</name>
</assembly>
As a consequence, compiling leads to "Assembly "CSScriptLibrary.v3.5, Version=3.20.0.0, Culture=neutral,...could not be loaded". Reverting the file name back to CSScriptLibrary.v3.5.dll works again.
Please fix the assembly's name, then build and release again, thanks!
(It's not urgent for me, I can live with reverting the file's name.)
As I understand a script loaded with CSScript.LoadCode
can access all host variables. For me it looks strange since I cannot control user activity. So I've found that setting CSScript.ShareHostRefAssemblies
to false forbids that. But I still want to pass to the script some custom object. Is that possible?
In order to install CSScript I had to manually addthe file css_config.exe.config
containing:
<configuration>
<runtime>
<loadFromRemoteSources enabled="true"/>
</runtime>
</configuration>
Please add it to the installer package to avoid errors
I downloaded cs-script today and when trying to build the project encountered an error caused by SystemWideLock.cs not being found.
The file is specified for compile in the csscript.csproj file, but not included anywhere in the download.
e.g.
public int field{get;set;}=48;
compile error.
I see a big danger with scripting, especially server side, that you can end up with a hosted script that goes into a loop and never completes. What we don't really want is the server to then need to be restarted.
Am I correct that there is no way to give a time limit to scripts using cs-script?
The only way that I can see of doing it would be to run the scripts on separate threads and then monitor them, which is probably fine server side but if you're working client-side you'd then get issues with the single-threaded nature of WinForms.
If there is no facility within cs-script then I guess I'll have to wrap my own "watchdog" processing around it.
All evaluators don't process "//css_ignore_namespace" when they invok ReferenceAssembliesFromCode. Though only with Mono compiler it leads to the script compile failure.
Have you considered supporting custom file extensions for CS-Script files? For example ".csexec" instead of ".cs"? That way CS-Scripts could be configured to automatically run when double clicked, instead of opening in Visual Studio.
It is easy enough for me to associate ".csexec" files on my system with your script engine, but then I lose all the CS-Script context menus such as "Open in Visual Studio", etc. It would be great to have the best of both worlds. I find it silly to always have to create batch files to make launching my CS-Scripts as painless as possible for myself and end-users in particular.
Hi Oleg,
I've realized a system that uses several db stored script to respond to events.
At the moment I have thirty different script that can be launched from a windows service.
Recently I'm having issues when the service tries to compile a script.
Once I got the exception on the first script, that can be a random one, all other script compilations fail with the same error.
If I then restart the service, for a while the script won't compile becausa they can't find the host service assemblies that are located in the bin.
I think the problem is related to the environment variabled added by csscript.
Can you give some advice about how to avoid this problem?
The error is:
System.InvalidOperationException: The environment block used to start a process cannot be longer than 65535 bytes. Your environment block is 65633 bytes long. Remove some environment variables and try again. at System.Diagnostics.EnvironmentBlock.ToByteArray(StringDictionary sd, Boolean unicode) at System.CodeDom.Compiler.Executor.ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, String cmd, String currentDir, TempFileCollection tempFiles, String& outputName, String& errorName, String trueCmdLine) at System.CodeDom.Compiler.Executor.ExecWaitWithCapture(SafeUserTokenHandle userToken, String cmd, String currentDir, TempFileCollection tempFiles, String& outputName, String& errorName, String trueCmdLine) at Microsoft.CSharp.CSharpCodeGenerator.Compile(CompilerParameters options, String compilerDirectory, String compilerExe, String arguments, String& outputFile, Int32& nativeReturnValue, String trueArgs) at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames) at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromFileBatch(CompilerParameters options, String[] fileNames) at csscript.CSExecutor.CompileAssembly(ICodeCompiler compiler, CompilerParameters compilerParams, String[] filesToCompile) at csscript.CSExecutor.Compile(String scriptFileName) at csscript.CSExecutor.Compile(String scriptFile, String assemblyFile, Boolean debugBuild) at CSScriptLibrary.CSScript.LoadWithConfig(String scriptFile, String assemblyFile, Boolean debugBuild, Settings scriptSettings, String compilerOptions, String[] refAssemblies) at CSScriptLibrary.CSScript.LoadCode(String scriptText, String tempFileExtension, String assemblyFile, Boolean debugBuild, String[] refAssemblies) at CSScriptLibrary.CodeDomEvaluator.CompileCode(String scriptText) at CSScriptLibrary.CodeDomEvaluator.LoadCode[T](String scriptText, Object[] args)
When temp script file generated by LoadCode is deleted (cleanup) the parent directory is not removed.
It is not a huge issue as the script engine periodically cleans these folders (if it isn't disabled). But it is a defect nevertheless.
Logged by mistake. There is no any problem with temp dirs. All temp files are created in a single common root.
The current CSScript mono evaluator does not support nested classes;
This is a consequence of the following mono issue: mono/mono#1058
This issue has been fixed by Mono, any plans to upgrade CSScript's mono lib?
Is there a way to import all script files in a directory?
I'd like to use a folder as a grouping mechanism for helper classes.
//css_dir ..\Shared;
//css_import BatchMethods;
//css_import BatchConstants;
//css_import SharedMethods;
...
It would be nice to be able to include all the files in "Shared"
From Oleg:
If you are hosting your script engine then it can be done very easy with dynamically composed includes script similarly to CS-Script "linq.includes.cs"
Though for stand alone script execution it's problematic.
I actually see this as a good (easy to implement) feature with syntax similar to this: //css_include *.cs
Derek:
That syntax looks good to me. It would be good to make sure it works with relative paths like:
//css_include ..\Shared*.cs
After installing Release v3.13.3.0 RC
When I right click a script file to do "Open in Visual Studio 2015"
I get similar results for 2013, etc.
csscript.CompilerException: c:\Dropbox\Installs\cs-script\lib\debugVS14.0.cs(1626,71): error CS1729: 'csscript.CSharpParser' does not contain a constructor that takes 2 arguments
at csscript.CSExecutor.ProcessCompilingResult(CompilerResults results, CompilerParameters compilerParams, ScriptParser parser, String scriptFileName, String assemblyFileName, String[] additionalDependencies)
at csscript.CSExecutor.Compile(String scriptFileName)
at csscript.CSExecutor.ExecuteImpl()
If I open visual studio 2015, and try to do "Open Script..." I get:
CS-Script cannot generate on-fly VS2010 project
I'm not 100% sure on the upgrade / removal process. I had installed previously with chocolatey, and then uninstalled with chocolatey. For the latest hotfix I just extrated into a folder and then ran the install batch file. I didn't make any changes the visual studio extension I had installed.
The time stamp of the compiled assembly file (.dll) is set to the time stamp of the original script file (.cs). I guess that behavior is intended (even if it's a bit surprising to find a .dll file that has just been compiled with a time stamp of e.g. last year...). So far so good.
However, the accompanying debug database file (.pdb, 'debugBuild = true') is set to the time stamp when the compilation took place. In my opinion, this is inconsistent. Both files should be set to the same time stamp if this is possible.
I'm trying to run a script that references an exe.
I put on fuslogvw to get some binding information. It doesn't look like it is trying to load the exe from the current folder in the command prompt.
C:\Users\Derek.Morin\Documents\Visual Studio 2010\Projects\ScriptCode\ScriptCode.ConvertedToC#\bin\x86\Debug>cscs /l "new script (3).cs"
C# Script execution engine. Version 3.18.0.0.
Copyright (C) 2004-2016 Oleg Shilo.
Error: Specified file could not be executed.
System.IO.FileNotFoundException: Could not load file or assembly 'ScriptCode, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
File name: 'ScriptCode, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
at Script.Main(String[] args)
Assembly manager loaded from: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
Running under executable C:\cs-script\cscs.exe
--- A detailed error log follows.
=== Pre-bind state information ===
LOG: DisplayName = ScriptCode, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
(Fully-specified)
LOG: Appbase = file:///C:/cs-script/
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: No application configuration file found.
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/cs-script/ScriptCode.DLL.
LOG: Attempting download of new URL file:///C:/cs-script/ScriptCode/ScriptCode.DLL.
LOG: Attempting download of new URL file:///C:/cs-script/ScriptCode.EXE.
LOG: Attempting download of new URL file:///C:/cs-script/ScriptCode/ScriptCode.EXE.
[I apologise in advance as this is the first time I have written on a github issue board so I may not be following the normal route for queries but I can find no alternative forum]
I am trying to integrate CSScript into a vb.net application. My application is the host application and will allow the user to create and edit scripts which the server side code will use to extend the application's functionality.
I want the user to have the option of writing C# or VB and I see from the help file with the downloaded binaries 3.4.1.2 that the code compile can be changed by including this code:
Public Class CSSCodeProvider
Public Shared Function CreateCompiler(ByVal sourceFile As String) As ICodeCompiler
Return New Microsoft.VisualBasic.VBCodeProvider().CreateCompiler()
End Function
End Class
However VS2013 flags this as an issue "ICodeCompiler is obsolete .... use CodeDomProvider".
Is this expected?
If the CodeCom Evaluator is used to compile N different scripts OR the CodeCom Evaluator is used with Caching disabled,
LoadCode becomes slower each iteration.
This can be seen from this xUnit test, created in a clone of the cs-script repo.
The preconditions for this behavior to occur are:
The events leading up to this behavior are:
This makes it hard to use CSScript.Evaluator.LoadCode in a server environment.
Is it "by design" that all previously dynamically compiled assemblies are referenced?
Are there any work-arounds for this behavior?
(other than using LoadCodeRemotely instead of LoadCode)
(other than using EvaluatorAccess.Singleton instead of EvaluatorAccess.AlwaysCreate)
Thanks for your time,
Koen
Ported from CodePlex: https://csscriptnpp.codeplex.com/discussions/660656
How I can add assembly reference with alias ? Some special syntax for css_reference ?
https://msdn.microsoft.com/ru-ru/library/ms173212.aspx
https://blogs.msdn.microsoft.com/ansonh/2006/09/27/extern-alias-walkthrough/
Hi Oleg,
As discussed via email, I request support for intrinsic .resx compilation and embedding. The support may be provided by css_resource/css_res or another css_... statement.
Use case/sequence:
Rationale/background info:
Suggested preferred solution:
//css_import .\MyForm.cs;
//css_import .\MyForm.Designer.cs;
//css_import .\MyForm.resx; => css_import automatically detects this as a resource and compiles and embeds it.
Suggested alternative solution:
//css_import .\MyForm.cs;
//css_import .\MyForm.Designer.cs;
//css_resource .\MyForm.resx; => css_resource compiles and embeds the resource.
Thanks & Best regards,
Matthias
A NullReferenceException occurs when ScriptParser..ctor() is invoked without a 'searchDirs' argument (i.e. new ScriptParser("MyScript.cs")). Stack trace:
System.NullReferenceException was unhandled by user code
Message="Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt." ("object reference not set to an instance of an object")
Source="CSScriptLibrary"
StackTrace:
I guess you are always using 'searchDirs', so ScriptParser..ctor(String fileName) is never called and this case never occurs.
Hi Oleg,
I have ran into some issues when invoking scripts in parallel, i.e. multiple processes that refer (and therefore try to compile and load) to the same assembly. With CSScript.CacheEnabled = false
I obviously run into an issue, since one instance may re-compile an assembly in the very moment another instance tries to re-compile or load it, so going without cache makes no sense. However, with CSScript.CacheEnabled = true
I also run into several issues:
When developing, the cache probing algorithm fails to detect that my hosting application's assemblies became newer and the script must therefore me rebuilt (in order to update the references to the latest hosting application assemblies):
The script in question has e.g. been edited at 10:00 in the morning. Thus, CSScript assumes that nothing needs to be re-compiled, after all, an up-to-date assembly of the script in question can be retrieved from the cache.
However, I am working at my hosting application, thus it's assemblies get e.g. built at 15:00 in the afternoon.
As a result, there is a mismatch among the hosting applications assembly versions and the .NET runtime throws:
System.IO.FileNotFoundException: Die Datei oder Assembly "MyHostingAppAssembly, Version=1.10.6276.25669, Culture=neutral, PublicKeyToken=37469a15c42ef9cb" oder eine Abhängigkeit davon wurde nicht gefunden. Das System kann die angegebene Datei nicht finden.
Stack:
bei System.Signature._GetSignature(SignatureStruct& signature, Void* pCorSig, Int32 cCorSig, IntPtr fieldHandle, IntPtr methodHandle, IntPtr declaringTypeHandle)
bei System.Signature..ctor(RuntimeMethodHandle methodHandle, RuntimeTypeHandle declaringTypeHandle)
bei System.Reflection.RuntimeMethodInfo.get_Signature()
bei System.Reflection.RuntimeMethodInfo.FetchNonReturnParameters()
bei System.Reflection.RuntimeMethodInfo.GetParametersNoCopy()
bei System.RuntimeType.FilterApplyMethodBaseInfo(MethodBase methodBase, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes)
bei System.RuntimeType.GetMethodCandidates(String name, BindingFlags bindingAttr, CallingConventions callConv, Type[] types, Boolean allowPrefixLookup)
bei System.RuntimeType.GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConv, Type[] types, ParameterModifier[] modifiers)
bei System.Type.GetMethod(String name, Type[] types)
bei CSScriptLibrary.AsmBrowser.FindMethod(String methodName, Type[] args)
bei CSScriptLibrary.AsmBrowser.FindMethod(String methodName, Object[] list)
bei CSScriptLibrary.AsmBrowser.Invoke(Object obj, String methodName, Object[] list)
bei CSScriptLibrary.AsmBrowser.Invoke(String methodName, Object[] list)
bei CSScriptLibrary.AsmRemoteBrowser.Invoke(String methodName, Object[] list)
bei System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
bei System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext)
Exception rethrown at [0]:
bei System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
bei System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
bei CSScriptLibrary.IAsmBrowser.Invoke(String methodName, Object[] list)
bei CSScriptLibrary.AsmHelper.Invoke(String methodName, Object[] list)
bei MyHostingApp.ScriptRunner.InitializeAssembly(AsmHelper helper, String scriptParentProperty) in MySolution\ScriptRunner.cs:Zeile 606.
There are moments when the CSScript.LastCompilingResult
becomes null
and one of the parallel instances will throw a System.NullReferenceException
when trying to access it. It seems that CSScript.LastCompilingResult
or one of its underlying dependencies is not multi-process capable. I guess that it's caused by the fact that some time passes between CSScript.CompileFile()
and accessing CSScript.LastCompilingResult
. In case another process invokes CSScript.CompileFile()
in the meantime, something obviously goes wrong.
There sometimes happens an IOException
"process cannot access the file … because in use by another process" in csscript.MetaDataItems.StampFile()
:
System.IO.IOException: Der Prozess kann nicht auf die Datei "MyTestScriptFolder\LocalUserSettings\TcpAutoSocketTerminalPair.dll" zugreifen, da sie von einem anderen Prozess verwendet wird.
bei System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
bei System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
bei System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
bei System.IO.FileStream..ctor(String path, FileMode mode)
bei csscript.MetaDataItems.StampFile(String file)
CSScript.IsOutOfDateAlgorithm states that default implementation is <see cref="CSScriptLibrary.CSScript.CachProbing.Simplified"/>
, but the static property is actually set to isOutOfDateAlgorithm = CachProbing.Advanced
, so this comment is outdated. (Note that the release notes of v3.6.0 IsOutOfDateAlgorithm set to CachProbing.Advanced by default
are correct.)
So I'm somewhat stuck. Disabling the cache leads to issues, as enabling it does. Any ideas on how to solve this?
Thanks,
Matthias
Create a new Console project
Install CS-Script.bin NuGet package (3.19.0)
Paste this code to reproduce the exception:
using CSScriptLibrary;
public interface ITest
{
void Main(string[] args);
}
class Program
{
static void Main(string[] args)
{
CSScript.Evaluator.LoadCode<ITest>(@"
public class FooScript : ITest
{
public void Main(string[] args)
{
return;
bool foo = true;
switch (args[0])
{
case ""blah"":
foo = false;
break;
}
System.Console.WriteLine(foo);
}
}
");
}
}
This results in a Mono.CSharp.InternalErrorException
.
The program is a little weird, admittedly. Removing any part of it makes the exception go away. The original code made more sense; I'm debugging a script and inserting a "return" halfway through some code. The fact that I can't execute that is a problem.
Warning that occurs when building the distributable of my application hosting CSScriptLibrary.v.3.5.dll. This warning did not occur with v3.3.0 / v3.3.5.0 but occurs now with v3.19.0 / v3.19.0.0. Looks like there is some undesirable dependency in CSScriptLibrary.v.3.5.dll.
If I use the Version 3.14.0 with the following sample I get an exception on evaluate.
try
{
dynamic script = CSScript.Evaluator
.LoadCode(@"using System;
using System.Data;
public class Update_DatabaseViews
{
public void Excute( IDbConnection databaseConnection)
{
}
}
");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
The Exception ist:
System.BadImageFormatException
Die Datei oder Assembly "file:///C:\WINDOWS\Microsoft.Net\assembly\GAC_32\System.Data\v4.0_4.0.0.0__b77a5c561934e089\System.Data.dll" oder eine Abhängigkeit davon wurde nicht gefunden. Es wurde versucht, eine Datei mit einem falschen Format zu laden.
This only happens, when I set the CompileOptions to x64. With AnyCPU and x86 everything works fine.
omitting the -c switch on linux leads to the following error:
C# Script execution engine. Version 3.14.1.0.
Copyright (C) 2004-2016 Oleg Shilo.
Error: Specified file could not be executed.
System.IO.FileNotFoundException: Could not load file or assembly 'cscs, Version=3.14.1.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies
File name: 'cscs, Version=3.14.1.0, Culture=neutral, PublicKeyToken=null'
Server stack trace:
at (wrapper managed-to-native) System.Reflection.Assembly:LoadFrom (string,bool)
at System.Reflection.Assembly.LoadFrom (System.String assemblyFile, System.Security.Policy.Evidence securityEvidence) [0x00000] in :0
at System.Activator.CreateInstanceFromInternal (System.String assemblyFile, System.String typeName, System.Boolean ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Object[] args, System.Globalization.CultureInfo culture, System.Object[] activationAttributes, System.Security.Policy.Evidence securityInfo) [0x00000] in :0
at System.Activator.CreateInstanceFrom (System.String assemblyFile, System.String typeName, System.Boolean ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Object[] args, System.Globalization.CultureInfo culture, System.Object[] activationAttributes) [0x00000] in :0
at System.Activator.CreateInstanceFrom (System.String assemblyFile, System.String typeName, System.Object[] activationAttributes) [0x00000] in :0
at System.Activator.CreateInstanceFrom (System.String assemblyFile, System.String typeName) [0x00000] in :0
at System.AppDomain.CreateInstanceFrom (System.String assemblyFile, System.String typeName) [0x00011] in :0
at (wrapper remoting-invoke-with-check) System.AppDomain:CreateInstanceFrom (string,string)
at System.AppDomain.CreateInstanceFromAndUnwrap (System.String assemblyName, System.String typeName) [0x00000] in :0
at (wrapper remoting-invoke-with-check) System.AppDomain:CreateInstanceFromAndUnwrap (string,string)
at (wrapper xdomain-dispatch) System.AppDomain:CreateInstanceFromAndUnwrap (object,byte[]&,byte[]&,string,string)
Exception rethrown at [0]:
at (wrapper xdomain-invoke) System.AppDomain:CreateInstanceFromAndUnwrap (string,string)
at (wrapper remoting-invoke-with-check) System.AppDomain:CreateInstanceFromAndUnwrap (string,string)
at csscript.AssemblyExecutor..ctor (System.String fileNname, System.String domainName) [0x0008e] in :0
at csscript.CSExecutor.ExecuteImpl () [0x006bb] in :0
Looks like we still need 3.15.1.0 on choco.
welcome to git,I watch you on codeplex long time,I have a question about:how encrypt script?
Hello,
I am trying to use the unsafe code in CS script, such code:
unsafe public static double fittingFunction(IntPtr data, Intptr para)
{
double* input = (double*)data.ToPointer(); double* variable = (double*)para.ToPointer();
double x = input[0];//x coordinate
double y = input[1]; // y coordinate
double A = variable [0];//Amplitude
double x0 = variable [1]; // x center
double y0 = variable [2]; // y center
double sigmalX = variable [3];
double sigmalY = variable [4];
return A * Math.Exp( -((x - x0) * (x - x0) / (sigmalX * sigmalX) + ((y - y0) * (y - y0)) / (sigmalY * sigmalY))/2);
}
I use CSScript.Evaluator.CreateDelegateAsync(sourceText) to get the compile result, but it says the unsafe code is not allowed:
error cs0227: unsafe code requires the `unsafe' command line option to be specified.
Could you please instruct me how to walk around this issue? I know for C# there is any option in project properties. But I have no idea how to specify that for CSS. Thanks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.