Unable to cast transparent proxy in a dll when called from PowerShell, but successful in C# console app Unable to cast transparent proxy in a dll when called from PowerShell, but successful in C# console app powershell powershell

Unable to cast transparent proxy in a dll when called from PowerShell, but successful in C# console app


I had the same problem: I created sandbox with Execute only permissions (the min one can have) to execute untrusted code in very restricted environment. All worked great in C# application, but did not work (the same cast exception) when starting point was vbs script creating .NET COM object. I think PowerShell also uses COM. I found workaround using AppDomain.DoCallBack, which avoids getting proxy from the appdomain. This is the code.If you find a better option, please post. Registering in GAC is not a good solution for me...

    class Test    {        /*         create appdomain as usually        */        public static object Execute(AppDomain appDomain, Type type, string method, params object[] parameters)        {            var call = new CallObject(type, method, parameters);            appDomain.DoCallBack(call.Execute);            return call.GetResult();        }    }    [Serializable]    public class CallObject    {        internal CallObject(Type type, string method, object[] parameters)        {            this.type = type;            this.method = method;            this.parameters = parameters;        }        [PermissionSet(SecurityAction.Assert, Unrestricted = true)]        public void Execute()        {            object instance = Activator.CreateInstance(this.type);            MethodInfo target = this.type.GetMethod(this.method);            this.result.Data = target.Invoke(instance, this.parameters);        }        internal object GetResult()        {            return result.Data;        }        private readonly string method;        private readonly object[] parameters;        private readonly Type type;        private readonly CallResult result = new CallResult();        private class CallResult : MarshalByRefObject        {            internal object Data { get; set; }        }    }


It sounds very much like a loading context issue. Type identity isn't just about the physical assembly file; it's also about how and where it was loaded. Here's an old blog post from Suzanne Cook that you'll probably have to read fifteen times until you can begin to make sense of your problem.

Choosing a Binding Context

http://blogs.msdn.com/b/suzcook/archive/2003/05/29/57143.aspx

Before you say "but it works in a console app," remember that when running it from powershell, you have an entirely different kettle of fish as regards the calling appdomain's context, probing paths, identity etc.

Good luck!