I'm quite sure I'm missing some constraint or caveat somewhere, but here's my situation. Assume I have a class that I want to have a proxy for, like the following:
public class MyList : MarshalByRefObject, IList<string>
{
private List<string> innerList;
public MyList(IEnumerable<string> stringList)
{
this.innerList = new List<string>(stringList);
}
// IList<string> implementation omitted for brevity.
// For the sake of this exercise, assume each method
// implementation merely passes through to the associated
// method on the innerList member variable.
}
I want to create a proxy for that class, so that I can intercept method calls and perform some processing on the underlying object. Here is my implementation:
public class MyListProxy : RealProxy
{
private MyList actualList;
private MyListProxy(Type typeToProxy, IEnumerable<string> stringList)
: base(typeToProxy)
{
this.actualList = new MyList(stringList);
}
public static object CreateProxy(IEnumerable<string> stringList)
{
MyListProxy listProxy = new MyListProxy(typeof(MyList), stringList);
object foo = listProxy.GetTransparentProxy();
return foo;
}
public override IMessage Invoke(IMessage msg)
{
IMethodCallMessage callMsg = msg as IMethodCallMessage;
MethodInfo proxiedMethod = callMsg.MethodBase as MethodInfo;
return new ReturnMessage(proxiedMethod.Invoke(actualList, callMsg.Args), null, 0, callMsg.LogicalCallContext, callMsg);
}
}
Finally, I have a class that consumes the proxied class, and I set the value of the MyList member via reflection.
public class ListConsumer
{
public MyList MyList { get; protected set; }
public ListConsumer()
{
object listProxy = MyListProxy.CreateProxy(new List<string>() { "foo", "bar", "baz", "qux" });
PropertyInfo myListPropInfo = this.GetType().GetProperty("MyList");
myListPropInfo.SetValue(this, listProxy);
}
}
Now, if I try to use reflection to access the proxied object, I run into problems. Here is an example:
class Program
{
static void Main(string[] args)
{
ListConsumer listConsumer = new ListConsumer();
// These calls merely illustrate that the property can be
// properly accessed and methods called through the created
// proxy without issue.
Console.WriteLine("List contains {0} items", listConsumer.MyList.Count);
Console.WriteLine("List contents:");
foreach(string stringValue in listConsumer.MyList)
{
Console.WriteLine(stringValue);
}
Type listType = listConsumer.MyList.GetType();
foreach (Type interfaceType in listType.GetInterfaces())
{
if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(ICollection<>))
{
// Attempting to get the value of the Count property via
// reflection throws an exception.
Console.WriteLine("Checking interface {0}", interfaceType.Name);
System.Reflection.PropertyInfo propInfo = interfaceType.GetProperty("Count");
int count = (int)propInfo.GetValue(listConsumer.MyList, null);
}
else
{
Console.WriteLine("Skipping interface {0}", interfaceType.Name);
}
}
Console.ReadLine();
}
}
Attempting to call GetValue on the Count property via reflection throws the following exception:
An exception of type 'System.Reflection.TargetException' occurred in
mscorlib.dll but was not handled in user code
Additional information: Object does not match target type.
When attempting to get the value of the Count property, apparently the framework is calling down into System.Runtime.InteropServices.WindowsRuntime.IVector to call the get_Size method. I'm not understanding how this call fails on the underlying object of the proxy (the actual list) to make this happen. If I'm not using a proxy of the object, getting the property value works fine via reflection. What am I doing wrong? Can I even do what I'm trying to accomplish?
Edit: A bug has been opened regarding this issue at the Microsoft Connect site.
I think this may be a bug in the .Net framework. Somehow the RuntimePropertyInfo.GetValue method is picking the wrong implementation for the ICollection<>.Count property, and it appears to have to do with WindowsRuntime projections. Perhaps the remoting code was redone when they put the WindowsRuntime interop in the framework.
I switched the framework to target .Net 2.0 since I thought if this was a bug, it shouldn't be in that framework. When converting, Visual Studio removed the "Prefer 32 bit" check on my console exe project (since this doesn't exist in 2.0). It runs without exception when this is not present.
In summary, it runs on .Net 2.0 in both 32 and 64 bit. It runs on .Net 4.x in 64 bit. The exception is thrown on .Net 4.x 32 bit only. This sure looks like a bug. If you can run it 64-bit, that would be a workaround.
Note that I've installed .Net 4.6, and this replaces much of the .Net framework v4.x. It could be this is where the problem is introduced; I can't test until I get a machine that doesn't have .Net 4.6.
Update: 2015-09-08
It also happens on a machine with only .Net 4.5.2 installed (no 4.6).
Update: 2015-09-07
Here's a smaller repro, using your same classes:
static void Main(string[] args)
{
var myList = MyListProxy.CreateProxy(new[] {"foo", "bar", "baz", "quxx"});
var listType = myList.GetType();
var interfaceType = listType.GetInterface("System.Collections.Generic.ICollection`1");
var propInfo = interfaceType.GetProperty("Count");
// TargetException thrown on 32-bit .Net 4.5.2+ installed
int count = (int)propInfo.GetValue(myList, null);
}
I've also tried the IsReadOnly property, but it appears to work (no exception).
As to the source of the bug, there are two layers of indirection around properties, one being the remoting, and the other being a mapping of metadata structures called MethodDefs with the actual runtime method, known internally as a MethodDesc. This mapping is specialized for properties (as well as events), where additional MethodDescs to support the property's get/set PropertyInfo instances are known as Associates. By calling PropertyInfo.GetValue we go through one of these Associate MethodDesc pointers to the underlying method implementation, and remoting does some pointer math to get the correct MethodDesc on the other side of the channel. The CLR code is very convoluted here, and I don't have enough experience of the in-memory layout of the MethodTable which holds these MethodDesc records which remoting uses (or the mapping it uses to get to the MethodTable?), but I'd say it's a fair guess that remoting is grabbing the wrong MethodDesc via some bad pointer math. That's why we see a similar but unrelated (as far as your program) MethodDesc - UInt32 get_Size of IVector<T> being invoked on the call:
System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
ConsoleApplication1.MyListProxy.Invoke(IMessage msg) Program.cs: line: 60
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
System.Runtime.InteropServices.WindowsRuntime.IVector`1.get_Size()
System.Runtime.InteropServices.WindowsRuntime.VectorToCollectionAdapter.Count[T]()
This is a pretty interesting CLR bug, some of its guts are showing in the mishap. You can tell from the stack trace that it is trying to call the VectorToCollectionAdapter's Count property.
This class is rather special, no instance of it ever gets created. It is part of the language projection that was added in .NET 4.5 that makes WinRT interface types look like .NET Framework types. It is pretty similar to the SZArrayHelper class, an adapter class that helps implement the illusion that non-generic arrays implement generic interface types like IList<T>.
The interface mapping at work here is for the WinRT IVector<T> interface. As noted in the MSDN article, that interface type is mapped to IList<T>. The internal VectorToListAdapter class takes care of the IList<T> members, VectorToCollectionAdapter tackles the ICollection<T> members.
Your code forces the CLR to find the implementation of ICollection<>.Count and that could either be a .NET class implementing it as normal or it could be a WinRT object that exposes it as IVector<>.Size. Clearly the proxy you created gives it a headache, it incorrectly decided for the WinRT version.
How it is supposed to figure out which is the correct choice is pretty murky. After all, your proxy could be a proxy for an actual WinRT object and then the choice it made would be correct. This could well be a structural problem. That it acts so randomly, the code does work in 64-bit mode, is not exactly inspiring. VectorToCollectionAdapter is very dangerous, note the JitHelpers.UnsafeCast calls, this bug is potentially exploitable.
Well, alert the authorities, file a bug report at connect.microsoft.com. Let me know if you don't want to take the time and I'll take care of it. A workaround is hard to come by, using the WinRT-centric TypeInfo class to do the reflection did not make any difference. Removing the jitter forcing so it runs in 64-bit mode is a band-aid but hardly a guarantee.
we are currently hacking around this problem with this brittle intervention (apologies for code):
public class ProxyBase : RealProxy
{
// ... stuff ...
public static T Cast<T>(object o)
{
return (T)o;
}
public static object Create(Type interfaceType, object coreInstance,
IEnforce enforce, string parentNamingSequence)
{
var x = new ProxyBase(interfaceType, coreInstance, enforce,
parentNamingSequence);
MethodInfo castMethod = typeof(ProxyBase).GetMethod(
"Cast").MakeGenericMethod(interfaceType);
return castMethod.Invoke(null, new object[] { x.GetTransparentProxy() });
}
public override IMessage Invoke(IMessage msg)
{
IMethodCallMessage methodCall = (IMethodCallMessage)msg;
var method = (MethodInfo)methodCall.MethodBase;
if(method.DeclaringType.IsGenericType
&& method.DeclaringType.GetGenericTypeDefinition().FullName.Contains(
"System.Runtime.InteropServices.WindowsRuntime"))
{
Dictionary<string, string> methodMap = new Dictionary<string, string>
{ // add problematic methods here
{ "Append", "Add" },
{ "GetAt", "get_Item" }
};
if(methodMap.ContainsKey(method.Name) == false)
{
throw new Exception("Unable to resolve '" + method.Name + "'.");
}
// thanks microsoft
string correctMethod = methodMap[method.Name];
method = m_baseInterface.GetInterfaces().Select(
i => i.GetMethod(correctMethod)).Where(
mi => mi != null).FirstOrDefault();
if(method == null)
{
throw new Exception("Unable to resolve '" + method.Name +
"' to '" + correctMethod + "'.");
}
}
try
{
if(m_coreInstance == null)
{
var errorMessage = Resource.CoreInstanceIsNull;
WriteLogs(errorMessage, TraceEventType.Error);
throw new NullReferenceException(errorMessage);
}
var args = methodCall.Args.Select(a =>
{
object o;
if(RemotingServices.IsTransparentProxy(a))
{
o = (RemotingServices.GetRealProxy(a)
as ProxyBase).m_coreInstance;
}
else
{
o = a;
}
if(method.Name == "get_Item")
{ // perform parameter conversions here
if(a.GetType() == typeof(UInt32))
{
return Convert.ToInt32(a);
}
return a;
}
return o;
}).ToArray();
// this is where it barfed
var result = method.Invoke(m_coreInstance, args);
// special handling for GetType()
if(method.Name == "GetType")
{
result = m_baseInterface;
}
else
{
// special handling for interface return types
if(method.ReturnType.IsInterface)
{
result = ProxyBase.Create(method.ReturnType, result, m_enforce, m_namingSequence);
}
}
return new ReturnMessage(result, args, args.Length, methodCall.LogicalCallContext, methodCall);
}
catch(Exception e)
{
WriteLogs("Exception: " + e, TraceEventType.Error);
if(e is TargetInvocationException && e.InnerException != null)
{
return new ReturnMessage(e.InnerException, msg as IMethodCallMessage);
}
return new ReturnMessage(e, msg as IMethodCallMessage);
}
}
// ... stuff ...
}
m_coreInstance here is the object instance that the proxy is wrapping.
m_baseInterface is the interface the object is to be used as.
this code intercepts the call(s) made in VectorToListAdapter and VectorToCollectionAdapter and converts it back into the original via that methodMap dictionary.
the part of the conditional:
method.DeclaringType.GetGenericTypeDefinition().FullName.Contains(
"System.Runtime.InteropServices.WindowsRuntime")
makes sure it only intercepts calls that come from stuff in the System.Runtime.InteropServices.WindowsRuntime namespace - ideally we would target the types directly but they are inaccessible - this should probably be changed to target specific class names in the namespace.
the parameters are then cast into the appropriate types and the method is invoked. the parameter conversions appear to be necessary as the incoming parameter types are based on the parameter types of the method calls from the objects in the System.Runtime.InteropServices.WindowsRuntime namespace, and not the parameters of the method calls to the original object types; i.e. the original types before the objects in the System.Runtime.InteropServices.WindowsRuntime namespace hijacked the mechanism.
for example, the WindowsRuntime stuff intercepts the original call to get_Item, and converts it into a call to the Indexer_Get method: http://referencesource.microsoft.com/#mscorlib/system/runtime/interopservices/windowsruntime/vectortolistadapter.cs,de8c78a8f98213a0,references. this method then calls the GetAt member with a different parameter type, which then calls GetAt on our object (again with a different parameter type) - this is the call we hijack in our Invoke() and convert it back into the original method call with the original parameter types.
it would be nice to be able to reflect over VectorToListAdapter and VectorToCollectionAdapter to extract all their methods and the nested calls they make, but these classes are unfortunately marked as internal.
this works for us here, but i'm sure its full of holes - it is a case of trial and error, running it to see what fails and then adding in the required dictionary entries/parameter conversions. we are continuing the search for a better solution.
HTH
ok, so in javascript, we can declare an object like this,
var obj={name:"Irshu",age:22};
console.log(obj);
How do we do the same in c#? the reason i ask because my function need to return a string and a bool together. I dont want to create a class for it, and i dont want to use the dictionary. Are there any alternatives?
public void Message(){
var obj=GetObject(val);
Messagebox.Show(Convert.ToString(obj.ind));
}
public object GetObject(string val){
return new {ind=val,flag=true};
}
This is not valid, is it?
.Net supports ExpandoObject since .NET 4.
http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject%28v=vs.110%29.aspx
It lets you declare the object and add properties as your would in javascript.
Traditionally it is for JS interop and I can't recommend it for production work. Tuple<T> is more appropriate as you get strong typing for free. Ultimately you will write less code and see less runtime errors.
What you have in your code is an anonymous type. Anonymous types cannot exist outside the scope in which they are declared. Generally, we use these for transforming LINQ results to temporary objects.
You can't return anonymous types from a method. You can do however something like this:
public void Message(){
var obj = new { ind = "oaiwejf", flag = true };
Messagebox.Show(obj.ind);
}
EDIT
Check this MSDN article
turns out, its posible, one genius on the internet posted this:
public void Message()
{
var obj=GetObject("Irshu");
var y= Cast(obj, new { ind= "", flag= true });
Messagebox.Show(y.ind); //alerts Irshu
}
public object GetObject(string val){
return new {ind=val,flag=true};
}
T Cast<T>(object obj, T type)
{
return (T)obj;
}
I hope you can help me with the following:
I have a WebService method which is supposed to return an array of CompensationPlanReturnReturn objects.
The method is called like this:
//This is the object I need to instanciate because it contains the method I wanna call
CompensationPlan_Out_SyncService test = new CompensationPlan_Out_SyncService();
//This is the method that is supposed to return me an array of CompensationPlanReturnReturn objects
//The data.ToArray() is the parameter the method need, then I pass the method that I wanna run when the method finishes and I dont know what to pass as the final parameter
test.BeginCompensationPlan_Out_Sync(data.ToArray(), new AsyncCallback(complete), null)
//The method description is:
public System.IAsyncResult BeginCompensationPlan_Out_Sync(CompensationPlanDataCompensationPlan[] CompensationPlanRequest, System.AsyncCallback callback, object asyncState)
//On this method I'd like to access to the resuls (the array of CompensationPlanReturnReturn) but I dont know how
private void complete(IAsyncResult result)
{
lblStatus.Text = "Complete";
}
You need to call test.EndCompensationPlan_Out_Sync(result), which will return the result of the asynchronous operation, or throw an exception if an error occurred.
Async methods breakdown into two submethods - Begin and End.
You need to call EndCompensationPlan_Out_Sync to get the actual result returned by method -
private void complete(IAsyncResult result)
{
var actualResult = test.EndCompensationPlan_Out_Sync(result);
lblStatus.Text = "Complete";
}
Try to use the AsyncState-Property and cast it the the given Type.
Like this:
cSACommand = (SACommand)Result.AsyncState;
I am having some trouble with assemblies and DLL's.
instrument_ is declared as an object and I'm creating an instance of "PP150" from the dll whose path is specified by path_.
string className = ContineoProperties.getSingleton().getClassName(path_);
assembly_ = Assembly.LoadFrom(path_);
Type classType = assembly_.GetType("Instrument." + className);
instrument_ = Activator.CreateInstance(classType);
Later I to call the method isntrument_.instrumentCommand(cmd.getCommandName())
The error I get is with when i call the method.
'object' does not contain a definition for 'instrumentCommand'
The isntrument_ is created fine. its just the method call that's giving me a problem. The method does exist in the "PP150.dll". Do I need some DLLImport to allow it to recognize it as a function?
Thanks,
P
If object type is not known in compile time,
To call a method defined on an object, you must use Reflection.
MethodInfo mInfo = classType.GetMethod("instrumentCommand");
mInfo.Invoke(instrument_, new Object[] { _parameters});
The compiler is never going to recognize the methods on a type that you are loading via reflection (e.g. using Assembly.GetType() and Activator.CreateInstance()). Unless you have the type metadata available at build time, you will always get that error if you try to call methods that are not defined on Object itself.
You have two options for making that kind of method call. Both of them require you to give up type safety, the only difference is the amount of work required. In both cases, if you make a mistake, the compiler will not tell you -- you will get a runtime exception instead.
Declare instrument_ as dynamic instead of object. This, obviously, only works in .NET 4.0, but it accomplishes exactly what you're trying to do. The method call will be dispatched at runtime, so as long as the instance that instrument_ references actually has a method call with the appropriate name, it will work.
Use reflection to call the method. You're already using reflection to load the type, so you are halfway there. You would need to add something like this:
// The array of types is the parameter list; assuming instrumentCommand takes
// a string it would look like this:
MethodInfo method = classType.GetMethod("instrumentCommand", new Type[] { typeof(string) });
method.Invoke(instrument_, new object[] { cmd.getCommandName() });
This happens because Activator.CreateInstance returns an object. I would create a separate DLL for the interface which is implemented by the class you want to instantiate. Both the DLL containing this class, and the executable should reference the DLL containing the interface. This way you could cast the object returned by Activator.CreateInstance to the interface, and call its methods:
IInstrument.dll:
interface IInstrument
{
void instrumentCommand(string cmd);
}
Instrument.dll (add IInstrument.dll as reference):
class Instrument : IInstrument
{
public void instrumentCommand(string cmd)
{
// ... implementation ...
}
}
InstrumentApp.exe (add IInstrument.dll as reference):
class Program
{
public static void Main()
{
// ... load Instrument.dll into assembly object ...
// ... load the type from the assembly ...
IInstrument instrument_ = (IInstrument)Activator.CreateInstance(classType);
instrument_.instrumentCommand(cmd.getCommandName());
}
}
The most simple thing would be to link agains PP150.
If you did link against the dll you must use Assembly.LoadFile or Assembly.Load and not LoadFrom because the last one will cause the assembly load to load your assembly in the LoadFrom loader context which will alter type identity.
Suppose you load the Type T from Assembly A via LoadFrom and you link against A as well.
object CreateTypeFrom()
{
var A = Assembly.LoadFrom(#"xxxx");
return A.CreateInstance("T");
}
void Test()
{
object t = CreateTypeFrom();
T RealT = new T(); // no prob
T Castedt = (T)t; // this will throw an InvalidCastException
T isNull = t as T; // this will result in a null instance
}
As you can see although you did create two times an instance of T they cannot be casted to due to different loader context which will make the type pretty useless.
To get rid of these things you could simply use Reflection to create a proxy type which will forward your calls to the proxy type. If you are using .NET 4 you can take advantage of the DLR to find the best matching methods at runtime. The code below creats a Version object and returns it as dynamic object. Then I do call the Major property to an integer and print it out to console. This does work with no exceptions nor compile time errors if you are using .NET 4 or later.
dynamic CreateTypeFrom()
{
var assembly = typeof(string).Assembly;
return assembly.CreateInstance("System.Version", true, BindingFlags.CreateInstance, null, new object[] { 1, 2, 3, 4 }, null, null);
}
[TestMethod]
public void Test()
{
var t = CreateTypeFrom();
int major = t.Major;
Console.WriteLine(major);
}
Given the following C# code:
public object CallJavaScriptFunction(string functionName, params object[] args)
{
object script = Document.Script;
var result = script.GetType().InvokeMember(functionName, BindingFlags.InvokeMethod, null, script, args);
return result;
}
And the following client-side JavaScript block:
function someFunction() {
alert('This is only a test!');
}
var someObj = {
someMethod: function() {
alert('This is another test!');
}
}
The following server-side block executes successfully:
CallJavaScriptFunction("someFunction");
But this will throw a DISP_E_UNKNOWNNAME:
CallJavaScriptFunction("someOBj.someMethod");
Obviously I'm doing something wrong here - probably there is another way of calling InvokeMember on JavaScript instance methods, but I was not able to find out how.
Any thoughts? Any help will be appreciated.
You need to invoke the someObj property, then invoke the someMethod method on the value of the property