COM interface declaration and use (or lack thereof) - c#

As I understand it, COM interfaces are abstract classes in C++ but for some reason translate to C# interfaces. Why must one declare all methods of an interface in C#, even when one does not intend to use any of its members? Take for example IFileOperation, I've tried removing function declarations which I have verified are never called in my code but it results in System.AccessViolationException being thrown.

Your code doesn't run in isolation. A COM interface is a binary contract between code offering a service, and code using those services. The contract is an all-or-nothing agreement (with the caveat that E_NOTIMPL can be used to indicate certain optional methods are not available, if the interface documentation indicates that this is allowed).
IFileOperation is not your contract. It belongs to Microsoft. It's used to interact with Microsoft code and other 3rd party code. That code (which you don't own) expects classes implementing the interface to provide a function pointer for each method in the interface (and put it in a VTable). That's what the interface means. You don't get to not provide that function pointer. And that code will call any method in the interface it sees fit to call, according to the documented rules of the interface. It's not your choice.
If you are absolutely sure the method is not called it means you're not using it to interact with the shell. If you don't like some of the methods and you don't interact with the shell (or other 3rd party code) you can always make up your own interface; nobody forces you to borrow someone else's. Make sure both the COM server and Client agree on the interface definition.
On the other hand, if you are interacting with the shell, you don't know which methods the shell will call on you. You have to provide implementations for all of them, even if all you do is return an error. I'm not super-familiar with IFileOperation so read the documentation carefully. It's possible that some methods can return specific error messages (like E_NOTIMPL) to indicate the specific functionality is not available.
The fact that you are getting an invalid access violation strongly suggests one of those methods you dislike is indeed being called.

Related

C# Forcing static fields [duplicate]

