mov(wordpress, livespaces);

January 26, 2007

I no longer blog here. Visit me @ http://vivekragunathan.spaces.live.com.


out, ref and InvokeMember !!!

May 12, 2006

When I was working on the .NET reflection extravaganza thing that I explained in my previous column, i learnt one another interesting thing, that is about the Type.InvokeMember. How will pass out or ref parameters for the method invoked using Type.InvokeMember ? If you are going to invoke a method with the prototype

int DoSomething(string someString, int someInt);

then you would use InvokeMember like this:-

object obj = someType.InvokeMember("DoSomething",   
	BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,   
	null,   
	this,   
	new object[] {"Largest Integer", 1});

or use some variables in the new object[] {…}. But what do you with the args if DoSomething takes out or ref parameters ?

int DoSomething(out string someString, ref int someInt);

Something like this will not work

string someText = string.Empty;   
int someInt = 0;   
object obj = someType.InvokeMember("DoSomething",   
	BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,   
	null,   
	this,   
	new object[] {someText, someInt});

It is tricky.

object[] args = new object[] { someText, someInt };   
object obj = someType.InvokeMember("DoSomething",   
	BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,   
	null,   
	this,   
	args);

or even suprisingly this works:-

object[] args = new object[2];   
// or object[] args = new object[] { null, null };            

object obj = someType.InvokeMember("DoSomething",   
	BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,   
	null,   
	this,   
	args);

Access the values by indexing args. So declaring the argument object[] as a local variable solves the problem, but I do not understand why this behaviour. May be somebody can explain !!!


.NET Reflection Extravanganza !!!

May 11, 2006

I was involved in this module for the past few weeks and successfully completed it in a very innovative way. Ok, this was the problem. We have a COM server, let us name it Server. I had to write an assembly in C#, let us call it Bridge, that will listen to all of the events fired by the Server and perform an action Action. To keep that Action simple, let us assume we have to log them in the database. But the Server fires hundreds of events, and it is not wise to write up static event handlers for all of them. Also if more events are added in the future, it is possible to support the Bridge.

So I came up with a different approach with the incredible Reflection in .NET. All of the events fired by the Server, its prototype and other relevant information can be got through reflection, and for each of the event methods, an event sink [event handler] can be generated at runtime. This means I have to create a method at runtime matching the prototype of the event. The dynamic method thus generated runtime has to appended with some method body so as to do the Action, and then has to be registered as the event sink for the corresponding event. So when the event is fired by the Server, the dynamically created event handler is called without any intervention. This is the theme of my solution. This keeps the Bridge unaffected for any event related changes in the Server.

But achieving this solution and make it work, it was a great and exciting adventure.

1. I was able to get the event information about the events fired by Server through reflection. I used the following sort of code for generating the dynamic method or the supposedly the dynamic event handler:-


using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;

class TaskDynamicEventHandler
{

public static void CreateDynamicEventHandler(ref TypeBuilder myTypeBld,
                         string methodName,
                         Type[] eventMethodParameters,
                         Type eventreturnType)
    {

MethodBuilder myMthdBld = myTypeBld.DefineMethod(methodName,
                          MethodAttributes.Public | MethodAttributes.Static,
                          eventreturnType,
                          eventMethodParameters);

ILGenerator ILout = myMthdBld.GetILGenerator();

int numParams = eventMethodParameters.Length;

for (byte x = 0; x < numParams; x++)
        {
            // Load the parameter onto the evaulation stack
            ILout.Emit(OpCodes.Ldarg_S, x);
        }

// Use the above sort of logic to access the event parameter
        // values and then package into a hashtable, and then call
        // a static method HandleEvent in TaskDynamicEventHandler,
        // which takes the hashtable as a parameter. All the code is
        // generated in IL using ILGenerator.

ILout.Emit(OpCodes.Ret);
    }

public static void Main()
    {

AppDomain myDomain = Thread.GetDomain();
        AssemblyName asmName = new AssemblyName("DynamicAssembly1");
        AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(asmName,
                       AssemblyBuilderAccess.RunAndSave);

ModuleBuilder myModule = myAsmBuilder.DefineDynamicModule("DynamicModule1",
                                      "MyDynamicAsm.dll");

TypeBuilder myTypeBld = myModule.DefineType("MyDynamicType", TypeAttributes.Public);

string dynamicMethodName = "DynamicEventHandler";
        CreateDynamicEventHandler(myTypeBld,
                         dynamicMethodName,
                         eventMethodParameters,
                         eventreturnType);        

Type myType = myTypeBld.CreateType();

myAsmBuilder.Save("MyDynamicAsm.dll");

// returnType - event method's return type
        // parameterTypes - event method's parameter types list
        ArrayList parameterTypes = new ArrayList(parameterTypes);
        parameterTypes.Insert(0, this.GetType());

DynamicMethod dynamicEventHandler = new DynamicMethod(methodName,
            returnType,
            (Type[])parameterTypes.ToArray(typeof(Type)),
            typeof(TaskDynamicEventHandler));
    }
}

The drawback in this approach was that a dynamic assembly+module+type was getting created for each event. This was not efficient enough, and so slightly altered the logic to create the dynamic assembly+module+type once and add the methods [dynamic event handlers] to the dynamic type.

Though a level of efficieny may have been achieved, it was not elegant enough to be satisfied. The dynamic event handlers [DEH] are all methods of a specific type belonging to a different assembly that is generated at run-time, and these DEH do not belong to the same assembly as the TaskDynamicEventHandler class. The responsibility of the DEHs was to read its parameter name and values at runtime, package them into a hashtable and call a method HandleEvent of TaskDynamicEventHandler, and it is in HandleEvent that the actual job of logging is done. Well, the actual job is not only logging but other things that require access to the memebers of TaskDynamicEventHandler. So the non-elegance here was that HandleEvent was exposed as public static method so that the DEH in the dynamic assembly could call, which lead to the ugliness where HandleEvent was exposed to the outside world from the assembly to which TaskDynamicEventHandler belongs to. So HandleEvent cannot be non-public. But it was required for other reasons to be an instance method.

2. Here is the most interesting part. The aim was then make the DEH call an instance method of the TaskDynamicEventHandler ie HandleEvent. How do you make a static method call an instance method ? Well, if I have an object reference of the TaskDynamicEventHandler class in the DEH execution, and IF i can load that on to the evaluation stack [using the IL code/ILGenerator], then i call an instance method. That was the pain and it was pretty tricky and interesting that everybody to whomever I explained could not correctly grasp that the 'this' used during the compiled code will not be the same in the runtime IL code of the DEH, and neither can I load an object reference without me creating it or getting it as a parameter. That is all the .NET type security. You will not be given any chance to do reinterpret_cast kind of stuff at all. But you can pass the TaskDynamicEventHandler object reference [this] to the DEH but that beats the goal where the prototype of the DEH will not match the prototpye of its corresponding event and so cannot act as a sink.

3. Here comes .NET 2.0 for the rescue to a certain extent, and helps us acheive the aim – Efficiency and Elegance. There is a class by name DynamicMethod to dynamically create methods. The beauty of the DynamicMethod is that it is possible to add the dynamic method as member of the current class TaskDynamicEventHandler.


// returnType - event method's return type
// parameterTypes - event method's parameter types list
ArrayList parameterTypes = new ArrayList(parameterTypes);
parameterTypes.Insert(0, this.GetType());

DynamicMethod dynamicEventHandler = new DynamicMethod(methodName,
            returnType,
            (Type[])parameterTypes.ToArray(typeof(Type)),
            typeof(TaskDynamicEventHandler));

Hence the DEH is now a part of the same assembly and class and it can call even non-public methods. Efficiency was well achieved but still elegant was a few feet away. The dynamic method created and added to TaskDynamicEventHandler using DynamicMethod class is a static method and hence cannot access instance methods of TaskDynamicEventHandler, although it can access non-public methods.
3. Here is the most interesting part. The aim of this iteration is to make the DEH call an instance method of the TaskDynamicEventHandler ie HandleEvent. How do you make a static method call an instance method ? Well, if I have an object reference of the TaskDynamicEventHandler class during the DEH execution, and if i can load that on to the evaluation stack [using the IL code/ILGenerator], then i call an instance method. Things are going to get interesting now. The difference between an instance and static method is that an instance method has the object reference, to which it belongs, as the first parameter while a static method does not. Though syntactically, the object reference is not added, the compiler adds it. So while creating the dynamic method [DEH] for an event, the TaskDynamicEventHandler object reference [this] is added as the first parameter to the event parameter list. This makes the DEH seem to be an instance method. So during runtime, when an event is fired, its corresponding DEH executes, the Lgarg_0 in the IL code represents the object reference it belongs to, and it is the same as that for HandleEvent.

