Learning Type Access Modifiers Basics !!!

When I started developing my module, I had an interface IParamCountBasedAlgo declared as a nested type in a class AlgorithmOneExecutor, declared as follows:-

namespace DataStructuresAndAlgo
{
partial class AlgorithmOneExecutor
{
private interface IParamCountBasedAlgo
{
void Validate();
void Execute();
}
}
}

There were other concrete nested types inside AlgorithmOneExecutor that implemented IParamCountBasedAlgo. But later, other types nested in other than AlgorithmOneExecutor emerged that required to implement IParamCountBasedAlgo. So I moved IParamCountBasedAlgo from a nested type to a direct type under the namespace DataStructuresAndAlgo, as declared below:-

namespace DataStructuresAndAlgo
{
private interface IParamCountBasedAlgo
{
void Validate();
void Execute();
}
}
And the compiler spat an error "Namespace elements cannot be explicitly declared as private, protected, or protected internal". Then a simple research gave me an insight that types directly under namespace can be declared either public or internal only, and the default is internal. Seems reasonable cuz if declared private, it gives an ambiguous look that it cannot accessed or created and protected seems rather very unrelated. Hence either public or internal only.

A subtle point to note is that not all access modifiers are applicable for all types and at all declaration levels. To learn the basics of type access modifiers, visit http://msdn2.microsoft.com/en-us/library/ms173121.aspx

where enum does not work !!!

I was writing a generic method with enum as the Constraint, and the compiler spat a few errors that did not directly convey me that enums cannot used as generic constraints. And I learnt the following from my investigation:-

This is an excerpt from the C# Language Specification. Enums are value types and there is no way that you can specify the System.ValueType as a constraint, as per the specification. But if you wish to specify a non-reference type as a [primary] constraint, struct can be used.

private void Method where T : struct

That does not guarantee that our generic method will not accept other value types, besides enum, for which we do not support our functionality.

During the course of investigation, I was extremely surprised to know that the numeric types like int, float etc in C# are struct. It is not far from the fact that they are value types, but it was interesting to know that they are declared as


public struct Int32 : IComparable, IFormattable, IConvertible, IComparable, IEquatable

Similar thing for other numeric types. Whereas an enum [System.Enum], though a value type, is declared as an abstract class that derives from System.ValueTypes unlike the int or float. The end result is that enums are value types but i wonder the way they are declared.

Anyway, the question still remains unresolved - why enums cannot be used as constraints, andjust the specification saying that enums cannot be used as constraints is unsatisfactory.

I am not sure if there is any other way to resolve my situation.
Question open to cyber space !!!

P.S.
Refer section 25.7 through for the specification on Generic Type Constraints.

First Google Gadget(s) !!!

I did some cool stuff here with google. I wrote my first "Hello World" sort of google gadget. It claims no rewards but just was fun. Since I am a novice in html and javascript sort of things, this gadget is pretty simple.

Use the following URLs

http://vivekragunathan.googlepages.com/Pirate.XML
http://VivekRagunathan.GooglePages.com/Clock.XML


to enjoy the gadgets.

Overloading......A Matter Of Taste !!!

This was a pretty interesting discussion about method overloading in the managed world. As the discussion says that the overloading is a matter of taste. It seems that the method overloading in the managed world, indeed, is a matter of taste. Sad BUT True !!! But on the contrary, it must have been a [strict] rule. Overloading might be exhibited differently by each language in the unmanaged world. But as far as .NET goes, it must have been made a standard specification. Pardon me, if there is one.

As it was pointed out in the discussion, how do we define the behaviour in the case where we derive classes across assemblies developed in another .NET language ?

As far traditional C++ goes, the overloaded method resolution starts from the derived but does not have strict type checking eg. for numeric types]. And the point to note is that only the method in the derived class with the exact prototype as the base is considered the overload. Ofcourse, C++ is not as much type safe as C#. This is taken care in C# by the override keyword which allows only the exact prototypes to be involved in overloading. And at times explicit casting is required unlike in C++.

But in the case of C#, the first principle observed in overloading is to avoid it. Pretty confusing, huh? Take a look at the example below:-


namespace Samples.MyConsole
{
class Parent
{
public void Foo()
{
Console.WriteLine("Parent.Foo");
}
}

class Child : Parent
{
public void Bar()
{
Console.WriteLine("Child.Bar");
}
}

class Base
{
public virtual void XYZ(Child c)
{
c.Foo();
c.Bar();
}
}

class Derived : Base
{
public virtual void XYZ(Parent p)
{
p.Foo();
}

public override void XYZ(Child c)
{
base.XYZ(c);
}
}

class User
{
public static void SomeMethod()
{
Child c = new Child();
Parent p = c as Parent;

Derived d = new Derived();
Base b = d as Base;

Console.WriteLine("Playing with Derived");
d.XYZ(c);
d.XYZ(p);

Console.WriteLine("\nPlaying with Base");
b.XYZ(c);
b.XYZ(p as Child);
}
}
}

Here is the output at the console:-

Playing with Derived
Parent.Foo
Parent.Foo

Playing with Base
Parent.Foo
Child.Bar
Parent.Foo
Child.Bar

You would have guessed the surprise that you are about to experience. Yes, d.XYZ(c) calls the Derived.XYZ(Parent p), and not the Derived.XYZ(Child c) which is a better match. It does if it had been defined as public new void XYZ(Child c). But same is not the case with C++. It gives us no suprise.

And as far as C++/CLI is concerned, it behaves as traditional C++.

So the intriguing bitter part is that the overloading in the managed world is not a thing at the CLR level nor does it seem to be something concerned with the specification. It seems to be a matter of taste.

