Fastest way to call a COM objects method without using a RCW - reflection

I'm trying to find the cleanest and fastest way for calling a COM objects methods.
I was using a RCW for the object but every time a new version of the third party COM object comes out its GUID changes which then renders the RCW useless, so I had to change and start using
Type mytype = Type.GetTypeFromProgID("MyCOMApp.Application");
so that every time a new version of the COM object comes out I don't have to recomplie and redeploy my app.
At the moment I am using refelection like mytype.InvokeMemeber but I feel it is so slow compared to just calling the RCW.
How does everyone else tackle the problem of changing 3rd party COM object versions, but still maintaining the speed of a RCW?

If you want to make the calls in reflection easier, you could use VB.NET, and make late calls on a variable typed as Object. VB.NET will help with the calls to reflection. You can also set a reference to Microsoft.VisualBasic.dll and make the call to CallByName as well to help with the reflection calls.
However, is it the IID (the interface GUID) or the class GUID that changes? If it is the class GUID that changes, then you can define the interface once, and then get the Type through a call to GetTypeFromProgID. Once you have that, you can pass the type to the CreateInstance method on the Activator class and then cast to the interface, which won't change.
If the IID does change, however, you will have to use reflection every time.

Related

Modifying a Biztalk message from custom code

Disclaimer: I am a complete biztalk newbie.
I need to be able to read and potentially edit 4 nodes in a biztalk message; preferably this needs to be done from a c# helper class as I am making a service call and also have unit tests written for this.
I already have this class wired up and it works with the XLANGMessage class, the problem I am running into is at this point in the orchestration the message is a Schema based type and doesn't seem to have any way for me to modify it.
I've done some reading and found a few ideas but have not been able to confirm if any of these can work from custom code.
1 write a map to transform the incoming message to the desired type
or
2 write something like this in your helper component to transform the message
public XmlDocument TransformMessage(XLANGMessage message)
Then pass the result document to a biztalk message in a message assignment shape.
responseMessage = xmlDocument;
You may get better performance if you pass streams instead of messages around.
You can pass messages into and out of C# helper classes easily. The simplest way is just to treat input parameters and return values as of type System.Xml.XmlDocument. The XLANG/s engine will safely cast back and forth from the XLANGMessage type to XmlDocument.
As you are essentially creating a "new" instance of the message (messages are immutable in BizTalk), the call to your helper class needs to be performed in a Message Assignment shape, with the outer Construct shape constructing the copy of your original message.
public static XmlDocument UpdateMyMessage(XmlDocument sourceMessage)
{
/* Do stuff to your Message here */
return sourceMessage;
}
A best-practice to consider is to declare all your C# helper methods as Static. This will avoid any issues with de/serialisation of your helper class during dehydration.
Are BizTalk messages immutable?
Generally speaking they are however, by creating a “corrective” orchestration and using a pass by reference option on the incoming message parameter, an existing message can be modified.

How does ninject work at a high level, how does it intercept object instantiation?

At a high level, how do these dep. injection frameworks work?
I can understand if you always instantiate an object via a custom factory like:
IUser user = DepInjector.Get<User>();
I'm guessing what happens is, wherever you defined the mappings, it will look at the type you want and try and find a match, if found, it will via reflection instantiate the type.
Are there dep. inj. frameworks that would work like:
IUser user = new User();
If so, how would it get the correct user, where is it hooking into the CLR to do this? In case of an asp.net website, is it any different?
If you want to know how Ninject works then the obvious place to start would be reading How Injection Works on their official wiki. It does use reflection but it now also uses dynamic methods:
"By default, the StandardKernel will
create dynamic methods (via
System.Reflection.Emit.DynamicMethod)
that can be used to inject values into
the different injection targets. These
dynamic methods are then triggered via
delegate calls."
As for you second example, I don't believe there are any DI frameworks that would do what you ask. However, constructor injection tends to be most common way of implementing IoC, so that when a class is constructed it knows what type to bind to via some configuration binding. So in your example IUser would be mapped to concrete User in config bindings so that any consuming class that has an IUser parameter as part of its constructor would get the correct User type passed in.
AFAIK there's no way to "hook into" object instantiation with the CLR. The only way to use DI in the second case would be to employ an assembly rewriter (i.e. a postprocessor similar to PostSharp) to replace the call to new with a call to the DI factory method (i.e. GetUser) in the compiled code.

NHibernate.IFutureValue<> when serialized includes .Value