4. But even now the HandleEvent is public and is vulnerable for improper usage. I made it a virtual method. That is fun, and now it is entirely the user's responsibility to avoid improper usage, and it is upto the user to override HandleEvent to do whatever he wants.

5. Few minor things- Added Trace.WriteLine in the IL code using ILGenerator for debugging; Added try-catch exception blocks for catching exceptions, but unfortunately does not seem to work.

All of these approaches until the final efficient and elegant solution took several iterations of revisit and review. I will not able to explain about the difficulties and tough IL debugging experience that I went through trying to make the HandleEvent an instance virtual method, although I will be able to share the joy and knowledge now. It was a great experience !!!


Where is my C++ ?

May 4, 2006

I have been using C# for quite some time now, and that too VS 2005. I see that Programming Pain at a macro level has boiled down to thinking than coding. Though it might be an advantage on one side, I feel I have become lazy. Since I am a programmer from the C++ world, it was very easy to become lazy. The small and handy applications that I write for myself in C++, I am writing them in C#. Even now I am a great disciple of C++. And even though C++/CLI is out there, and I work a small amount of it in my project, I am getting inclined to C#.

I am not sure why I am writing this.
Is it the fear or sorrow of getting away from C++ ?
Or am I just expecting much elegant syntax and features like in C# ?

But I have begun to feel that the result you achieve out of the code you write is much more important than the programming language you use. Does anyone care whether Windows or Visual Studio or Yahoo Messenger or Google Talk or Internet Explorer or FireFox or any application you love, is written in C++ or C# or C++/CLI ? That is the way I consoled myself.

But I wish that C++ never go exile in my programming life.


Infinite .NET Languages !!!

April 26, 2006

Though I knew that there are quite a few languages for the .NET platform, I came to know when surfing today that there are many well beyond my knowledge, most surprisingly like the COBOL.

Check it out @ http://www.dotnetpowered.com/languages.aspx


Implementing COM OutOfProc Servers in C# .NET !!!

April 26, 2006

Step 1:
Implement IClassFactory in a class in .NET

Step 2:

[DllImport("ole32.dll")]
private static extern int CoRegisterClassObject(ref Guid rclsid,
   [MarshalAs(UnmanagedType.Interface)]IClassFactory pUnkn,
   int dwClsContext,
   int flags,
   out int lpdwRegister);

[DllImport("ole32.dll")]
private static extern int CoRevokeClassObject(int dwRegister);

Step 3:
Use these functions to register your own IClassFactory

Step 4:
IClassFactory has a CreateInstance method. Implement this method to return a reference (IntPtr) to your own object. Use Marshal.GetIUnknownForObject to get IUnknown pointer to your object.

Step 5:
The COM client receives a pointer to this object, and can use it as a regular COM object. .NET does the reference counting for you, and the GC will collect these objects when the COM-reference-count decremetns to zero.

Walking through and closely examining the working of ClassFactories for COM will give a clear sight of the objects that you need to implement in .NET, and a solution for COM Server in managed world.


Non-conventional Window Shapes [I love C#] !!!

April 15, 2006

I am not a UI guy. More specifically, I love to work with UIs. I think (only) a UI can give a better picture of the system in a multitasking environment unlike Unix. I do not say I hate Unix. And I do not like to work on UIs ie program on UIs cuz I do not know much. But have always wanted to create a non-conventional window, say an elliptical one. .NET made things like that very easy for guys like me. Look at the code below for creating a ellipitcal window.

GraphicsPath windowShape = new GraphicsPath();
windowShape.AddEllipse(0, 0, 320, 200);
this.Region = new Region(windowShape);

The GraphicsPath has methods to create wiondows of other shapes too.

I am not sure but I think it was not this straight forward in the MFC/Win32 programming world. Thanks to C#.NET. I love this 3 lines of code.


Serialization and Exceptions !!!

April 14, 2006

I am just in a stage like Alice in Wonderland, and not yet got out of the wonders of the .NET framework, C# and the VS 2003(5) IDE. I thought that the serialization is all not my thing until I do something big in C#. I had written this custom exception class in my project that has 3 processes connected by .NET Remoting Infrastructure. I throw my custom exception for a scenario but all I got was some other exception that said "The constructor to deserialize an object of type MyException was not found". But I had the Serializable attribute tagged to my custom expection class.

Let me to get to the point. Even though you attach the Serializable attribute to your custom exception class, the base class Exception implements the ISerializable interface and the constructor required during the deserialization [Exception()] is protected. So when you throw MyException, it may get serialized and cross the remoting boundaries but on the client side, it will not able to deserialize because the required ctor is not accessible. So what we do is simple as shown in the following code:-

[Serializable]
public class MyException : ApplicationException
{
    // Member Data
    // Other necessary ctors 

///
    /// Let us call this ctor as Deserializing Ctor [DSCTOR]
    /// 

public MyException(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
        // Any other custom data to be transferred
        // info.AddValue(CustomDataName, DataValue);
    }

/// If any custom information needs to be transferred
    /// with the MyException thown, it must be added to the
    /// SerializationInfo object on the call to
    /// GetObjectData() and to take them from this object in
    /// the constructor for deserialization.
    public override void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        base.GetObjectData(info, context);
        // Any other custom data to be transferred
        // info.AddValue(CustomDataName, DataValue);
    }

// Other methods
}

