How to mark .NET objects exposed to COM-interop as single threaded? - c#

When defining a COM-visible class in C++ I can define the supported threading model in the header file (the threading(single) line):
[
coclass,
default(IComInterface),
threading(single),
vi_progid("Example.ComClass"),
progid("Example.ComClass.1"),
version(1.0),
uuid("72861DF5-4C77-43ec-A4DC-ED04396F0CCD")
]
Is there a comparable way of setting the threading model in .NET (for example an attribute)? I currently define my COM-class as such:
[Guid("67155A91-2948-43f5-B07F-5C55CDD240E5")]
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IComInterface
{
...
}
[Guid("DC5E6955-BB29-44c8-9FC0-6AADEEB2AFFB")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("Example.ComClass")]
public class ComClass : IComInterface
{
...
}
--edit:
The comments on the marked answer are the really important thing. It seems like the only way to tell RegAsm to set a different ThreadingModel is to write a custom registration method marked with the [ComRegisterFunction]attribute.

That's really obscure, I've never seen the "threading" attribute in MIDL. Nor have the MSDN Library authors.
A COM coclass publishes its threading requirements in the registry, using the HKCR\CLSID\{guid}\InProcServer32 key. The ThreadingModel value declares the apartment it needs. If it is missing or is set to "Apartment" then is announces that is not thread-safe and requires help from an STA thread. CoCreateInstance() uses this value when it creates the object. If necessary it will start an STA thread and create a proxy if the current thread is not STA, ensuring it is always used in a thread-safe way.
A [ComVisible] .NET class will be registered as "Both", indicating that it is okay to be used on a thread in the MTA. Pretty optimistic, but follows the .NET philosophy that everything is thread-unsafe but can be made safe by putting the lock keyword in the right places. A promise that is not often tested btw, risky. Overriding the ThreadingModel value (or omitting it) requires writing code to register the coclass yourself, decorated with the [ComRegisterFunction] attribute. RegistrationServices.RegisterTypeForComClients() can be useful to get the basic keys into place.

Related

Is It Possible to Access Introduced/Weaved Interfaces and Members by PostSharp During Build Time?