I'm building an ASP.NET (2.0, no, I can't change it) site with NHibernate, and have a custom JSON converter so I can not-serialize properties I want hidden from the client. This lets me just return the objects, and never have to worry about their serialized values - they're always secure.
Unfortunately, it appears that if I use query.FutureValue<class>(), the object that gets serialized is first the NHibernate.Impl.FutureValue<class> and not my entity, which means I get JSON that looks like this if I throw it in a dictionary and return it to the client:
{key: { Value: { /* my serialized object properties */ } }
Previously I discovered that I can't get any interfaces to work in ASP's JavaScriptConverter implementations... only regular or abstract classes. So returning typeof(IFutureValue<MyBaseClass>) as a supported type means my converter is completely ignored. I can catch MyBaseClass, because I refactored things earlier to use an abstract base instead of an interface, but not the interface.
And then I discover that the FutureValue implementation in .Impl is internal to the assembly, or some other such nonsense that only serves to make my .NET experience even more painful. So I can't use typeof(FutureValue<MyBaseClass>) to handle it all, because FutureValue exists only in my debugging sessions.
Is there a way to get the class type out of the assembly? Or a way to convince ASP that interfaces do in fact have uses? Or might there be some superclass I can access that would let me get around the whole issue?
Help! I like my Futures, it lets me batch a whole heck-ton of calls at once!
(if something isn't clear, or you want more code, by all means, ask! I can post quite a bit.)
If I'm understanding you correctly, it seems you are mixing things a together a little bit.
It sounds like you're trying to serialize an instance of query.FutureValue<class>(), which unsurprisingly gives you just that: a JSON object where the Value fields has JSON representing your entity.
To me it sounds like you really want to just serialize query.FutureValue<class>().Value.
Using NHibernate futures like this gives you little benefit though, so you're probably after something like:
var future1 = query1.FutureValue<SomeEntity>();
var future2 = query2.FutureValue<AnotherEntity>();
var json1 = serializer.Serialize(future1.Value); //<BAM! Multi-query gets fired!
var json2 = serializer.Serialize(future2.Value);
Does that make sense?

can I use Moq to grab values that are passed into a public method of an object that is not a mock?

I'm writing a unit test for FluentMigrator. I am testing a method that gets called n times in succession. What I'd like to do is grab the successive inputs and stow them in a SortedList, so that I can verify the methods were called in the right order, then pass those inputs to the actual method -- like a temporary redirect. But, after reading the docs etc, I can't get it to work.
Code in the test:
var listOfVersions = new SortedList<int, long>();
int i = 0;
var runnerMock = Mock.Get(_runner); // runner is a MigrationRunner
runnerMock.Setup(r => r.RollbackToVersion(2))
.Callback((long v) =>
{
listOfVersions.Add(i, v);
i++;
_runner.RollbackToVersion(v, true); });
_runner.RollbackToVersion(2);
The error:
System.ArgumentException : Object instance was not created by Moq.
Parameter name: mocked
I'm coming from Moles, where dipping into the behavior of an object and then redirecting it isn't unusual. Maybe it is in Moq?
No. Really mocking frameworks fall into 2 camps. The ones that can mock anything and the other than can only mock Interfaces, Abstract/Virtual methods.
This is because they use very much a different interception technology. Moq, RhinoMocks etc use Castle's Dynamic Proxy Generator under the hood which all it does create an instance that exposes the same public interface. It uses this to record interactions with that object so you can verify on it. Abstract and Virtual members can be mocked cause it can derive from that class and prevent calls to the base class.
However Moles and TypeMock Isloator play around with the IL directly. I know for TypeMock it actually weaves IL into the methods you are trying to mock so you can intercept and record interactions on it for testing (It also stops further processing of the methods also). I know that Moles creates another assembly and you refer to that in your test method but I imagine it does very similar things to TypeMock.
If you want to mock concrete non overrideable methods you will have to use that latter frameworks.

Calling a getter without assigning it to anything (lazy loading)

I have a DTO which can be fully loaded or lazy loaded using Lazy Load Pattern. How it is loaded depends on what the Flex Application needs. However, this DTO will be sent to a Flex application (swf). Normally, a collection for instance, will only be loaded when called. In my case however, the collection will only be called in Flex, so my implementation on the .NET side will obviously not work in this case (except if Flex would do a server call... something I would like to avoid).
In the getter of the collection, the data is retrieved from the database. If I would be working with ASP.NET pages, it would work, but not if the DTO is sent to Flex.
How would you deal with this? I could call the getter before sending the DTO to Flex, but that seems awful... + calling the getter can only be done if it is assigned to something (and the local variable that will hold the collection will never be used...).
You can introduce a method to load dependents - loadDependencies - that should take of all lazy loading for your DTO object before being sent over the wire (to Flex). You can abstract this method to an interface to streamline such process across different DTOs. There is nothing against using getters the way you described it inside this method.
I would probably introduce a Finalize method for the class and perhaps a FinalizeAll extension method for various collections of the class. This method would simply go through and reference all the getters on the public properties of the class to ensure that they are loaded. You would invoke Finalize (or FinalizeAll) before sending the object(s) to your Flex app. You might even want to make this an interface so that you can test for the need for finalization before transfering your objects and invoke the method based on a test for the interface rather than checking for each class individually.
NOTE: Finalize is just the first name that popped into mind. There may be (probably is) a better name for this.

Resources