tags:

views:

786

answers:

2

I got a little problem I can't figure out. I have a server side MarshalByRefObject that I'm trying to wrap a transparent proxy around on the client side. Here's the setup:

public class ClientProgram {
    public static void Main( string[] args ) {
        ITest test = (ITest)Activator.GetObject( typeof( ITest ), "http://127.0.0.1:8765/Test.rem" );
        test = (ITest)new MyProxy( test ).GetTransparentProxy();
        test.Foo();
    }
}

public class MyProxy : RealProxy {

    private MarshalByRefObject _object;

    public MyProxy( ITest pInstance )
        : base( pInstance.GetType() ) {
        _object = (MarshalByRefObject)pInstance;
    }

    public override IMessage Invoke( IMessage msg ) {
        return RemotingServices.ExecuteMessage( _object, (IMethodCallMessage)msg );
    }
}

The problem is that the call to RemotingServices.ExecuteMethod, an exception is thrown with the message "ExecuteMessage can be called only from the native context of the object.". Can anyone point out how to get this to work correctly? I need to inject some code before and after the method calls on remote objects. Cheers!

A: 

I did that a while ago and forgot exact procedure, but try using RemotingServices.GetRealProxy to get proxy from test object and pass this into your MyProxy and call invoke on it.

Something like this:

ITest test = (ITest)Activator.GetObject( typeof( ITest ), "http://127.0.0.1:8765/Test.rem" );
RealProxy p2 = RemotingServices.GetRealProxy(test)
test = (ITest)new MyProxy( p2 ).GetTransparentProxy();
test.Foo();

You'll have to update MyProxy class to work with RealProxy insted of direct class

bh213
+1  A: 

Got it. your comment put me on the right track. The key is to unwrap the proxy and call invoke on it. THANK YOU!!!!!

public class ClientProgram { public static void Main( string[] args ) { ITest test = (ITest)Activator.GetObject( typeof( ITest ), "http://127.0.0.1:8765/Test.rem" ); ITest test2 = (ITest)new MyProxy( test ).GetTransparentProxy(); test2.Foo(); } }

public class MyProxy : RealProxy {

    private object _obj;

    public MyProxy( object pObj )
        : base( typeof( ITest ) ) {
        _obj = pObj;
    }

    public override IMessage Invoke( IMessage msg ) {
        RealProxy rp = RemotingServices.GetRealProxy( _obj );
        return rp.Invoke( msg );
    }
}