Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to serialize a C# code block?

Tags:

I'm using C# with .NET 3.5. Is it possible to serialize a block of code, transmit it somewhere, deserialize it, and then execute it?

An example usage of this would be:

Action<object> pauxPublish = delegate(object o) {     if (!(o is string))     {         return;     }     Console.WriteLine(o.ToString()); }; Transmitter.Send(pauxPublish); 

With some remote program doing:

var action = Transmitter.Recieve(); action("hello world"); 

My end goal is to be able to execute arbitrary code in a different process (which has no prior knowledge of the code).

like image 326
NoizWaves Avatar asked Dec 06 '08 09:12

NoizWaves


People also ask

What is serialization in C?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

How do I make my AC class serializable?

The easiest way to make a class serializable is to mark it with the SerializableAttribute as follows. The following code example shows how an instance of this class can be serialized to a file. MyObject obj = new MyObject(); obj. n1 = 1; obj.

Can we serialize static class?

In Java, serialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI). But, static variables belong to class therefore, you cannot serialize static variables in Java.

Can you serialize a List C#?

C# Serialize ListSerialize a List with the Serializable attribute. List, serialize. In C# programs we often need to read and write data from the disk. A List can be serialized—here we serialize (to a file) a List of objects.


1 Answers

YES!!!

We have done this for a very real case of performance. Doing this at runtime or using a DSL was not an option due to performance.

We compile the code into an assembly, and rip the IL out of the method. We then get all the metadata associated with this method and serialize the whole mess via XML, compress it, and put it in our database.

At re-hydration time, we re-constitute the IL with the metadata using the DynamicMethod class, and execute it.

We do this because of speed. We have thousands of little blocks of code. Unfortunately, to compile a block of code and run it on the fly takes at least 250 ms, which is way too slow for us. We took this approach, and it is working REALLY well. At run-time, it takes an unmeasurable amount of time to reconstitute the method and run it.

Only thing to keep an eye on... Signed assemblies and Unsigned assemblies cannot mix the serialized method data.

like image 56
Brian Genisio Avatar answered Oct 04 '22 11:10

Brian Genisio