Share via

Dynamically Execute C# with Microsoft.CodeAnalysis.CSharp.Scripting is failing in .Net 5

Sambeet Das 1 Reputation point
2021-02-17T08:11:08.773+00:00

I have a requirement of executing a C# class in the string format and populate an object with the properties of that class. To achieve the requirement I was doing a POC and that's failed.

Following is the code for the same.

ScriptManager.cs

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSCodeExecuter
{
    public class ScriptManager
    {
        public void ExecuteScript<T>(string scriptId, ref T input)
        {
            try
            {
                string inputSript = GetStriptById(scriptId);
                var scriptOptions = ScriptOptions.Default;
                scriptOptions.AddReferences("CSCodeExecuter");

                Execute(inputSript, scriptOptions);
                var result = Execute("new ScriptedClass().input", scriptOptions);
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        private string GetStriptById(string id)
        {

            string csSript = @" public class ScriptedClass
            {
                public CSCodeExecuter.Model input {get;set;}
                public void ScriptedClass()
                {
                   {" + GetInternalScript() + @"}
                }
            }";

            return csSript;
        }

        private string GetInternalScript()
        {
            return "input.Id = \"1111\"; " + "input.Name = \"test\"; " + "input.Phone = \"1234567890\"; ";
        }


        private static ScriptState<object> scriptState = null;
        public static object Execute(string code, dynamic scriptOptions)
        {
            scriptState = scriptState == null ? CSharpScript.RunAsync(code).Result : scriptState.ContinueWithAsync(code).Result;

            if (scriptState.ReturnValue != null && !string.IsNullOrEmpty(scriptState.ReturnValue.ToString()))
                return scriptState.ReturnValue;
            return null;
        }
    }
}

***Model.CS***

namespace CSCodeExecuter
{
    public class Model
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Phone { get; set; }
    }
}
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.