I am developing a set of classes that implement a common interface. A consumer of my library shall expect each of these classes to implement a certain set of static functions. Is there anyway that I can decorate these class so that the compiler will catch the case where one of the functions is not implemented.
I know it will eventually be caught when building the consuming code. And I also know how to get around this problem using a kind of factory class.
Just curious to know if there is any syntax/attributes out there for requiring static functions on a class.
Ed Removed the word 'interface' to avoid confusion.
No, there is no language support for this in C#. There are two workarounds that I can think of immediately:
use reflection at runtime; crossed fingers and hope...
use a singleton / default-instance / similar to implement an interface that declares the methods
(update)
Actually, as long as you have unit-testing, the first option isn't actually as bad as you might think if (like me) you come from a strict "static typing" background. The fact is; it works fine in dynamic languages. And indeed, this is exactly how my generic operators code works - it hopes you have the static operators. At runtime, if you don't, it will laugh at you in a suitably mocking tone... but it can't check at compile-time.
No. Basically it sounds like you're after a sort of "static polymorphism". That doesn't exist in C#, although I've suggested a sort of "static interface" notion which could be useful in terms of generics.
One thing you could do is write a simple unit test to verify that all of the types in a particular assembly obey your rules. If other developers will also be implementing the interface, you could put that test code into some common place so that everyone implementing the interface can easily test their own assemblies.
This is a great question and one that I've encountered in my projects.
Some people hold that interfaces and abstract classes exist for polymorphism only, not for forcing types to implement certain methods. Personally, I consider polymorphism a primary use case, and forced implementation a secondary. I do use the forced implementation technique fairly often. Typically, it appears in framework code implementing a template pattern. The base/template class encapsulates some complex idea, and subclasses provide numerous variations by implementing the abstract methods. One pragmatic benefit is that the abstract methods provide guidance to other developers implementing the subclasses. Visual Studio even has the ability to stub the methods out for you. This is especially helpful when a maintenance developer needs to add a new subclass months or years later.
The downside is that there is no specific support for some of these template scenarios in C#. Static methods are one. Another one is constructors; ideally, ISerializable should force the developer to implement the protected serialization constructor.
The easiest approach probably is (as suggested earlier) to use an automated test to check that the static method is implemented on the desired types. Another viable idea already mentioned is to implement a static analysis rule.
A third option is to use an Aspect-Oriented Programming framework such as PostSharp. PostSharp supports compile-time validation of aspects. You can write .NET code that reflects over the assembly at compile time, generating arbitrary warnings and errors. Usually, you do this to validate that an aspect usage is appropriate, but I don't see why you couldn't use it for validating template rules as well.
Unfortunately, no, there's nothing like this built into the language.
While there is no language support for this, you could use a static analysis tool to enforce it. For example, you could write a custom rule for FxCop that detects an attribute or interface implementation on a class and then checks for the existence of certain static methods.
The singleton pattern does not help in all cases. My example is from an actual project of mine. It is not contrived.
I have a class (let's call it "Widget") that inherits from a class in a third-party ORM. If I instantiate a Widget object (therefore creating a row in the db) just to make sure my static methods are declared, I'm making a bigger mess than the one I'm trying to clean up.
If I create this extra object in the data store, I've got to hide it from users, calculations, etc.
I use interfaces in C# to make sure that I implement common features in a set of classes.
Some of the methods that implement these features require instance data to run. I code these methods as instance methods, and use a C# interface to make sure they exist in the class.
Some of these methods do not require instance data, so they are static methods. If I could declare interfaces with static methods, the compiler could check whether or not these methods exist in the class that says it implements the interface.
No, there would be no point in this feature. Interfaces are basically a scaled down form of multiple inheritance. They tell the compiler how to set up the virtual function table so that non-static virtual methods can be called properly in descendant classes. Static methods can't be virtual, hence, there's no point in using interfaces for them.
The approach that gets you closer to what you need is a singleton, as Marc Gravell suggested.
Interfaces, among other things, let you provide some level of abstraction to your classes so you can use a given API regardless of the type that implements it. However, since you DO need to know the type of a static class in order to use it, why would you want to enforce that class to implement a set of functions?
Maybe you could use a custom attribute like [ImplementsXXXInterface] and provide some run time checking to ensure that classes with this attribute actually implement the interface you need?
If you're just after getting those compiler errors, consider this setup:
Define the methods in an interface.
Declare the methods with abstract.
Implement the public static methods, and have the abstract method overrides simply call the static methods.
It's a little bit of extra code, but you'll know when someone isn't implementing a required method.

How to distinguish 'Role' interfaces from 'Result' interfaces?

This issue comes up for me so often in my coding that I'm astonished I can find so little reference to it, and would value other people's thoughts and ideas.
I define lots of APIs, for the frameworks I work on, and within large domain models that I want to break up. Those APIs consist almost entirely of interfaces (meaning, in my case, C# interfaces). I find, over and over again, that I want to distinguish between two kinds of interface. In the absence of finding any more widely used terms, I define these two as follows:
'Role' interfaces are intended to be implemented by objects outside of the API, in order that those objects can be used as arguments for methods defined on the API.
'Result' interfaces are implemented by objects inside the API and made available to other parts of the system via the API. The intent of defining a result interface rather than exposing the object that implements it is to restrict the view of the object to the outside world.
To pick one example, a Payments sub-system might define IPayableItem as a Role interface, implemented by many types in other parts of the application in order that Payments may be generated for them. Those generated Payment objects may be retrieved via the API but defined by the Result interface IPayment.
The only way I can currently distinguish these is by naming convention and/or commenting. Ideally, I would like the distinction enforced by the language, and have it enforce the rule: you can't implement a Result interface outside the API, only use it. But C# doesn't provide any such mechanism. (Can anyone advise me of a language that does?). I could define an attribute, but this still wouldn't enforce anything.
Another important significance of the distinction lies in Semantic Versioning of the API. If I add a new member to a Role interface then this should be seen as a breaking change (and hence a first-level version) - because any existing external implementations will need to add that member. But if I add a member to what I deem to be a 'Result' interface then it should only be my own code that is impacted - it is just a new feature (second-level version) for everyone else. But with no enforced distinction between the two types there's some risk that people are implementing the Result interfaces and hence their code would be broken.
Has anyone else encountered this dilemma? If so, how have you dealt with it? I look forward to your answers.
But please don't both to respond with either of the following arguments (which I have heard all too often):
My Result interfaces should be abstract classes rather than interfaces. This does not solve the problem, and potentially makes it worse, since external code can sub-class them.
I should be returning the concrete type and ensuring that anything I don't want accessible outside the API is marked 'internal'. There are lots of cases where I need things inside the API to be public, e.g. to be accessible to other frameworks (not going through the API).
I think what you're asking is it possible to expose an interface, but determine that a given instance is one you created?
If so, you could also create an internal private interface, and mark all your implementations as also implementing the private interface. Then upon being given an object from the outside world, verify it has the internal interface implementation as well.
public interface IPublic
{
...
}
internal interface ISecret { }
public class PublicImplementation : IPublic, ISecret
{
...
}
Only you can implement the ISecret, so even if someone implements the IPublic and passes it to you, it will fail the ISecret test.

Explicit interface implementation for COM interfaces in C#

Some time I ago I was working on a major refactoring of an old Win32 program implemented with COM, and there were various parts that were implemented with C# (.NET). During my work on this project, I ran across a Microsoft page on COM programming in C# that recommended C# classes explicitly implement COM interfaces, rather than implicity. I recently tried to remember why, and I couldn't. I also couldn't find the page on the MSDN site again. Can anybody please tell me why Microsoft might recommend this ?
Hmm, that makes a wee bit of sense, COM is pure interface-based programming and the actual implementation of the interfaces should be hidden. Implementing interface methods explicitly gets you that automatically because they cannot be public.
Actually doing this is quite pointless, you could (and should) simply apply the [ClassInterface(ClassInterfaceType.None)] attribute to the class. That by itself ensures that the implementation isn't exposed, only the interfaces implemented by the class are visible. Implementing the interface methods explicitly isn't actually good enough. Because you cannot hide the fact that your class inherits System.Object. Which exposes the four public methods of Object and puts a reference to mscorlib.tlb in your type library, a reference that a real COM client will never use. It will almost always work because the odds that the compiler that uses your class runs on a machine that doesn't have .NET installed are pretty small. But very yucky nonetheless, it isn't actually required. Only the machine that uses the class needs it installed.
Just don't do this. Declare the interfaces you implement, give them the [InterfaceType(ComInterfaceType.InterfaceIsDual)] attribute to allow them to be used both early and late bound. And hide the actual implementation of them with [ClassInterface(ClassInterfaceType.None)]. Only sensible way.
It's old, but from here: http://msdn.microsoft.com/en-us/library/aa288461%28v=VS.71%29.aspx they mention implementing an interface explicitly so you can implement multiple interfaces that have the same member names.
This also requires that the user of your class cast an instance of your class to the appropriate interface.
As for why this is especially important for COM: my first guess is so that COM can call one set of methods while managed code may call another. However, I'm guessing here.

Any way to avoid creating a huge C# COM interface wrapper when only a few methods needed?

Greetings all,
I’m working on a C# program that requires being able to get the index of the hot item in Windows 7 Explorer’s new ItemsView control. Fortunately, Microsoft has provided a way to do this through UI Automation, by querying custom properties of the control.
Unfortunately, the System.Windows.Automation namespace inexplicably does not seem to provide a way to query custom properties! This leaves me with the undesirable position of having to completely ditch the C# Automation namespace and use only the unmanaged COM version. One way to do it would be to put all the Automation code in a separate C++/CLI module and call it from my C# application. However, I would like to avoid this option if possible, as it adds more files to my project, and I’d have to worry about 32/64-bit problems and such.
The other option is to make use of the ComImport attribute to declare the relevant interfaces and do everything through COM-interop. This is what I would like to do. However, the relevant interfaces, such as IUIAutomation and IUIAutomationElement, are FREAKING HUGE. They have hundreds of methods in total, and reference tons and tons of interfaces (which I assume I would have to also declare), almost all of which I will never ever use. I don’t think the UI Automation interfaces are declared in any Type Library either, so I can’t use TLBIMP.
Is there any way I can avoid having to manually translate a bajillion method signatures into C# and instead only declare the ten or so methods I actually need? I see that C# 4.0 added a new “dynamic” type that is supposed to ease COM interop; is that at all relevant to my problem?
Thanks
The most important thing (from the perspective of calling a COM method from C#) is that the methods appear in the interface in the right order. If you're not using a method, you can just declare it as void and nothing bad will happen (unless you actually call it!). This saves you from having to work out the correct signatures and define all the other types, etc. For example,
[ComImport, Guid("30cbe57d-d9d0-452a-ab13-7ac5ac4825ee"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IUIAutomation
{
void CompareElements();
void CompareRuntimeIds();
void GetRootElement();
// 50 or so other methods...
// ... define only the signatures for the ones you actually need
}
The methods should be defined in exactly the same order they appear in UIAutomationClient.h (in the Windows SDK).

Is there a way to force a C# class to implement certain static functions?

I am developing a set of classes that implement a common interface. A consumer of my library shall expect each of these classes to implement a certain set of static functions. Is there anyway that I can decorate these class so that the compiler will catch the case where one of the functions is not implemented.
I know it will eventually be caught when building the consuming code. And I also know how to get around this problem using a kind of factory class.
Just curious to know if there is any syntax/attributes out there for requiring static functions on a class.
Ed Removed the word 'interface' to avoid confusion.
No, there is no language support for this in C#. There are two workarounds that I can think of immediately:
use reflection at runtime; crossed fingers and hope...
use a singleton / default-instance / similar to implement an interface that declares the methods
(update)
Actually, as long as you have unit-testing, the first option isn't actually as bad as you might think if (like me) you come from a strict "static typing" background. The fact is; it works fine in dynamic languages. And indeed, this is exactly how my generic operators code works - it hopes you have the static operators. At runtime, if you don't, it will laugh at you in a suitably mocking tone... but it can't check at compile-time.
No. Basically it sounds like you're after a sort of "static polymorphism". That doesn't exist in C#, although I've suggested a sort of "static interface" notion which could be useful in terms of generics.
One thing you could do is write a simple unit test to verify that all of the types in a particular assembly obey your rules. If other developers will also be implementing the interface, you could put that test code into some common place so that everyone implementing the interface can easily test their own assemblies.
This is a great question and one that I've encountered in my projects.
Some people hold that interfaces and abstract classes exist for polymorphism only, not for forcing types to implement certain methods. Personally, I consider polymorphism a primary use case, and forced implementation a secondary. I do use the forced implementation technique fairly often. Typically, it appears in framework code implementing a template pattern. The base/template class encapsulates some complex idea, and subclasses provide numerous variations by implementing the abstract methods. One pragmatic benefit is that the abstract methods provide guidance to other developers implementing the subclasses. Visual Studio even has the ability to stub the methods out for you. This is especially helpful when a maintenance developer needs to add a new subclass months or years later.
The downside is that there is no specific support for some of these template scenarios in C#. Static methods are one. Another one is constructors; ideally, ISerializable should force the developer to implement the protected serialization constructor.
The easiest approach probably is (as suggested earlier) to use an automated test to check that the static method is implemented on the desired types. Another viable idea already mentioned is to implement a static analysis rule.
A third option is to use an Aspect-Oriented Programming framework such as PostSharp. PostSharp supports compile-time validation of aspects. You can write .NET code that reflects over the assembly at compile time, generating arbitrary warnings and errors. Usually, you do this to validate that an aspect usage is appropriate, but I don't see why you couldn't use it for validating template rules as well.
Unfortunately, no, there's nothing like this built into the language.
While there is no language support for this, you could use a static analysis tool to enforce it. For example, you could write a custom rule for FxCop that detects an attribute or interface implementation on a class and then checks for the existence of certain static methods.
The singleton pattern does not help in all cases. My example is from an actual project of mine. It is not contrived.
I have a class (let's call it "Widget") that inherits from a class in a third-party ORM. If I instantiate a Widget object (therefore creating a row in the db) just to make sure my static methods are declared, I'm making a bigger mess than the one I'm trying to clean up.
If I create this extra object in the data store, I've got to hide it from users, calculations, etc.
I use interfaces in C# to make sure that I implement common features in a set of classes.
Some of the methods that implement these features require instance data to run. I code these methods as instance methods, and use a C# interface to make sure they exist in the class.
Some of these methods do not require instance data, so they are static methods. If I could declare interfaces with static methods, the compiler could check whether or not these methods exist in the class that says it implements the interface.
No, there would be no point in this feature. Interfaces are basically a scaled down form of multiple inheritance. They tell the compiler how to set up the virtual function table so that non-static virtual methods can be called properly in descendant classes. Static methods can't be virtual, hence, there's no point in using interfaces for them.
The approach that gets you closer to what you need is a singleton, as Marc Gravell suggested.
Interfaces, among other things, let you provide some level of abstraction to your classes so you can use a given API regardless of the type that implements it. However, since you DO need to know the type of a static class in order to use it, why would you want to enforce that class to implement a set of functions?
Maybe you could use a custom attribute like [ImplementsXXXInterface] and provide some run time checking to ensure that classes with this attribute actually implement the interface you need?
If you're just after getting those compiler errors, consider this setup:
Define the methods in an interface.
Declare the methods with abstract.
Implement the public static methods, and have the abstract method overrides simply call the static methods.
It's a little bit of extra code, but you'll know when someone isn't implementing a required method.

Categories