OWASP O2 Platform Blog

Dynamically creating private/internal types and delegates (UserCallBack and AsyncStreamReader)

When trying to create a callback into Console.Out, I tried to create a instance of the internal class AsyncStreamReader (which has a dependency on the private delegate UserCallBack). This workded ok  (see code below), but it didn’t have the expected behaviour (I did get a call into the outputReadNotifyUser Lambda method, but it only happened once and there was no value in its text variable) .

I actually found a better way (see next blog post), but meanwhile here is an  example of how to use reflection to create instance of private types and delegates.

//Not currently working, but shows how to create a private Delegate and Type

var currentProcess = Processes.getCurrentProcess();
Action<string> outputReadNotifyUser =
                "outputReadNotifyUser: {0}".info(text);

var userCallBackType = PublicDI.reflection.getType("UserCallBack");
var userCallBack = Delegate.CreateDelegate(userCallBackType, outputReadNotifyUser, typeof(Action<string>).method("Invoke"));

var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream);
streamWriter.AutoFlush = true;

var oParams = new object[] { currentProcess,memoryStream, userCallBack , Encoding.UTF8};
var asyncStreamReader = PublicDI.reflection.getType("AsyncStreamReader");
var aSyncReader =  asyncStreamReader.ctors()[0].Invoke(oParams);


return "ok";
//using System.Text
//using System.IO
//using System.Diagnostics

November 25, 2011 Posted by | .NET, Reflection | 1 Comment