Search code examples
c#serializablebinaryformattercsharpcodeprovider

How to compile a serializable object at runtime using C# CSharpCodeProvider and BinaryFormatter


So,

I have the following code as text:

using digitracktest.DigiTrack.CoreLogic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Runtime.Serialization;

namespace EntityModels
{
    [Serializable()]
    public class ActionInstance : IAction
    {
        private string _id;

        public string id {
            get { return _id; }
            set { _id = value; }
        }

        public void execute()
        {
            //Rest of the codes
        }
    }
}

I would like to compile the above code at runtime using CSharpCodeProvider.

And below is how I compile:

    CSharpCodeProvider provider = new CSharpCodeProvider();
    CompilerParameters parameters = new CompilerParameters();

    parameters.ReferencedAssemblies.Add("System.dll");
    parameters.ReferencedAssemblies.Add("System.Core.dll");
    parameters.ReferencedAssemblies.Add("mscorlib.dll");

    parameters.GenerateInMemory = false; // True - memory generation, false - external file generation
    parameters.GenerateExecutable = false; // True - exe file generation, false - dll file generation


    CompilerResults results = provider.CompileAssemblyFromSource(parameters, a.src);
    _CompileResults = results;

    if (results.Errors.HasErrors)
    {
        List<string> errors = new List<string>();
        results.Errors.Cast<CompilerError>().ToList().ForEach(error => errors.Add(error.ErrorText));

        return new { isSuccess = false, errors = errors };
    }
    else
    {
        Assembly assembly = results.CompiledAssembly;
        IAction act = (IAction)assembly.CreateInstance("EntityModels.ActionInstance");
        act.id = a.actionId;

        Stream stream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/a/") + a.id + ".dat", FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
        BinaryFormatter serializer = new BinaryFormatter();
        serializer.Serialize(stream, a);
        stream.Close();

        return new { isSuccess = true };
    }

The issue is that after compilation, I need to serialize it using BinaryFormatter and save it to file.

Although I already marked the class with Serializable tag, I keep getting the error below:

Type 'EntityModels.ActionInstance' in Assembly '3k0rfezm, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

I don't really know how to proceed from here. Unfortunately the CSharpCodeProvider and BinaryFormatter are part of the requirements. Any help is really appreciated.

Cheers!


Solution

  • I found the culprit!

    Apparently, since I call this compile method in a loop, apparently there are old blueprint codes that I haven't marked as [Serializable()] yet. This resulted in some object compiled with no Serializable mark. I checked by:

    Type x = act.GetType();
    
    Console.WriteLine("Is Object Serializable: " + x.IsSerializable);
    

    and some of them returned false.

    Hope this helps someone somewhere someday as well.

    Cheers!