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 »

  1. […] the usage of a MemoryStream in a way simular to how Console actually works (see O2 blog post Dynamically creating private/internal types and delegates (UserCallBack and AsyncStreamReader) ) , but a much easier way is to specify a TextWriter […]

    Pingback by API_ConsoleOut.cs – InProcess Capture of the Console Output « OWASP O2 Platform Blog | November 26, 2011 | Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: