Skip to main content

Posts

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

.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 gener...

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

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 CoR...

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

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 initializa...

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 oper...

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

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

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

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 r...

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 Deb...

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 o...

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 fac...

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 *fpStdO...

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 di...