Allow only single instance of COM object - com

Is there a good way to enforce that only one instance of my COM object (served by an in-process server) may be created at any one time?
Currently I am creating a Windows Mutex in the constructor of TMyObjectImpl; and if the mutex already exists then I set a flag to put my object into a "dead" state: when this flag is set, all implementations of interface functions will return an error code.
I would like to throw an exception instead of creating a "dead" object like this, however it is not good to throw C++ exceptions across a COM boundary and I'm not sure if the C++Builder implementation of COM can cope with this reliably.
There are actually two possible problem scenarios:
The same process creates two of MyObject
Two different processes create one each of MyObject
The Mutex guards against both of these.
My object factory function is:
static void createFactory()
{
new TCppAutoObjectFactory<TMyObjectImpl>(Comserv::GetComServer(),
__classid(TMyObjectImpl),
CLSID_MyObject,
Comobj::ciMultiInstance,
Comobj::tmSingle);
}
#pragma startup createFactory 32
According to the C++Builder DocWiki, setting the Instancing property has no effect for in-process servers - it always behaves like ciMultiInstance even if you specify ciSingleInstance.
My object needs this property because it access global resources (e.g. writes to a file in a specific disk location); the semantics of the object are such that there is only supposed to be one open at a time. I'm not looking to add support for multiple instances of my object.

Related

Two SSLContext in same JVM

We are receiving a SSL handshaking exception when another part of the code is calling SSLContext.getInstance(). Can someone please confirm or deny the ability to have multiple concurrent SSLContexts running in the same JVM using the same provider? The method name getInstance implies a singleton.
Yes, you can have multiple SSLContext instances, configured differently if you wish.
getInstance(...) is generally part of the factory pattern, not the singleton pattern, although a number of implementations of the singleton pattern also use the factory pattern to access this singleton.
In addition, SSLContext.getInstance() doesn't exist, only getInstance(String), getInstance(String,String) or getInstance(String,Provider) (and having an argument on the getInstance method hardly makes sense for a singleton).
(Don't confuse this with SSLContext.getDefault(), which will always return the current default instance, although this can also be changed globally with setDefault(SSLContext).)
Just in case you were talking about SSLContext.getDefault() instead, it's worth noting that the default SSLContext will only read and use the javax.net.ssl.* system properties once, the first time it is loaded. This could have consequences if you set these properties somewhere within the code, but not somewhere else (or differently) and call SSLContext.getDefault() in a different order: the first call to SSLContext.getDefault() wins (assuming you're not complicating this with further calls to SSLContext.setDefault(...)).

COM-class without being able to instantiate