I am designing a scenario where two PostSharp aspects are working with each other. I have one aspect (FirstAspect in the code below) that is meant to introduce an interface, and then another aspect (SecondAspect in the code below) is supposed to work with the interface that was introduced by the first aspect.
However, it does not seem that the interface that is introduced by the first aspect is ever available to the second aspect.
Here is the code that I am currently working with:
public class Tests
{
[Fact]
public void Verify()
{
// Not really all that significant as the current code does not compile correctly:
var sut = new MyClass();
Assert.True( sut is IInterface );
}
public interface IInterface
{
void HelloWorld();
}
[IntroduceInterface( typeof(IInterface) )]
public class FirstAspect : InstanceLevelAspect, IInterface, IAspectProvider
{
public void HelloWorld() {}
public IEnumerable<AspectInstance> ProvideAspects( object targetElement )
{
// Implementing IAspectProvider appears to ensure this aspect is processed first.
// This may be a bug.
// Please see: http://support.sharpcrafters.com/discussions/problems/3365-runtimeinitialize-does-not-follow-ordering-rules#comment_40824072
// for more information.
yield break;
}
}
[AspectTypeDependency( AspectDependencyAction.Order, AspectDependencyPosition.After, typeof(FirstAspect) )]
public class SecondAspect : InstanceLevelAspect, IAspectProvider
{
public IEnumerable<AspectInstance> ProvideAspects( object targetElement )
{
var type = (Type)targetElement;
if ( !typeof(IInterface).GetTypeInfo().IsAssignableFrom( type ) )
{
// This is currently being thrown, as MyClass does not implement
// IInterface when the AppDomain is first loaded and initialized:
throw new InvalidOperationException( $"Does not implement {typeof(IInterface)}" );
}
// How to access the weaved elements from FirstAspect? ...
yield break;
}
}
[FirstAspect, SecondAspect]
class MyClass {}
}
When I build, the InvalidOperationException in the SecondAspect.ProvideAspects is thrown, as the interface that was introduced by FirstAspect is not available to SecondAspect at the time the call is made. That is, even though the interface has been weaved into the MyClass type, the type as it stands within the current AppDomain as loaded is not marked as having the interface implemented.
What I am looking for is the ability to access and locate all known and weaved interfaces and members on a target element during build time.
I looked into ReflectionSearch, and this is close to what I am looking for, but it does not appear to account for weaved elements at the time calls into this API are made. For instance, making a call to ReflectionSearch.GetMembersOfType does not yield the expected IInterface.HelloWorld on MyClass (which is introduced by FirstAspect in the example above).
Is there another API I should be using to access introduced/weaved elements by PostSharp during build-time? Is this even possible?
So this question looks a little old, but I have a similar issue which I still need an answer to (which is: how do I introduce an attribute to an introduced method without applying the attribute to the implementation and copying it). That said, I may have to ask my own question, as there are some common steps for the pattern you're asking about which may solve your dilemma, but do not solve mine. It looks like you've already experimented with some of this, but for the sake of others that come along, I'll detail it out.
In short, don't use "reflection" types to specify aspect dependency. PostSharp provides attributes which you can use to require aspects to be applied or to require specific order (See: Coping with Several Aspects on the Same Target for an overview), as well as a method for importing members already provided by other aspects (This StackOverflow Answer, while not marked, is the correct answer to that user's question and also shows a way to use the ImportMemberAttribute together with aspect dependency). The ImportMemberAttribute is capable of importing members from other aspects as long as the order is correct; the IsRequired property on this attribute will cause a build error if the member does not exist and was not introduced by an aspect.
Now, if you want your second aspect to be able to apply to all classes that implement an interface, whether the interface was applied by your first aspect or not, you would set the AspectTypeDependencyAttribute with AspectDependencyAction.Order, but not set an AspectTypeDependencyAttribute with AspectDependencyAction.Required; if you only want the second aspect to apply to targets advised by the first then you can apply multiple dependency attributes to specify both the requirement and the order and no Aspect Provider would be required (the above answer also shows an alternative implementation applying Advice to multiple Pointcuts in a single Aspect). Similarly, if you want your first aspect to always require your second aspect you can apply an additional AspectTypeDependencyAttribute to specify requirement in the other direction (i.e. if both require the other you want the requirement specified on both).
Aspect "Priority" can also be used to determine the order aspects are applied, although whenever possible you should use the dependencies instead because they also server as contract documentation.
This is all assuming you don't actually need to use an Aspect Provider (since your comments imply it was done for ordering). You would not want one Aspect Provider to depend on the results of another Aspect Provider (this would violate separation of concerns), you would instead have a single Aspect Provider yield multiple aspects for each target. You can, however, use AspectTypeDependencyAttribute on Aspect Providers as well so, for instance, you can have a Type Level Aspect Provider that orders after a type level aspect that introduces an interface and then in the provider you can loop through methods on the type and inject aspects that depend on the first aspect (e.g. an interface introduction follower by a provider that applies method interception advice to members that can now call methods introduced by the first aspect).
Hope that clears things up for you (or, given the time since the question was asked, anyone else that runs into this issue). Some of this information may also be outdated or inaccurate (for all I know, it may now be possible to detect injected interfaces on the target types passed to aspect providers, under some or any condition), but I believe the patterns expressed are still the preferred practice proposed by PostSharp.

Naming convention: How to name a different version of the same class?

