Using C # as a Scripting Language for a C # Application

I developed an application that uses C # script files for specific configurations and settings. The script file contains various objects created by the user and specific functions for these objects. Currently, the user must generate the .cs file using a third-party editor and specify the path to my program in order to use it. The disadvantage of this method is that the user does not have the flexibility to support Auto-complete and intellisense-esque when editing script files.

I want to insert the editing part of the script into my application. I can do this using the rich text editor. But autocomplete coding is a huge pain. Is there a way that I can provide the user with an editor in the program that also automatically terminates.

Code to compile a script dynamically in a program.

public String Compile(String inputfilepath) { CompilerResults res = null; CSharpCodeProvider provider = new CSharpCodeProvider(); String errors = ""; if (provider != null) { try { Assembly asb = Assembly.Load("BHEL.PUMPSDAS.Datatypes, Version=1.0.0.0, Culture=neutral, PublicKeyToken=81d3de1e03a5907d"); CompilerParameters options = new CompilerParameters(); options.GenerateExecutable = false; options.OutputAssembly = String.Format(outFileDir + oName); options.GenerateInMemory = false; options.TreatWarningsAsErrors = false; options.ReferencedAssemblies.Add("System.dll"); options.ReferencedAssemblies.Add("System.Core.dll"); options.ReferencedAssemblies.Add("System.Xml.dll"); options.ReferencedAssemblies.Add("System.Xml.dll"); options.ReferencedAssemblies.Add(asb.Location); res = provider.CompileAssemblyFromFile(options, inputfilepath); errors = ""; if (res.Errors.HasErrors) { for (int i = 0; i < res.Errors.Count; i++) { errors += "\n " + i + ". " + res.Errors[i].ErrorText; } } } catch (Exception e) { throw (new Exception("Compilation Failed with Exception!\n" + e.Message + "\n Compilation errors : \n" + errors + "\n")); } } return errors; } 
+7
source share
1 answer

In particular, for autocompletion you need to use two systems: parser and reflection.

Parser is a pretty simple concept, theoretically, but I'm sure that writing in a language with such syntactic sugar and with as many context-sensitive keywords as C # will not be easy.

Since .NET is inherently reflective and provides a reflection structure, this part also should not be incredibly painful. Reflection allows you to manipulate object-oriented elements that contain compiled assemblies β€” and the assemblies themselves β€” as objects. For example, a method will be a Method object. You can peer into this system by examining the members of the Type class, which provide one basic starting point for reflection. Another useful starting point is Assembly . MSDN , as usual, has rich β€œofficial” information in a structured format.

+2
source

All Articles