MSDN:
"You implement an IClassFactory interface for each (COM) class of object that you offer to be instantiated."
Is it useful to create COM class without Class Factory?
The IClassFactory is provided for objects which are instantiated directly by the caller, for example using CreateObject or CoCreateInstance, or GetObject.
Other objects can be obtained by getting them indirectly from objects that are created.
For example, the Scripting.FileSystemObject in VB or VBScript is created directly. You can use the methods to obtain File or Folder objects, which cannot be directly created. Instead these are created by the FileSystemObject and returned from FileSystemObject methods.
Is it useful to create COM class without Class Factory?
Yes, why not? It can still be fully featured COM class, just except that you cannot launch it via CoCreateInstance API. For some reason you might want to make it available otherwise, e.g. as a returned [out] parameter on a method of another interface/class, or via GetActiveObject API.
Class factories let you expose your class for direct instantiation.
I'm not entirely sure the wording is quite correct here. You almost always implement IClassFactory once for all COM classes of objects that your host will instantiate. In particular, your implementation of IClassFactory is what gets returned from DllGetClassObject.
In particular, when someone calls CoCreateInstance(CLSID_foo, pUnkOuter, CLSCTX_INPROC, IID_IFoo, (void **) &pFoo), the following things happen (assuming you're not doing remoting):
COM looks up CLSID_foo in the registry. (In particular, HKEY_CLASSES_ROOT\CLSID\\InprocServer32).
COM loads that DLL and calls DllGetClassObject with IID_IClassFactory.
Your DLL returns a function pointer to the implementation of IClassFactory.
COM calls your implementation of IClassFactory::CreateInstance with pUnkOuter, IID_IFoo, and pFoo.
There are many other situations where you would have COM objects that aren't directly creatable, as #Ben mentioned. There are even other standard factory interfaces, like IServiceProvider, that exist so that classes can expose a dynamic set of interfaces.

VB connect to COM object

Either I don't understand COM objects, either it's all that confusing.
I frequently 'create' , 'dispatch' COM objects - either in Python, either in VB ( Obj = win32com.client.Dispatch('Visum.Visum') or Obj = CreateObject("Excel.Application") respectively).
That's easy, obvious and everything's fine.
But how can I:
a) connect to COM object which is already running
b) get list of running processes which are COM objects
in VB what is the reference, and additional info on: CreateObject command. In Python it's part of well defined, comprehensive library of win32com whereas in VB it's just single method without reference: http://msdn.microsoft.com/en-us/library/7t9k08y5(v=vs.80).aspx
Highly confusing (COM object,server? connection, dispatching, registering??)
Thanks for claryfying
Rafal
i2
First of all, I would suggest reading a good introduction to COM. Personally, i think that 'Essential COM' by Don Box is the best book about COM. Spending a few hours with it will save you many hours later.
That being said, let's move to your questions.
a) In order to retrieve an existing COM object from VB, you need to call GetObject function. This will only work for COM objects which are registered with Running Object Table. Excel does this, so there shouldn't be any problems with that.
b) as Hans Passant correctly noted, this question doesn't make sense. Processes and COM objects are completely unrelated things, except for the fact that processes host the COM objects. It is similar to asking 'which processes are instances of class X'. However, a process can host a COM object (or many of them). These object can be alive only temporarily, so what would you expect there? Besides, many COM classes are implemented within dlls, but created instances obviously are hosted within a process - so what would you expect there?
COM technology is something I didn't not use for a while, so sorry if some info might be wrong (anyway, I've got my book "Inside COM+ base services" with me!)
Briefly speaking, let's give a simplified definition of a COM object: it nothing else than a standard DLL with classes exposing a standard interface IUnkown with the following methods:
AddRef: to register a client consuming the COM object
Release: to unregister a client (usually unused objects stop running, but other might remain resident)
QueryInterface: to get the address of a function
QueryInterface is used to dynamically retrieve the address of a function (late-binding) which is powerful (you don't have to know the DLL at compile time) but time consuming. On the other hand, you can directly reference the addresses of the functions at compile-time because those DLL are registered in the system (all the informations are stored in the registry)
Creating a new object or getting the address of a running object is done through RPC (remote procedure call) which will load and/or play the role of a proxy
So to create a new instance of a COM object, you will call CreateObject (in VB) (Co)CreateInstance in VC++ (or even c#?), while to get an executing instance, you might want to call GetObject().
Getting the list of COM objects is not that easy (I guess not possible at all) because, as told earlier, a COM object is nothing else but a DLL: this means that the library will mainly load in the address space of each process which access is private. Even for out-process COM objects (opposite to in-process) which are object shared between many processes (i.e.: Excel is an out-of-process COM object: you don't load the DLL in your application's address space), they are loaded by a host (rpc.exe or a proprietary host)
Hope this helps
Serge

Unexpected reinitialization of variables declared in VB6 DLL module

I have a VB6 DLL embedded in some ASP pages. The DLL hits a Codebase database, an obsure and obsolete database engine (a dialect/variation on dBase) that virtually no-one has even heard of. It takes Codebase nearly a second to initialise a new connection, which is unacceptably slow and so I've created a connection pool, managed by a VB class. The single instance of this class is created at the start of a VB module, i.e.:
Private m_codebaseManager As New CodebaseManager
My problem is that periodically the class initialization method is called again completely wrecking my pooling class and I've no idea why. Terminate does not fire and there's no sign of any crash occurring, so why on earth is initialize called? My understanding is that data in non-class modules persists for the lifetime of the DLL. Is that correct and if not, under what circumstances does a module 'restart'?
I would recommend removing the "New" from the variable declaration. Declaring a variable "As New" causes it to be checked every time it is referenced, and if set to Nothing a new instance of your CodebaseManager will be created.
A better solution would be to declare your variable like this:
Private m_codebaseManager As CodebaseManager
and then explicitly set it to a new instance when your application starts:
Set m_codebaseManager = New CodebaseManager
This means you can be sure you won't be creating any unintentional new instances of CodebaseManager. You'll probably then still have a bug but at least it will be an "Object or with block variable not set" error which you should be able to easily fix.
My understanding is that data in non-class modules persists for the lifetime of the DLL. Is that correct and if not, under what circumstances does a module 'restart'?
Sort of. Global state (module public/private vars) are apartment specific and is stored in TLS slots. VB6 supports apartment threading only, so each thread gets a "fresh" copy of the global state. Because ASP environment is multi-threaded so each thread gets a separate DB connection "pool".
If you need a real global state you have to use Application object to store it. If you put apartment threaded objects there (like VB6 ones) these can serialize you multi-threaded ASP environment and degrade performance. Use ADO objects or Dictionary objects or anything you are certain is free threaded.
Btw, you can let COM+ do the object/connection pooling for you. If OLEDB provider is a better one it can do connection pooling internally too (SQLOLEDB for MSSQL is an example).
But it's a DLL and not an ActiveX exe, so there's no Main() function and nowhere for the 'Set m_codebaseManager = New CodebaseManager' line to go except in global scope.

Create each COM-instance in it's own exe-container

Is there possible to create a COM-instance in it's own, dedicated, host-process?
I guess some background is needed.
We have an end-user client which has it's central logical components inside an singleton-COM object. (Not propper singleton, but it uses global variables internally, so it would fail.) So that there should be only one instance per exe-file. Convenient while making the client.
However, I should now make a "client-simulator" to test the server-side. I therefore which to make 20 instances of the client-component.
If I could make each instance instanciate in its own exe-host, then the singleton-issue would be handled.
Regards
Leif
I have been struggling with this problem for a few days. I finally found a solution that works. My COM object is written using ATL, so my code snippet will be geared toward that, but the technical solution should be clear. It all hinges on how the class objects are registered. The REGCLS_SINGLEUSE flag is the key. I now have separate processes for each object instance.
In the ATL module, override the RegisterClassObjects() function as follows:
HRESULT RegisterClassObjects(DWORD dwClsContext, DWORD dwFlags) throw()
{
return base::RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_SUSPENDED | REGCLS_SINGLEUSE);
}
From MSDN regarding REGCLS_SINGLEUSE:
REGCLS_SINGLEUSE
After an application is connected to a class object with
CoGetClassObject, the class object is removed from public view so that
no other applications can connect to it. This value is commonly used
for single document interface (SDI) applications. Specifying this
value does not affect the responsibility of the object application to
call CoRevokeClassObject; it must always call CoRevokeClassObject when
it is finished with an object class.
My theory is that because the registration was removed from public view, it causes a new process to be created for the subsequent instantiations.
This other question mentioned a description of how to use DLLHost as a surrogate process:
http://support.microsoft.com/kb/198891
I've never tried this myself, and I don't know off-hand if you can specify flags for the factories (which control if surrogates can be reused for multiple objects), but maybe you can tweak that via DCOMCNFG or OLEVIEW.
My COM days are long gone, but as far as I remember, there's no built-in way to do that.
It might be easier to rewrite your code so it supports multiple instances than to go the one-process-per-instance route with COM, but here's what you could do:
Use thread-local storage for your global variables and write another CoClass, where each instance owns its own thread through which accesses to the class with the global variables are marshaled. This would at least allow you to avoid the performance impact of DCOM.
Write your own out-of-process exe server (similar to windows' DllHost.exe) to host your COM instances. This requires IPC (Inter-Process Communication), so you either have to code something yourself that marshals calls to the external process or use DCOM (presuming your COM object implements IDispatch)