This DSCTOR is very much necessary, else the exception thrown will not be caught as the one thrown and you will get this excepetion "The constructor to deserialize an object of type MyException was not found".

If any custom data needs to be transferred with the MyException thown, it must be added to the SerializationInfo object on the call to GetObjectData() and to take them from this object in this secondary [deserialization] constructor.


Know where you initialize and Do not forget to uninitialize !!!

April 10, 2006

If you have long been programming in C++/COM and then you move to C#.NET, the first difference you can feel is that you got a ctor for the object you create unlike the CoCreateInstance. In the C++/COM world, you generally would have a Initialize method to do the constrcution sort of, paired with Terminate/Uninitialize method. Similar is the case with singleton classes. For singleton classes in C++, you will have public static Instance or GetInstance method to get the only and one instance of the class and then use the initialize method to do the construction. This is certainly advantageous than the ctor facility in .NET, since you will not know when the instance will be initialized without the initialze method. Any call like SingletonClass.GetInstance().SomeMethod may initialize the singleton anywhere and you will not exactly do the initialization during the application startup, which in many cases will lead to application errors after startup.

I do not recommend putting the initialization logic in the ctor, particularly for singletons. The Initialize/Uninitialize method seem to be primitive and kind of from the legacy age but we want code elegance rather than fashion. The pair gives a reasonable intuition and a feel of responsibility to initialize and uninitiailze. Without this simple pair, the object [singleton or any .NET object] gets initialized without control. Also the developers as soon as they enter the .NET world, with the advice from somebody next door, instantly or deliberately forget the memory management and leave everything to GC. But GC can perform the uninitialization required by the business logic.

The Initialize/Uninitialize pair just silently enforces to follow the pattern to initialize at the right place, and most important uninitialize, not giving the risk of remembering about Dispose.

I was forced to write this comment because I was forced to write that code.


An encounter with Hashtables !!!

April 10, 2006

I encountered a situation like this where I had a hashtable in which the key is a string and the value is some object, and I had to change the values of all the keys [from zero to count] to null or some other value. I used the some of the facilities – enumerator, the Keys property etc provided by the hash table itself but it did not work out, and I spent too much time on this.

The interesting thing is that for the following code, the compiler spits an error saying "'System.Collections.IDictionaryEnumerator.Value' cannot be assigned to — it is read only":-

IDictionaryEnumerator de = ht.GetEnumerator();
while (de.MoveNext())
{
   de.Value = null;
}

while for this code

foreach (string key in ht.Keys)
{
  ht[key] = null;
}

it compiled successfully but threw a runtime exception [An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll Additional information: Collection was modified; enumeration operation may not execute].

But the solution was just bit out of sight while it was in hand. Just forget that you encountered this problem, and start again, you will have the solution simple like this:-

ArrayList keys = new ArrayList(ht.Keys);
foreach (string key in keys)
{
   ht[key] = null;
}

And another thing I came to know was that the hash table entries are not maintained in the same order as they are inserted. I came to know that it is the inherent nature of the algorithm. That is basic but it was new to me.


A Note On Finalize !!!

April 10, 2006

This is not about what Finalize is, but well Finalize is the last call on a managed object, where you can perform some clean up operations, before getting garbage collected by the .NET runtime. A few important things that are to be noted about finalizers are:-

