GithubHelp home page GithubHelp logo

oleg-shilo / cs-script Goto Github PK

View Code? Open in Web Editor NEW
1.6K 1.6K 230.0 57.48 MB

C# scripting platform

Home Page: http://www.cs-script.net

License: MIT License

C# 96.10% Batchfile 0.55% Makefile 0.07% PowerShell 0.17% Shell 0.14% HTML 1.99% JavaScript 0.67% CSS 0.32%

cs-script's People

Contributors

alfish2000 avatar burberger avatar hugoross avatar husk3r avatar jasonauk avatar jfevia avatar jtone123 avatar lbs-contributor avatar ljpung avatar oleg-shilo avatar reprogroup avatar rzamponiatigt avatar stephenriddell avatar taras-au avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cs-script's Issues

Faster loading scripts?

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?

Feature request to support conditional directives

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

.config file missing in installer

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

It should be possible to disable injection of script AssemblyAttribute

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.

  • The settings that enables/disables it is not publicly exposed.
  • The assembly attribute is injected even for LoadCode use cases. What is not useful at all the stored path is a temp (artificial) script file.

ASP Core with net461 framework got System.IO.FileLoadException

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"
  }

Ability to timeout scripts

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.

Using wide wildcards in //css_inc can be improved

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.

How to enable unsafe code

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

Error while compiling related to environment block

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)

Request to support compiler options for CSScript.Load() and CSScript.LoadFile()

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.

Missing Source File

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.

LoadCode call leaves empty temp directories

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.

AsmHelper does not 'deleteOnExit' and keeps a reference to the assembly in case an invoked method throws

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:

  • 'deleteOnExit' does not happen.
  • The AsmHelper seems to keep a reference to the assembly file (.dll), as a consequence, the assembly file cannot be deleted (by the application or Cmd or Windows Explorer or ...).

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.

Custom CS-Script file extension for simple double-click execution of scripts.

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.

Suggestion for minor improvement in AsmHelper.Invoke()

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:

  • bei System.Object.GetType()
  • bei CSScriptLibrary.AsmBrowser.MethodSignature..ctor(String name, Object[] args)
  • 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 MyProject.MyMethod in MyWorkspace\MyFile

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.

Problem with System.Data Reference in Script.

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.

Is there a way to specify the working directory for a script?

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.

Feature request to support .resx compilation and embedding intrinsically

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:

  1. A form (e.g. MyForm, derived from System.Windows.Forms.Form) is created using the Visual Studio designer. Some kind of resource is added to the form, e.g. an image or a long string, resulting in MyForm.resx and MyProject\Properties\Resources.resx files created by the designer.
  2. The form shall be referenced/loaded by a css script, by //css_import .\MyForm.cs; and //css_import .\MyForm.Designer.cs; (which currently results in a "MissingManifestResourceException was unhandled by user code" due to the missing resource file). The designer generated .resx file shall be referenced directly, without the need to first compile it to a .resource file.

Rationale/background info:

  • Designer generated forms shall be usable by scripts, without the need to first compile the .resx file.
  • Generating the .resource file by res.cs technically works, but...
    • ...requires a script user to perform two steps, and...
    • ...requires to either install the CSScript extensions, just res.cs, or a clone of that script at the user's machine. This prevents use cases where an application (MyApp.exe) embeds CSScriptLibrary.v<x.y>.dll and provides script functionality to some (dummy) user of the application, who does not need to know the very details of CSScript, and does not need to install CSScript and the CSScript extensions at his target machine.

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

ICodeCompiler is obsolete

[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?

Can't open project in visual studio after performing upgrade to latest hotfix

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.

Neither AsmHelper nor Compiling provides the additional directories specified by //css_searchdir

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

Persistent Caching Bug

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

Issues with caching

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:

Issue 1 (CacheEnabled)

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.

Issue 2 (CacheEnabled)

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.

Issue 3 (CacheEnabled)

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)

By the way

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

CSScript.ShareHostRefAssemblies issues

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?

CodeCom Evaluator gets slower after many LoadCode iterations

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:

  • EvaluatorConfig.Access = EvaluatorAccess.AlwaysCreate
  • LoadCode is used, not LoadCodeRemotely to load the assembly in a separate AppDomain

The events leading up to this behavior are:

  • When the CodeComEvaluator is cloned, all assemblies in the current AppDomain are referenced.
    (happens in the Reset(true) call in the CodeComEvaluator ctor)
  • Because all assemblies up to iteration N-1 are already in the current AppDomain,
    all of these assemblies will be referenced on iteration N.
  • The eventual call to Microsoft.CSharp.CSharpCodeGenerator.CompileAssemblyFromFileBatch,
    will have all of these assemblies in compilerParams.ReferencedAssemblies, leading to slower
    compilation

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

using css_reference for interop service

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](IEnumerable1 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

Linux requires -c switch

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

Suggestion for minor improvement in ScriptParser..ctor()

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:

  • bei csscript.Utils.Concat(String[] array1, String item)
  • bei CSScriptLibrary.FileParser..ctor(String fileName, ParsingParams prams, Boolean process, Boolean imported, String[] searchDirs, Boolean throwOnError)
  • bei CSScriptLibrary.ScriptParser.Init(String fileName, String[] searchDirs)
  • bei CSScriptLibrary.ScriptParser..ctor(String fileName)

I guess you are always using 'searchDirs', so ScriptParser..ctor(String fileName) is never called and this case never occurs.

No way to install extension pack using chocolatey

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.

Linux,css_inc XXXX.cs or css_import XXXX.cs error.....

run css_config.exe is error!
qq 20161104191007
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();
}
}
}
qq 20161104191429

Renamed assembly is still called CSScriptLibrary.v3.5

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.)

Deprecation in wsdl.cs

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?

Inconsistent time stamp (.dll -vs- .pdb) when using CSScript.CompileFile() with 'debugBuild = true'

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.

Mono.CSharp.InternalErrorException in a simple script

  1. Create a new Console project

  2. Install CS-Script.bin NuGet package (3.19.0)

  3. 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.

Enhancement: Have a way to import all the script files in a directory.

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

how encrypt script?

welcome to git,I watch you on codeplex long time,I have a question about:how encrypt script?

Auto-class decoration algorithm improvements

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).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.