I have a class MyClass which has a bug in the implementation. The class is part of a library, so I can't change the implementation of the class because it will silently change behavior for existing clients (clients who in this case may rely on the bug: See for example (https://connect.microsoft.com/VisualStudio/feedback/details/790160/httpclient-throws-operationcanceledexception-insead-of-timeoutexception))
I need to create a second version of the same class which includes the bug fix.
I've seen situations like this before but the naming I've seen was always incremental Eg MyClass2 , MyClass3.
These cases are probably quite rare, however I was wondering if there is a better way of naming these "versioned" classes.
I imagine a solution which grows in time and has multiple classes of these type which can get probably really confusing especially for a library. I imagine myself having to pick between MyClass, MyClassV2, MyClassV3 etc.
In an ideal world, new versions would introduce additional functionality while still remaining 100% backwards compatibility with previous versions of the API. Unfortunately, the ideal world remains elusive, and it is not always possible to retain full backwards compatibility. A versioned suffix is the appropriate pattern in this case.
The standard .NET naming convention is to use incremental numbering, like Class, Class2, Class3, etc.. This comes from the naming convention for COM interfaces, designed for exactly the use case you're describing. For example, the IHTMLDocument interface currently has 8 versions, from IHTMLDocument up through IHTMLDocument8.
The original Framework Design Guidelines book, by Cwalina and Abrams, explicitly recommended this practice, with the authors having this to say:
DO use a numeric suffix to indicate a new version of the existing API, if the existing name of the API is the only name that makes sense (i.e., it is an industry standard), and adding any meaningful suffix (or changing the name) is not an appropriate option.
// old API
[Obsolete("This type is obsolete. Please use the new version of the same class, X509Certificate2."]
public class X509Certificate { ... }
// new API
public class X509Certificate2 { ... }
The old convention, followed by the original Windows team, was to add the suffix Ex to new-and-improved versions of an API, which comes from the word "extend." This doesn't scale well, however, leading to functions confusingly suffixed ExEx. I don't think there was an ExExEx; everyone was afraid to touch those APIs. The Framework Design Guidelines recommend explicitly against this practice, the folks who went on to architect .NET having learned their lesson:
DO NOT use the "Ex" (or similar) suffix for an identifier to distinguish it from an earlier version of the same API.
[Obsolete("This type is obsolete. ..."]
public class Car { ... }
// new API
public class CarEx { ... } // the wrong way
public class CarNew { ... } // the wrong way
public class Car2 { ... } // the right way
public class Automobile { ... } // the right way
Obviously, as their last code sample hints, if you are adding support for a specific feature in the new version of the API, you would be best off naming the new class/interface with a reference to that particular feature.
And although the above has focused almost exclusively on classes and interfaces, the same logic would hold true for any member functions of that class that might be added in later revisions. The original function could retain its original name, with the newly added function having a different name that either reflects its iteration or its added functionality.
I was wondering if there is a better way of naming these "versioned" classes.
There is no .NET naming convention for "classes which fix bugs in other classes". I would advise with other developers in your workplace and see if they have any company conventions for such a thing. I think consistency is of importance more than the actual name.
And on a side note to your problem, I wouldn't create a new class at all. I would mark the method with DeprecatedAttribute and implement the logic inside the same class, exposing a new set of API methods which are properly documented to state they are here as a fix. The clients of your library are probably already familiar with MyClass, and doing so would ease the use for them, interleaving them the need to ask themselves each time "which version of this should I use".
I would copy all the behaviour of your existing class to a new one, rename the original one to indicate that the class is obsolete, rename the new one to the actual name from before and mark the original one (with the new name now) as [Obsolete] indicating that it should not be used any more. Thus all consuming code automatically invokles the new behaviour. So your new class with the correct behaviour gets the name of the original class, where the buggy one gets a version-number for instance.
For legacy code you can do the opposite, make a new class with new name and mark the old one as Obsolete. I know SDKs with a version-number, where the last number indicates the most recent version of the class, and all the others have such an attribute together with a notice within the docs mentioning that the class is superseded with a new version.
For clarity, if that happens, I use ClassV2. That indicates that it's another version of the class.
I think duplication class name will seriously confuse other people overtime. You extract method with c# interface and implement different version.

Reasoning behind implementing Dispose but not implement IDisposable?

I am refactoring a program right now. Trying to prevent memory leaks I was looking for objects to enclose in using blocks when I found a TaskDefinition object (class found in Microsoft.Win32.TaskScheduler) that Dispose was not called on. When I tried to enclose it VisualStudio told me that this class does not implement IDisosable. Looking at the class this is certainly true:
namespace Microsoft.Win32.TaskScheduler
{
// Summary:
// Defines all the components of a task, such as the task settings, triggers,
// actions, and registration information.
public sealed class TaskDefinition
{
...
// Summary:
// Releases all resources used by this class.
public void Dispose();
}
}
So why would you implement a Dispose method but not implement the IDisposable interface? Are there any drawbacks from implementing the interface?
Thank you for helping me to understand this.
From the comments:
According to this page, this is a bug that's fixed in newer versions of the assembly.
An additional note, however: the documentation for IDisposable.Dispose explicitly requires implementations to support calling Dispose multiple times, so a valid reason in other cases could be that the class does not support that. In that case, pretending to implement IDisposable but not meeting its requirements would be worse than not implementing it.

Attribute, interface, or abstract class

I'm wondering what the general recommendation would be (attribute, interface, abstract class, or combination thereof) for the following implementation:
/// <summary>
/// Loads class specific information into a list for serialization. The class must extend PlugIn.
/// The filenames parameter is passed from a FileDialog.
/// </summary>
/// <param name="filenames">Accepts any number of filenames with fully qualified paths.</param>
public static void ExtractPlugInData(params string[] filenames)
{
List<Type> l;
foreach (string f in filenames)
{
Assembly a = Assembly.LoadFrom(f);
// lambda expression selects any class within a library extending the abstract PlugIn class
l = a.GetTypes().Where(type => typeof(PlugIn).IsAssignableFrom(type)).ToList<Type>();
if (l.Count > 0)
// write data to serializable class
WritePlugInData(f , l);
else
// throw exception
WriteLine("{0} :: No PlugIn Data Found" , a.FullName);
}
}
I realize there are advantages and disadvantages to each method. Obviously, attributes require some reflection (as do abstract extension and interface implementation). An abstract class takes our only base inheritance, and any future changes in an interface can break any existing plugins. So, as I see it, those are the disadvantages.
Performance is not an issue (unless there is something I don't see) since any reflection is only done once when a qualified class is extracted. The key pieces of data that are getting saved is a name for the plugin ("MyPlugIn"), the namespace ("SuperPlugIn.PlugInClass"), and the startup path for the .dll. Right now, with the abstract PlugIn class, the extension of the properties is enforced. This is more or less the same result if we implement an interface (IPlugIn).
We are allowing custom plugins to be written by end-users. With the plugins we are writing in-house, it is easy to teach and enforce a required structure for our application to instance a qualified class. However, I'm also considering the difficulties or inconvenience to the end-user should there be a major change.
All comments, suggestions, and questions welcome!!
Note: thanks go to Jon Skeet for the lambda expression in the snippet. :)
EDIT: I should have noted in the beginning that this is intended to be platform independent (i.e. Mono).
UPDATE: Based on the excellent recommendations, comments, and links below, a mix of attributes and interfaces is the best approach. Attributes let you load the assembly and check for required information and implementations rather safely without instancing the plugin classes/objects. This is ideal in situations where 3rd party or end users are allowed to create custom plugins. We can check to ensure that the proper contract implementation is in place where the attribute says it's suppose to be. We can check for required dependencies and resources and alert the developer of any problems before anything is instanced.
You want your end users to write plugins? I don't think that's a very good idea, unless your end users are programmers.
I'm going to keep my answer short this time since this is a pretty big honkin' dupe:
Plug-in architectures almost always involve classes in an external assembly implementing a specific interface in a common assembly;
There are already dozens of cookie-cutter .NET plugin implementations including Microsoft's own Managed Extensibility Framework. Don't reinvent the wheel.
Edit: For Mono, check out Mono.Addins.
I'd probably tend to use attributes. Extending the base class system with metadata is kind of exactly what they're for, and saying 'this class is a plugin' certainly fits that bill.
Assembly.GetTypes is a very expensive call, and I would avoid it where possible. (App startup time matters)
The faster way to do this is probably (I haven't benchmarked) an assembly-level attribute, which would be used like this:
[assembly: PluginClass(typeof(MyPlugin), more info)]
You can then call GetCustomAttributes on the Assembly, which would probably be much faster than GetTypes.
Using LINQ:
filenames.SelectMany(f =>
Assembly.LoadFrom(f).GetCustomAttributes(typeof(PluginClassAttribute), true)
.Cast<PluginClassAttribute>()
.Select(a => a.PluginType)
).ToList();

Purpose of having API wrapped around interface

I am working on a piece of C# web application that has a page (MainPage) with a small area to display a gadget. There are several kinds of gadgets implementing a main interface (IMainInterface) and an optional interface (IOptionalInterface).
In MainPage, when interacting with the gadget class, it uses following syntax:
MyAPI api = new MyAPI();
api.SomeMethod(gadgetClassName, param);
And in api.SomeMethod(...), it does following:
// use reflection to get an IMainInterface based on gadgetClassName
Type t = Type.GetType(gadgetClassName);
IMainInterface gadget = (IMainInterface)t.InvokeMember(
gadgetClassName,
BindingFlags.CreateInstance,
null,
null,
null);
return gadget.SomeMethod(param)
Looking at this MyAPI class, it contains a whole bunch of methods that map to the corresponding methods defined in IMainInterface and IOptionalInterface.
My question, is this MyAPI class really neccesary? Wouldn't it be less overhead if MainPage accesses interfaces(IMainInterface and IOptionalInterface) directly?
Update: seeing some of the answers, I realized that I wasn't explicit that the "several kinds of gadget" means different classes (e.g. CalendarGadget, TaskGadget).
Update 2: Added more code sample
The MyApi class looks like it's shielding you from using reflection to create the object, null checks if the optional interface isn't in use, and probably the whole fact of using interfaces in general. Without all the code it's conjecture. As Dzmitry Huba points out, mixing a factory and a wrapper is a bad smell, and you should try to refactor that out.
static class GadgetFactory
{
public static IMainInterface GetGadget(string className)
{
(IMainInterface)Activator.CreateInstance(Type.GetType(className))
}
}
A factory decouples the logic of creation, but it should only be responsible for creation.
Q: Is there any logic in myAPI, or is it just creating and then dispatching if the gadget supports the interface?
If MyApi doesn't have any logic, it's hard to see why it's necessary. Perhaps the writer of MyApi didn't realize at the time that you can cast to the other interface when needed. I have a hunch that they were trying to shield junior developers from interfaces.
// basic use of interfaces
IMainInterface gadget = GadgetFactory.GetGadget("Gadgets.Calendar");
gadget.SomeMethod();
IOptionalInterface optional = gadget as IOptionalInterface;
if( optional != null ) // if optional is null, the interface is not supported
optional.SomeOptionalMethod();
A relevant SO question Difference between Activator.CreateInstance() and typeof(T).InvokeMember() with BindingFlags.CreateInstance
It seems the author of MyApi mixed factory and consumer. I do not see any reason to access interface members indirectly when it is defined at compile time.
Yes, from the description in your question, I'd say reflection or any other indirection mechanism is unnecessary. I'm not sure if that answers your question though?
// in MainPage:
IList<IMainInterface> gadgets = new List<IMainInterface>
{
(IMainInterface)Activator.CreateInstance(Type.GetType("Gadgets.CalendarGadget")),
(IMainInterface)Activator.CreateInstance(Type.GetType("Gadgets.TaskGadget")),
};
Generally this is not bad. But I guess that this is complete overkill for your intentions. I would suggest to borrow something from IOC.
var api = new MyAPI(new GadgetClass());
api.SomeMethod(parameters);
This would make your life much less complicated.
Hope this helps

Categories