– In C#, finalizers are represented by the ~ClassName [destructor syntax], and the Object.finalize can neither be overridden or called directly. It cannot be called directly because it is protected. The destructors in C# also take care of calling the dtor of the base class.
– Finalizer is called on an object only once, just before the .NET runtime attempts to garbage collect the object.
– Finalizers can be called anytime on a managed object that is not being referenced, and on any thread by the .NET runtime.
– The order in which the finalizers are called is also not fixed. Even when two objects are related to each other in some way, there is no hierarchial order in which the finalizers for the objects will be called.
– During an application shutdown, finalizers will be called even on objects that are still accessible.

The most interesting part of the finalizer is not when it is called but when all is it NOT called. This is where we need to watch and rely on the Dipose method [IDispoable – Dispose pattern].

– When a finalizer of a object blocks indefinitely [deadlock, infinite loop etc].
– When the process terminates improperly without giving the .NET runtime a chance run the finalizers.
– When a managed object is exempt from finalization by calls like GC.SupressFinalize or KeepAlive.


Explicit Interface Implementation !!!

April 10, 2006

I have encountered this [wait i'll explain] sort of situation many times and I mostly do this way in C++.

Assume you have a class CMyClass that exposes its functionality through its public methods, and also let it listen to events from some sources, events being OnSomeEvent or OnXXXX(), by implementing some event interface IXModuleEvents. Now these event listener methods are reserved only for internal use and are not meant to be called by the users. So when I implement the IXModuleEvents interface in CMyClass, I make them private. Think about it and the problem is solved. It is the polymorphism game, that never cares for the accessibility of the method.

But I was in the same situation and my head had stopped working and my hands went coding the same way, and found that it does not work. In C#, i have the facility to declare a interface and by default its methods are public, strictly no need of any access specifiers. And the class that implements has to implement it publicly. So my OnXXX() methods get exposed.

But yes, there is a solution for the situtation, it is called Explicit Interface Implementation. It is this way:-

internal interface IXModuleEvents
{

void OnSomeEvent(int i, int j);
void OnSomeOtherEvent(string name);

}

public class CMyClass : IXModuleEvents
{

// ….. Other implementation // No need of any access specifiers
void IXModuleEvents.OnSomeEvent(int i, int j)
{
}

// No need of any access specifiers
void IXModuleEvents.OnSomeOtherEvent(string name)
{
}

}

So you can access these OnXXXX() method implementation only if you have a IXModuleEvents reference of the CMyClass, and try out with a CMyClass reference to access the event listener method implementation.


The Interface Based Programming Argument !!!

April 10, 2006

I am always a great fan of interface programming. I mean not exactly the interface keyowrd but some way to expose the functionality of the class or your module relieving the user about the worries of the implementation. But definitely make him curious of the stuff inside.

The Win32 APIs are not that good in what I am talking about. Well, there are several reasons for that. And I strongly object that they are raw APIs and not for the ordinary application programmer. That kind of an abstraction is there at every level. Even a programmer using the Win32 APIs does not know what goes inside though some of the APIs expose unknowningly the sort of internals. This is an argument, but what I mean to say is that anything that you wish your users to use must have a elegant interface just exposing the functionality, and in the most intuitive way that makes sense. It may be an interface in C# or an abstract class in C++. And once you do that, you will slowly be under the tree where you can clearly realise the roots of an object oriented system.

I have to argue/fight like that recently to make things bit more object oriented in my project where I had to refactor-redesign the existing mess.


Properties in C++/CLI….The C# look alike !!!

April 10, 2006

Inherently after writing some code in C#, I wanted everything to be as easy to do like in C#. And could not resist myself writing property like syntax in C++ [ofcourse C++/CLI, threw away the ugly Managed C++ before it was too late for my code to grow into a tree]. Then I learnt that properties are supported in C++.NET too but as always in the ugly way. But in C++/CLI, I was happy enough that the syntax is more elegantly redefined. For instance, there was this boolean member logToStdError in my class, and in my legacy code, the property definition for logToStdError looked like:-


__property bool get_LogToStdError()
{
    return logToStdError;
}
__property void set_LogToStdError(bool value)
{
    logToStdError = value;
}

Doesn't that seem like the cat scorching its skin wanting to look like a tiger ? But we need to understand that the Managed C++ is just an extension provided by Microsoft for C++, and is not standard unlike C++/CLI. And then in C++/CLI, the syntax for property was reformed with the property keyword:-


property bool LogToStdError
{
    bool get()
    {
        return logToStdError;
    }

void set(bool value)

    {
        logToStdError = value;
    }
}

This makes life bit luxurious, and the compiler takes care of still generating the get_LogToStdError and set_LogToStdError version of the methods. Try defining a method with that name and see what happens.

But the purpose of this entry is not just put another note on C++/CLI Property instead there are 2 cute features that i liked:-

1. If the property that we define is a very simple one, just getting and setting the value of the related member variable, then we can simply declare a statement like this in our class [for the LogToStdError], and the compiler takes care of the under-the-cover activities.

property bool logToStdError;

2. This one I love very much because I wanted this behaviour in a lot of places in my code, and before. It is possible to specify different accessibility levels for the get and the set property accessors. For example,


property bool LogToStdError
{
public:
    bool get()
    {
        return logToStdError;
    }

protected internal:
    void set(bool value)
    {
        logToStdError = value;
    }
}

The get accessor can be accessed anywhere outside the class in the assembly, but the set accessor can be accessed only inside the current assembly or within the types derived from the type in which LogToStdError is declared. I guess that this facility is not available in C#.


Managed Debugging Assistant !!!

April 10, 2006

The Loader Lock is a synchronization object that hepls to provide mutual exclusion during DLL loading and unloading. It helps to prevent DLLs being re-entered before they are completely initialized [in the DLLMain].

When the some dll load code is executed, the loader lock is set and after the complete intialization it is unset. But there is a possibility of deadlock when threads do not properly synchronize on the loader lock. This mostly happens when threads try to call other other Win32 APIs [LoadLibrary, GetProcAddress, FreeLibrary etc] that also require the loader lock. Often this is evident in the mixed managed/unmanaged code, whereby it is not intentional but the CLR may have to call those APIs like during a call using platform invoke on one of the above listed Win32 API.

For instance, if an unmanaged DLL’s DllMain entry point tries to CoCreate a managed object that has been exposed to COM, then it is an attempt to execute managed code inside the loader lock.

MDA – Managed Debugging Assistant, facility available in .NET 2.0/VS 2005 helps to find out this situation while debugging and pops up a dialog box. Then we can break into the code, have a look at the stack trace and resolve it. The feature can be disabled if not needed.

So what could be the effect of this deadlock ? It saved me whole of time and effort that I would have wasted when such a box poped up in my project, and I do not know if I would have found the reason. If the thread that deadlocks happens to be the GC thread or any thread that loads and unloads my assemblies, I do not have explain further the disasterous effect. And for a programmer like me, new to the .NET environment, who has not yet gotten out of the fascinating external features, will not ponder into the internals.


Do not delete [] a scalar pointer !!!

March 27, 2006

Recently I got tangled into this problem in my code – Calling a vector dtor for a scalar pointer. We all know that it is perfectly illegal to do that. For example, if we allocate something like this:-

OurClass *p = new OurClass();

and try to delete like this:-
delete []p;

then we are going to end up in trouble. Ofcourse we know that we will end up in trouble. But I have really not given a thought HOW ?

When we allocate an array of items eg. OurClass pa[] = new[5] pa(), the compiler actually allocates the necessary amount of memory, calls the ctors for each allocated class and also prefixes the block of memory of the ‘n’ items allocated with the number of items allocated.

NumItems | OurClassObject1 | OurClassObject2 | …… | OurClassObjectn

But pa always points to the first item in the allocation, thereby the item count prefix remains hidden. When we call delete[] pa, the compiler uses the item count prefix to delete the allocated objects and call the dtors.

Now i think i don’t need explain any further as what happens when i use delete []p, and what junk value will the compiler take from the memory location just before the memory location p believing it to be the item count.

I learnt this interesting information from OldNewThing Blog. Adam Nathan has explained it well with the compiler generated assembly and a bit of excellent code for the dtor.

And what if we do a scalar delete on a vector pointer, there is less harm, you do not unallocate the memory completely, you leave behind remnants of your allocated memory which you cannot reclaim.

Either way, it is better to be disciplined while programming.


Where do you QueryInterface ???

March 26, 2006

For an ATL class, the QueryInterface is implemented in CComObject. The figure below is the inheritance hierarchy for a class generated by the wizard representing an ATL-COM object.

CComObjectRootBase has an InternalQueryInterface method, which uses the interface map built by the BEGIN_COM_MAP macro to resolve IID -> interface pointer. The BEGIN_COM_MAP macro also defines a method _InternalQueryInterface, which passes the map on to InternalQueryInterface. CComObject implements QueryInterface, and calls _InternalQueryInterface.

NOTE:
CComObjectRootEx: Provides methods to handle object reference count management for both nonaggregated and aggregated objects.

CComObject: Implements IUnknown for a nonaggregated object. It is a template class that takes a class like CSomeClass derived from CComObjectRootEx.

CComObjectNoLock: Implements IUnknown for a nonaggregated object, but does not increment the module lock count in the constructor. ATL uses CComObjectNoLock internally for class factories.

CComCoClass: Defines the object’s default class factory and aggregation model.


Use Of Class Factories !!!

March 26, 2006

To understand quickly and to explain in the simplest way, Class Factories are the factory classes that create a COM object. A class factory may be responsible for creating one or more COM objects. In the case of COM OutOfProc servers, the server registers the class factories for objects that it can create in a system-global table using CoRegisterClassObject. Whenever a client does CoGetClassObject for a CLSID, the COM run-time can look it up in the system global table, and return the factory instance. The case with InProc servers is also similar but through the DLLGetClassObject.

The point here is that class factories are required [irrespective of how they exist physically in the servers, either as seperate instances or the COM object itself behaving as a factory for the objects of that type], they abstract the creation of the COM object through IClassfactory::CreateInstance.


Unsafe Operations with STL !!!

March 26, 2006

It is UNSAFE to do any operation on an STL container that will modify its size while holding a reference to one of its exisiting element. What could happen is, when you do an operation, say push_back on a vector, it determines if there is enough space available to add a new element. If there is not sufficient space available, it allocates new space for whole of the data structure and deletes the old buffer. At this point, any reference to one of its elements created prior to push_back would have gotten corrupted.

For example, the following usage of code is dangerous when used within a single scope.

SomeClass &sc = m_Vector.back();
m_Vector.push_back(someotherobject);
.
.
.
sc.SomeMethodCall(); // Code might crash here.


Consoles for Mr.GUI !!!

March 26, 2006

Learnt something new, a small one but very useful.
Many times I have seen GUI applications accompanied by console windows that show logs or trace information of the application. How do we do that for our application ?

Any GUI application can create its own console window just by calling AllocConsole Win32 API. Actually any process can use that API to allocate a new console. And the application must also learn to be disciplined enough to FreeConsole. Ok, fine. I used that in my small MFC application and was happy to see the console. But I did not see anything displayed on the console. As we know, each process has its own stdin, stdout and stderr. So redirect the console output of your parent application to the console. How do you do that ?

Use the FILE *freopen(const char *path, const char *mode, FILE *stream); API. The freopen function closes the file currently associated with stream and reassigns stream to the file specified by path. By that way, call freopen as follows:-

FILE *fpStdOut = freopen (“CONOUT$”, “w”, stdout);

This means that I want to reassign the standard console output stdout with the console output of the parent application CONONUT$. So any printf calls will print the characters on the console. Cool !!!


Setting Environment Variables !!!

March 26, 2006

Need to change or set the value of an environment variable programmatically and without the need to restart/log off the machine. I need the change to reflect for all processes, ie, I need to change the global environment value and not the one in the PEB [Process Environment Block] of a process. Frustated with setting the value of an environment variable !!!

For getting the set of environment variables or to get the value of an environment vaible from your C# program, there is the GetEnvironmentVariables/GetEnvironmentVariable API in the System.Environment class. But there is no API for setting the value of an environment variable.

The system environment variables are stored in the registry under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment.

The [current] user environment variables are stored in the registry under HKEY_CURRENT_USERE\Environment.

When the system boots up, the environment is built from this list in the registry. If we change the value directly in the registry, the change does not effect. For example, change the value of TEMP variable that specifies the temporary files directory, in the registry and check with the set command in the command prompt, you won’t see the change you made. Or just create a new entry in the registry under the one of the above mentioned registry paths, you won’t see the change. Also you can verify that programmatically with GetEnvironmentVariable API.

But the changes you made will be reflected after a log off or restart. After some research, I found the Win32 SDK API SetEnvironmentVariable. But unfortunately, it just the changes the variable value in the PEB of that process alone, it does not effect the global environment values. Pathetic.

There is definitely a solution for this simple and primary problem. All we have to do is to update the registry as we discussed before, and also notify that the global enviroment variable list has been modified. Ok, how do we do that ?

Simple, one line of code.

// Broadcast the WM_SETTINGCHANGE message for Enviroment

SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
(LPARAM) “Environment”,
SMTO_ABORTIFHUNG,
5000, &dwReturnValue);

