Infinite .NET Languages !!!

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 !!!

Had to implement our COM OOP Server project in .NET, and I found this solution from the internet after a great deal of search, but unfortunately the whole idea was ruled out, and we wrapped it as a .NET assembly. This is worth knowing.

Step 1:

Implement IClassFactory in a class in .NET. Use the following definition for IClassFactory.

namespace COM
{
   static class Guids
   {
      public const string IClassFactory = "00000001-0000-0000-C000-000000000046";
      public const string IUnknown = "00000000-0000-0000-C000-000000000046";
   }
   
   /// 
   /// IClassFactory declaration
   /// 
   [ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid(COM.Guids.IClassFactory)]
   internal interface IClassFactory
   {
      [PreserveSig]
      int CreateInstance(IntPtr pUnkOuter, ref Guid riid, out IntPtr ppvObject);
      [PreserveSig]
      int LockServer(bool fLock);
   }
}

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#] !!!

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 !!!

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 !!!

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 !!!

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 !!!

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 !!!

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 !!!

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 !!!

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 ava
ilable in C#.

Managed Debugging Assistant !!!

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.