Disposing of a c# interface wrapping an IDispatch COM interface - c#

I have implemented an IDispatch interface in C#. It in turn opens up an unmanaged COM interface which also exposes an IDispatch interface.
~MyObject()
{
Logger.TraceDebug("About to clean up object");
CleanupObject();
}
private void CleanupObject()
{
lock (lock_so)
{
try
{
if (so != null)
{
Logger.TraceWarning("Releasing object");
Marshal.FinalReleaseComObject(so);
}
}
catch (Exception e)
{
}
so = null;
}
}
The problem I'm having is that the Finalize is being called while the object is being used during normal execution meaning that attempts later to access the wrapped interface fail. When I take the cleanup code out, the code works fine but will fail when the program using the code exits (I don't have debug info from the calling app but it's likely to be the wrapped interface hasn't been disposed). I'm at a loss as to how to address this issue and thinking that my understanding is incorrect. Any suggestions would be greatly appreciated.
The object is initialised in the following:
private void InitialiseObject()
{
if (so == null)
{
so = Activator.CreateInstance(Type.GetTypeFromProgID("MyProgID));
}
}
Then used like:
public void DoSomething(string String)
{
try
{
lock (lock_so)
{
Object[] args = new Object[1];
args[0] = String;
so.GetType().InvokeMember("DoSomething", BindingFlags.InvokeMethod, null, so, args);
}
}
The point of all this is the c# interface acts as a pass through class and is able to log information being passed from the third party application to the IDispatch interface.

Why do you need this? If i ware you and i would have a dispose method to free up some resource then i would implement the IDisposable interface. Pattern

Related

Shared ownership of IDisposable objects in C#

Is there any classes in C# which provide shared ownership of IDisposable objects? Something like shared_ptr in c++? And if not, what are best practices here?
UPDATE
I'm writing a c++/cli wrapper over native lib. And I need release native resources (MAPI COM interfaces for example, so I need determenistic resource releasing).
Native part:
//Message.h
class Message
{ ... };
//MessageSet.h
class MessageSet
{
...
class iterator : public std::iterator<std::forward_iterator_tag, Message*>
{
...
public:
Message* operator*();
bool operator!=(const iterator& that);
iterator& operator++();
};
iterator begin();
iterator end();
};
Managed part (c++/cli):
public ref class Message
{
native::Message* inst;
public:
Message(native::Message* inst);
~Message();
!Message();
};
public ref class MessageSet : public IEnumerable<Message^>
{
native::MessageSet* inst;
public:
MessageSet(native::Message* inst);
~MessageSet();
!MessageSet();
virtual IEnumerator<Message^>^ GetEnumerator();
virtual System::Collections::IEnumerator^ EnumerableGetEnumerator() = System::Collections::IEnumerable::GetEnumerator;
};
When I use Message objects in TPL Dataflow (BroadcastBlock block i.e. there are many concurrent consumers) in C# I don't know when I should call Dispose() for these messages.
I think the best you could do is something like this:
public sealed class SharedDisposable<T> where T : IDisposable
{
public sealed class Reference : IDisposable
{
public Reference( SharedDisposable<T> owner )
{
mOwner = owner;
}
public void Dispose()
{
if( mIsDisposed ) return;
mIsDisposed = true;
mOwner.Release();
}
public T Value => mOwner.mValue;
private readonly SharedDisposable<T> mOwner;
private bool mIsDisposed;
}
public SharedDisposable( T value )
{
mValue = value;
}
public Reference Acquire()
{
lock( mLock )
{
if( mRefCount < 0 ) throw new ObjectDisposedException( typeof( T ).FullName );
mRefCount++;
return new Reference( this );
}
}
private void Release()
{
lock( mLock )
{
mRefCount--;
if( mRefCount <= 0 )
{
mValue.Dispose();
mRefCount = -1;
}
}
}
private readonly T mValue;
private readonly object mLock = new object();
private int mRefCount;
}
Basically this allows you to have one object (SharedDisposable<T>) manage the lifetime of the underlying disposable while providing a mechanism to distribute "shared" references to it.
One shortcoming here is that technically anyone could dispose the underlying value by accessing it through the shared reference Value property. You could address this by creating some sort of facade object that wraps the underlying disposable type but hides its Dispose method.
That would a NO.
Best way I found so far is quite clunky, using Dictionaries and WeakReferences. The Dictionary maps the object to it's refcount. WeakReference is used so you don't increase the ref count artificially.
You do not own IDisposable, you implement it, so .NET Garbage Collector will call overridden method in your class, notifying about a fact happened.
It's a different concept from shared_ptr, where destructor is guaranteed to be called once last ownership of a pointer is gone.
In general, in .NET, unless you are not using unsafe programming techniques, you do not own anything, .NET Garbage Collector owns it.
Even when you explicitly destroy an object, the memory allocated for it may not, and often will not, be reclaimed immediately, like once would expect from C++.
EDIT
If you have native resources and want release them in precise moment, you can achieve that by :
1) Implementing IDisposable with your .NET wrapper object
2) Inside Dispose() method of that wrapper write the code that releases native resources
3) In the code that consumes wrapper object, in the moment you would like to release native resources allocated by wrapper object, call explicitly Dispose() on it.
In this case Dispose() method is called, your code executes and releases native resources immediately.
EDIT (2)
After that is more clear what's the question about:
If you can not determine when Dispose() has to be called, I would stay with #Hans's comment: just relay on eventual (soon or later) GC call and avoid your own reference counter implementation (especially in multi threaded environment).
Do not invent the wheel, if that is a feasible in your situation.