Of course, this is C++ code. Not a big deal to do that in C# or whatever.


CoMarshal…. working in NT, Not working in XP !!!

March 25, 2006

Problem:-

I have created a multi-threaded application which works without any problems on a NT-4.0 Workstation/Server. When I try to run the same application in Windows XP, I get an error in a call to CoMarshalInterThreadInterfaceInStream which returns -2147418113.
I have provided a snippet of the code below where the call fails in Windows XP.
Environment – Windows-XP,SP-2,Visual Studio 6.0,SP-4,ATL-3.0
Should I be doing anything different in Windows XP?

HRESULT hr = S_OK;
IUnknown** pp = p->m_vec.begin();
while (pp m_vec.end() && hr == S_OK)
{
if (*pp != NULL)
{
IEvent* pEvent = (IEvent*)*pp;
IStream* pIStream;
HRESULT hr = CoMarshalInterThreadInterfaceInStream(IID_IEvent, pEvent, &pIStream);
if(SUCCEEDED(hr))
{
CComPtr pMarshalEvent;
hr = CoGetInterfaceAndReleaseStream(pIStream, IID_IEvent, (void**)&pMarshalEvent);

if(SUCCEEDED(hr))
hr = pMarshalEvent->NewCurrentCassette(m_pCurrentCassette, m_setBy);
}
P++;
}

Thread 2:-

I remember facing this problem long time back.The reason it happened was b’cos of the Free-Threaded marshaller code in Finalconstruct and FinalRelease even though i don’t remember the logic behind it.In my case commenting the Free-Threaded marshaller code did the trick.

1) The commented code in FinalConstruct was
hr = CoCreateFreeThreadedMarshaler( GetControllingUnknown(), &m_pUnkMarshaler.p);
PROCESS_HR(IID_ISomeThing);