Follow the trail.......Join the Concurrency Revolution !!!

I could not stop writing this post after I read this article by Herb Sutter. The article is just a casual technical discussion but very encouraging that a person requires at the right time - the time when he is a student. Even after several years after my college, I have been trying to keep myself a student and I got a right encouragement to join the Concurrency revolution. Thanks to Herb Sutter.
As Albert Einstein, Robert Goddard, and Wernher von Braun walked the trail of Galileo and Newton , I will to walk the trail of some of the contemporary people like Sutter, Stroustoup, Don Box, Richter and others.

The New Looking Post !!!

I am very much fond of tools, updates and stuff. So I keep updating my softwares and hear/learn about new tools etc. I am excited about the new spaces - Live Spaces. Looks much better than before. I thought I would write something about the new spaces. Please 'spaces guys', make the arranging the boxes on the home page a bit easier and intelligent. That is a feature request. Otherwise the default skin/theme is cool and professional. Old themes are still old and not much appealing. Anyway, i write the post just to say i love it.

And talking about tools and softwares, i heard this news about Microsoft acquiring the SysInternals tools. And probably, Microsoft might be shipping the tools like Debug View, Process Explorer, RegMon etc with the Windows SDK. Me not sure of that, better read what Tom Archer said.

Fooled by the Activator !!!

It was interesting to know that a custom exception, say an exception class derived from System.ApplicationException, thrown while creating an instance of a type using Activator.CreateInstance does not get caught in its appropriate exception handler, instead gets caught in the global exception handler "catch(Exception ex)", if provided. Any exception raised while creating an instance of the loaded type is wrapped inside a new exception object as InnerException by Activator.CreateInstance.

I was fooled that there was some problem with the image generation for quite some time, and then very lately inspected the members of the exception caught and found my exception object wrapped as InnerException.

Now my global exception catch handler catch(Exception ex) has the logic to check if there is any inner exception in ex and inspect if it is of my custom exception type. I am not sure but why cannot the custom exception be thrown as such by the Activator.CreateInstance without wrapping it inside a new Exception object. Would not that be good besides saving a few lines of code ?

Properties C# 2.0 - Not Elegant Enough !!!

Prior to .NET 2.0, there wasn't the facility in C# to opt the visibility level for the get and set property or indexers. And i take my comment in my previous post that C# does not provide the facility of having different visibility levels for the get and set accessors. While that is partly correct, it is no more in C# 2.0.

And obviously it isn't in the easy and elegant way. Take a look at this code snippet:-

public bool LogToStdError
{
get
{
return _log2StdError;
}
protected set
{
_log2StdError = value;
}
}
I do not have to explain the code except there are some restrictions while having different visibility levels for the get/set accessors of a property.

1. You can provide an explicit visibility either for get or set. Hence the following code will throw an error:-

public bool LogToStdError
{
protected get
{
return _log2StdError;
}
protected set
{
_log2StdError = value;
}
}

2. The visibility thus explicitly specified must be a subset [restrictive than] of the property declaration.
For example, if the property declaration is protected, then the get/set accessor cannot be like say public. So the following code throws an error:-


protected bool LogToStdError
{
get
{
return _log2StdError;
}
public set
{
_log2StdError = value;
}
}

I feel that these restrictions are stupid, and this resulted because of the syntax. I just thought of some ideas for a bit elegant syntax for the property definition.

1. The get and set accessors individually have to specify the visibility level.

bool LogToStdError
{
public get
{
return _log2StdError;
}
property set
{
_log2StdError = value;
}
}

2. The property declaration syntax must not bear any visibility level unless the associated get/set accessors do not bear any. For example, in the property definition below, the get/set accessors are public:-

public bool LogToStdError
{
get
{
return _log2StdError;
}
set
{
_log2StdError = value;
}
}

and as per this property definition, the get/set accessors are protected:-

protected bool LogToStdError
{
get
{
return _log2StdError;
}
set
{
_log2StdError = value;
}
}

3. If there are visibility levels specified neither in the property definition nor in the accessors, then the default visibility level as specified for C# [I guess internal] will be applied for the property accessors. Hence the get/set accessors are internal for the following property:-

bool LogToStdError
{
get
{
return _log2StdError;
}
set
{
_log2StdError = value;
}
}

Singularity - Safety & Speed !!!

I read about this interesting thing somewhere in MSDN.

There are two types of programming or programming languages. The good old C/C++ kind called the unsafe programming languages, and the other is the safe programming type which we realised very much after advent of Java/C#. And there has always been debate about safety and speed. And neither of the two has won.

So Microsoft is doing a research on a new operating system called Singularity which is written in a safe programming language [C#]. Although there are parts in the OS, especially the kernel, that uses unsafe code, it stills uses the safe C#. So in the Singularity environment, every program that runs is safe. And the environment as such is reinventing from the hardware layers up and above.

Any process in singularity will not be as huge as its counterpart in the unsafe world. It will start with very minimal image and bring up things as when required. But also there was some thing that i read but could not understand exactly. It said that Singularity processes are closed - dynamic loading of code is not allowed after the process starts executing.

Whatever, the environment is .NET as whole which means that .NET is not just libraries on the disk instead it is into the kernel. Microsoft is doing the research to prove that there is no compromise between speed and safety with this safe programming environment, and also help programmers stopping worrying about the choice of speed or safety.

out, ref and InvokeMember !!!

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

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");
}
}

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++ ?

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

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.

Do not delete [] a scalar pointer !!!

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

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

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

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

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

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

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

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.