Can I implement a managed COM-visible interface in unmanaged code?

I have a class implemented in C# that I want to use from a native application. The C# class has a dependency described by an interface, which is exepected to be delivered by the code instantiating the class. I would like to realize this interface in the native application and pass it to the C# object via COM. Strongly simplified, the C# code looks like this:
[ComVisible(true)]
[Guid("910E8445-7A62-403F-BAEE-17AB0C169CA8")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IComWidget
{
void SetClient(IComWidgetClient client);
void DoStuff();
}
[ComVisible(true)]
[Guid("850F3EBB-CD18-4E16-881F-50B50DD5AEB0")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IComWidgetClient
{
int GetValue();
}
[ComVisible(true)]
[Guid("86B9EC33-6CDF-438F-9A67-57D009723027")]
[ClassInterface(ClassInterfaceType.None)]
public class ComWidget : IComWidget
{
private IComWidgetClient m_Client;
public void DoStuff()
{
var i = m_Client.GetValue();
Debug.WriteLine("value was {0}", i);
}
public void SetClient(IComWidgetClient client)
{
m_Client = client;
}
}
The native application loads the COM library as a side-by-side assembly with a proper manifest, and implements the IComWidgetClient interface. It seems to work, but when running automated tests on the system several tests fail with an unhandled ExecutionEngineExecption. The way it fails (the test process is aborted) smells like some kind of corruption during garbage collection.
I think I may be able to write a managed c++ unit test that mimics the steps that lead to the error. At least it fails the same way. The test looks like this:
[TestMethod]
void TestStuff()
{
IComWidgetPtr sut = NULL;
NativeClient* client = NULL;
try
{
sut = IComWidgetPtr(__uuidof(ComWidget));
client = new NativeClient();
IComWidgetClient* pvObject;
client->QueryInterface(IID_IComWidgetClient, (void**)&pvObject);
sut->SetClient(pvObject);
sut->Release();
GC::Collect();
GC::WaitForPendingFinalizers();
Assert::IsTrue(true); // If we get this far, everything went OK...
}
finally
{
sut = NULL;
delete client;
client = NULL;
}
};
Where NativeClient is a simple native object implementing IComWidgetClient
public class NativeClient: IComWidgetClient
{
...
}
What goes wrong? Is what I am trying to do at all possible?
Full source code can be found here:
https://drive.google.com/file/d/0B-D57qCpESa5MnpZUXZRN2pyNnc/view?usp=sharing

Mocking and Marshal.ReleaseComObject()

I have a problem setting up a mock, so I can call Marshal.ReleaseComObject() on my Mocked object.
I am using Moq to set up a mock of a type IFeature (from a third-party interface library). The mock setup is fairly simple:
var featureMock = new Mock<IFeature>();
IFeature feature = featureMock.Object;
In my code, The feature object is created in a while loop, running through a type of cursor (FeatureCursor). Due to legacy issues of the third-party library, the Feature object has known problems with memory leakage. Thus, I have to release the objects through Marshal.ReleaseComObject(), like shown in the code;
public class XXX
{
public void DoThis()
{
IFeatureCursor featureCursor;
//...fill the cursor with features;
IFeature feature = null;
while ((feature = featureCursor.NextFeature)!= null)
{
//Do my stuff with the feature
Marshal.ReleaseComObject(feature);
}
}
}
It works when I use real a featurecursor and features, but when when I mock the feature in a unittest, I get an error:
"System.ArgumentException : The object's type must be __ComObject or derived from __ComObject."
But how do I apply this to my Mock object?
The Mocked IFeature will just be a standard .NET class, not a COM object which is why your test is currently throwing the The object's type must be __ComObject... exception.
You just need to wrap the call to Marshal.ReleaseComObject(feature); and check whether the object is a COM object first:
if (Marshal.IsComObject(feature)
{
Marshal.ReleaseComObject(feature);
}
Then your test will work pass but won't call Marshal.ReleaseComObject (the production code will call it).
Since it sounds like you actually want to verify somehow that Marshal.ReleaseComObject was called by the code you will need to do a little more work.
Since it's a static method and doesn't actually do anything to the object itself the only option you have is to create a wrapper:
public interface IMarshal
{
void ReleaseComObject(object obj);
}
public class MarshalWrapper : IMarshal
{
public void ReleaseComObject(object obj)
{
if (Marshal.IsComObject(obj))
{
Marshal.ReleaseComObject(obj);
}
}
}
Then make your code depend on IMarshal which you can also mock in your test and verify:
public void FeaturesAreReleasedCorrectly()
{
var mockFeature = new Mock<IFeature>();
var mockMarshal = new Mock<IMarshal>();
// code which calls IFeature and IMarshal
var thing = new Thing(mockFeature.Object, mockMarshal.Object);
thing.DoThis();
// Verify that the correct number of features were released
mockMarshal.Verify(x => x.ReleaseComObject(It.IsAny<IFeature>()), Times.Exactly(5));
}

C# code to handle different classes with same method names

Let's say you have two different C# classes A and B that while not deriving from the same base class do share some of the same names for methods. For example, both classes have a connect and a disconnect method, as well as several others. I want to be able to write code once that will work with both types.
Here is a simplified example of what I would like to do:
public void make_connection(Object x)
{
x.connect() ;
// Do some more stuff...
x.disconnect() ;
return ;
}
Of course, this does not compile as the Object class does not have a connect or disconnect method.
Is there a way to do this?
UPDATE. I should have made this clear from the start: I only have the DLLs for A and B and not the source.
You can use an interface to accomplish what you want to do.
interface IConnectable
{
void Connect();
void Disconnect();
}
Both A and B should implement IConnectable. Then use IConnectable instead of Object as the parameter type for your method and you should be all set.
public void MakeConnection(IConnectable connectable)
{
connectable.Connect();
// Do some more stuff...
connectable.Disconnect();
}
Edit: Since you don't have the source code, you have a couple of options:
Use Max's solution of using the dynamic keyword, (if you are using .NET 4.0)
Use Steve's solution of using casting and if/else statements
Create wrapper classes for A and B and have them implement the interface (or use common abstract base class for them)
For example:
class AWrapper : IConnectable
{
private A obj;
public AWrapper(A obj)
{
this.obj = obj;
}
public void Connect()
{
this.obj.Connect();
}
public void Disconnect()
{
this.obj.Disconnect();
}
// other methods as necessary
}
(BWrapper would be similar, just using B instead of A)
Then you could create the wrappers and pass them into MakeConnection. It's up to you how you want to do it. Depending on your situation, one method may be easier than the others.
This will work in C# 4:
public void make_connection(dynamic x)
{
x.connect() ;
// Do some more stuff...
x.disconnect() ;
return ;
}
Try using an Interface rather.
Have a look at interface (C# Reference) and Interfaces (C# Programming Guide)
So something like
public interface IConnections
{
void connect();
void disconnect();
}
public class A : IConnections
{
public void connect()
{
//do something
}
public void disconnect()
{
//do something
}
}
public class B : IConnections
{
public void connect()
{
//do something
}
public void disconnect()
{
//do something
}
}
public void make_connection(IConnections x)
{
x.connect();
// Do some more stuff...
x.disconnect();
return;
}
There is a OOAD concept of 'Programe to an interface not to an implementation' which let's you avoid the chain of inheritance hierarchies
1- You can create a interfcae
interface IConnection
{
void Connect();
void Disconnect();
}
2- And let your classes implement this interface as shown below.
class A : IConnection
{
#region IConnection Members
public void Connect()
{
// your connect method implementation goes here.
}
public void Disconnect()
{
// your disconnect method implementation goes here.
}
#endregion
}
class B : IConnection
{
#region IConnection Members
public void Connect()
{
// your connect method implementation goes here.
}
public void Disconnect()
{
// your disconnect method implementation goes here.
}
#endregion
}
3- Once you done with the implementation than you can make your function accepting an argument of IConnection as shown below.
public void makeConnection(IConnection con)
{
con.Connect();
con.Disconnect();
}
4- And from your client code , you can pass the object of classes which implements IConnect Interface.
If the interface solution is not possible (e.g you don't have source code), another less effecient solution is to use reflection.
As others have said, re-factoring to use interfaces or using the dynamic approach are probably the most elegant ways.
If this is not possible you could cast the object to your types. I'd suggest using as and then checking that the cast worked, an unchecked cast would be dangerous if someone called this with a type that failed to cast.
E.g. If types A and B both have a method called DoSomething() then this will work...
public static void CallDoSomething(object o)
{
A aObject = o as A;
if (aObject != null)
{
aObject.DoSomething();
return;
}
B bObject = o as B;
if (bObject != null)
{
bObject.DoSomething();
return;
}
}
BUT this is pretty ugly to be honest... I'd really try and refactor to interfaces.
Either you will have to use an Interface (or Base class) as shown by Zach and astander, or you will have to case the object before using:
public void make_connection(Object x)
{
((A)x).connect() ;
// Do some more stuff...
x.disconnect() ;
return ;
}
You could also use reflection to invoke the methods
What you want is called Duck Typing.
From Wikipedia:
Duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface.
C# 4.0 allows this, as other have said, using the dynamic keyword

Casting of interfaces

interfaces provide a useful abstraction capability. One can have a class Foo implement some interfaces, say A, B, and C. Some client code may get a reference of type A, others one of type B, etc. each actually the same Foo object but the interface exposing only a narrow subset of the functionality. Of course, evil client code can try to cast the A reference to Foo, then access the other functionality.How to prevent this?
This is called a "malicious cast" and you can prevent it by having a wrapper that implements only the narrow interface you want to expose (by delegating to a private reference to the object that you would have otherwise directly passed to the evil client).
However, if the client is not only evil, but powerful as well, he might be able to use reflection to get to the hidden reference anyway.
Normal inheritance will always allow it, you can do nothing with it. If you want to expose some class as interface but hide other methods use Adapter pattern (google it)
You can't. One workaround is to implement three proxy classes, one to implement each interface, that forward all calls to a single Foo instance.
The person who performs a malicious cast does so at their own risk. In almost all cases, you can safely assume that the user will not use an object in a manner outside the specified interface contract.
The only time you really need to use a proxy object is if you are exposing security-sensitive object to untrusted code. Otherwise, spend your time making clear documentation about how objects can be used and work under the assumption that it will be followed.
Hide the underlying object.
Let's say you have:
public interface A {
}
public class B implements A {
}
So, interface A implements just a subset of B's functionality. Effectively it hides parts of B. Your question is how to stop the user from downcasting A to a B.
B objectOfTypeB = (B)objectOfTypeA; // you don't want this
So, don't give the user access to class B. If the user can't import it, he can't instantiate it or downcast to it. So, he's force to use the interface and nothing more.
Change the above code to:
/* Publicly accessable interface */
public interface A {
}
/* Class hidden inside the package. */
public class B implements A {
}
Then, you can just have a function return an A, secure in the knowledge that the user can't use B.
/* Function that returns an A. */
public A foo() {
/* ... */
return objectOfTypeB;
}
You can use a Facade class.
This class should wrap a delegate of class Foo and then only expose interface methods of, say A and just forward them to the delegate.
On the other hand, you can prevent casting to Foo by declaring it package private and have a public factory method that returns just the interface A ( which in reality is Foo ). That way casting from other packages will not be possible ( still, somebody may play tricks with reflection ).
There is no really practical, non-invasive way to protect against this.
However, if your situation really requires this protection, use this utility class to create dynamic proxy (delegate) classes (adapted from Dynamic Proxy Classes - <50 lines of production code!!).
This will cause ClassCastExceptions at runtime if someone uses tries a malicious cast. You could even conditionalize the code to turn it off at production time (have newInstance() just return obj - the object to as the "proxy").
DynamicProxy.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class DynamicProxy implements java.lang.reflect.InvocationHandler {
private Object obj;
public static Object newInstance(Object obj, Class<?>... interfaces) {
if (interfaces == null || interfaces.length == 0) {
throw new IllegalArgumentException("No interfaces");
}
return java.lang.reflect.Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
interfaces,
new DynamicProxy(obj));
}
private DynamicProxy(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method m, Object[] args)
throws Throwable
{
Object result;
try {
result = m.invoke(obj, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " +
e.getMessage());
}
return result;
}
// ** DEMO CODE BELOW HERE **
interface A {
void methodA();
}
interface B {
void methodB();
}
static class Foo implements A, B {
public void methodA() { System.out.println("A"); }
public void methodB() { System.out.println("B"); }
}
public static void main(String[] args) {
Foo foo = new Foo(); // implements both interfaces
// calls foo's methods, but only A methods
A a = (A) DynamicProxy.newInstance(foo, A.class);
// calls foo's methods, but only B methods
B b = (B) DynamicProxy.newInstance(foo, B.class);
// calls foo's methods, but only B methods
A ab = (A) DynamicProxy.newInstance(foo, A.class, B.class);
a.methodA();
b.methodB();
ab.methodA();
((B) ab).methodB();
// ClassCastException: $Proxy0 cannot be cast to DynamicProxy$Foo
((Foo) a).methodA();
// ClassCastException: $Proxy1 cannot be cast to DynamicProxy$Foo
((Foo) b).methodB();
// ClassCastException: $Proxy0 cannot be cast to DynamicProxy$B
((B) a).methodB();
// ClassCastException: $DynamicProxy1 cannot be cast to DynamicProxy$A
((A) b).methodA();
}
}

Categories