2)In FinalRelease it was the corresponding m_pUnkMarshaler.Release(); that was commented.

3)In the header,DECLARE_GET_CONTROLLING_UNKNOWN() and COM_INTERFACE_ENTRY_AGGREGATE(IID_IMarshal, m_pUnkMarshaler.p) and CComPtr m_pUnkMarshaler; was commented.

4)Remove marshalling code i.e,CoInterface and related marshalling code.The interface pointer can be accessed in the secondary thread directly,no need of marshalling.

I remember faintly that Free-Threaded marshaller is basically to optimize marshalling.So in my case removing it did not have any side-effects as we were not worried about Free-Threaded marshaller.Again the above fix might work but the best thing to do will be to anaylze the apartment link(STA,MTA etc.) between say the client and the component and then come to a conclusion.

Thread 3:-

You need not marshal/unmarshal to call a method on the interface pointer since the sink class itself deriving from the IConnectionPointImpl takes care of unmarshalling. You can see the code in your connection point implementation class.

Thread 4:-

I don’t think IConnectionPointImpl class as such has anything to do with marshalling, it is the m_pUnkMarshaler member object.It is the call to CoCreateFreeThreadedMarshaler in FinalConstruct that initializes the m_pUnkMarshaler object.I suggest reading the documentation about CoCreateFreeThreadedMarshaler in order to come to a conclusion whether to use it or not.By default ATL provides the code calling CoCreateFreeThreadedMarshaler API to do efficient marshalling across *thread of the same process(Refer doc)*, but depending on our need we may or may not use it.In my case we did not need it so we commented it out.It depends on the need,but generally i think it is safe to comment it out if we are going to access interface pointers in secondary threads.Hope this helps.


Consts in .NET !!!

March 25, 2006

I was doing some programming with C# and I had to use some ‘const’s as everybody does generally in programming. I had a class that simply had const string variables for my DB table names and stuff like that. My program was not working well and I started debugging and in the debugger, I was shocked to see that the const variables did not show the string values I had assigned. I did rebuilt and other non-sensical stuff like that until I learnt this about the consts in .NET:- ‘const’ variables in .NET do not exist as variables out of the assembly they exist in. Instead, during compilation, they get embedded [hard-coded] where ever you use them, and so when you debug, you do not see the proper value that you had assigned. For debugging purposes you have to output diagnostic trace messages and verify.


Joining the Game

April 19, 2005

Everything has a beginning.