Tuesday, December 7, 2010

Ways of Throwing an Exception in C#

Exception handling is very common for everyone. Exceptions are runtime errors which might be caused by some operation illegal to the application. .NET provides a good Exception Model (even though Microsoft wants to change this model) using try/catch which lets us to deal with runtime exceptions from our code.

It is stated that, you write your code that might generate an exception inside try block, write the logic which handles the exception generated within the catch block ( like logging, notifying etc.), where catch block can overload. Also you should keep in mind, it is recommended to wrap your code in try / catch only if you think you can handle the exception, if you cannot, it is better to leave apart the exception and let the caller to handle this in their own code. Lets take an example :


public void FirstCall()
{
    try
    {

        this.SecondCall();
        Console.WriteLine("After Exception");
    }
    catch (Exception ex)
    {
        this.DumpException(ex);
    }
}

So in the above code the Try/catch block is introduced to implement the code with exception handling.  I am using DumpException which writes the exception to the Console.

Download Sample Code - 30 KB


Sunday, December 5, 2010

Win32 Handle (HWND) & WPF Objects - A Note

Well, there is a common confusion for many who are working with WPF objects, is does it truly interoperable with Windows environment, or more precisely, does it act the same way as it does with normal Win32 objects?
The problem here comes with the fact that each WPF window has only one window handle (HWND) and each other controls are actually placed as content to the window and does not have any entry on Kernel table(no HWND) except of course Popup class in WPF. In this post I will try to cover the basis of HWND (for those of you who don't know) and later go on with what are the changes of it with WPF environment.

If you know what HWND is or how it works, please skip the next section.

Overview of Win32 HANDLE

Win32 Handle is very important for any Win32 applications. For every Win32 apps, Kernel maintains a Table which has entries to identify a memory address. A HANDLE is actually a DWORD (32 bit integer) which maps the memory address on the table. So if you get a HANDLE, you can easily locate the memory address it points to.  Each object that you have in Windows (like windows, buttons, mouse pointers, icon, menu, bitmap etc) has entries in the table and the object is traced using both internally by windows or by programs using those HANDLEs. Even though it is just an unsigned integer value, you should not edit the value, otherwise the HANDLE could not be used to point the object anymore.


Monday, November 29, 2010

Summary of Microsoft Community Tech Days - 28th November Kolkata

Yesterday(28th November 2010), we had our Session for Community Tech Days Kolkata, In association with Kolkata .NET community we have put our effort to produce few great Sessions from few great people. In this post, lets cherish those magical moments we had together (or if you missed).  Here is the Agenda :


Saturday, November 20, 2010

Debugging with Async

C# async feature really exposes a lots of things to us. I can see, there is lots of people is discussing about it in MSDN forums, few people wanted to get rid of the Task from the async methods and really want to deal with normal return types, while others just wanted to get rid of the async postfix. During my leisure, I read them but what I thought the most important part of the feedback is that most of the people really liked the way Microsoft simplifies the Asynchronous approach of programming style. 

I have already studied some of the important facts on Async style of programming, and found that it uses the StateMachine to let the program return after a certain portion of the method gets executed while the Rest of the program is sent as ContinueWith for the Task. Thus the TaskCompletion automatically restarts the method and continue. If you want to know more about how Task gets executed in async methods, please read my article where I have discussed how exactly the current trend of programming style got changed.

Today while I was looking at the implementation of Async style of programming, I just discovered an Internal class named DebugInfo inside the System.Runtime.CompilerServices.AsyncMethodBuilder.


You can see the class is internal, and hence not exposed from the perspective of BCL. You cannot create object of the class or even look at the private member LocationForDebuggerDisplay. But the only thing that you can see through this is the ActiveMethods.

Sunday, November 14, 2010

Microsoft Community Tech Days - 28th November

Microsoft is going to arrange a Community Technical Day for us on 28th November 2010 here in Kolkata. The whole thing is organized by Kolkata Dotnet Community. I am very glad to announce that I am going to present Ribbon UI control for the seminar.



I will mainly present Windows Presentation Foundation in light of a new Ribbon UI Controlset introduced recently and may be added to the main line library in next version of WPF. Be there, if you wish.

To Register :

Register Yourself

Who else is speaking?

Abu Sayed Mohammad Ismail, Sankarsan Bose, Rajiv Popat, Abhijit Jana

See you there.

C# 5.0 vNext - Asynchrony in Synchronous flow style code

There is a buzz all around on the new way of doing asynchronous programming using async database modifier and await contextual keyword. Threading or Asynchronous style of programming is very useful at times but each of us faced a lots of problems though converting a Synchronous code to Asynchronous coding style. Asynchronous style of coding is not new to the framework. From the very beginning of the evolution of C# as a language we can do programs that may run in parallel. But was it simple enough? No ! Its not. The way of writing our very own asynchronous programs can be very complex at times when we are about to deal with exception handling. We could have lots of callbacks around for every single asynchronous calls, there might be few thread blocks around for network calls etc.

C# 5.0 takes this into consideration and orchestrate the style of coding to more like synchronous manner.


I have already introduced, the two new keywords async and await which was introduced with async CTP recently, but it was just a rough introduction to the fact (as I posted that on the same day). Now let me move a bit further in this world and go with more complete asynchronous style of coding.

I have put a lovely article for you in codeproject with few sample codes. Please try the link below to read the whole story around async and await :

C# 5.0 vNext - New Asynchronous Pattern

You can also download sample Code from

Sample-CodeAsync - 385KB

I hope you would like this article. Please give your comments and feedbacks.

Thank you.

Saturday, November 6, 2010

Reflection - Slow or Fast? Demonstration with Solutions

Many of you might have heard, calling reflection APIs from your code is always slower than that of calling it directly.  Well, it is right. Some of the major Reflection methods like GetXXX (of MethodInfo, PropertyInfo, FieldInfo etc) are say 100 times slower than that of calling a Method, Property or Fields directly. In this post, I will try to cover some of the major portion of Reflection which is slower like hell than that of normal method call and also try to solve the same.


So what is Reflection for?

As I have already told you about Reflection and Code Emit and also how to build your Lamda Expression Tree, it is good to know where you would like to use Reflection. Yes... Reflection is made truly late bound approach to browse through the object hierarchy or to call methods inside the object. So if you do not know much about your object hierarchy or you have somehow found an assembly external to your application and you need to parse through the object and call its methods say, then Reflection would be the right choice for you.

So basically Reflection allows you to create plugin type of applications where you define an Interface and publish the same for your application and let others create those plugins for you to seamlessly added to your application. Fine. Then what it isn't for?

Yes basically few people try to work everything based on Reflection. Using reflection unnecessarily will let your application very costly. Say for instance,

ConstructorInfo cinfo= typeof(MyType).GetConstructor(new Type[] { typeof(int), typeof(string) });
object createdObject = cinfo.Invoke(new object[] { 10, "Abhishek" });
MyType xyz = createdObject as MyType;

Or say using
MyType typ = Activator.CreateInstance<MyType>();

Silly huh..
I saw few people to do this. They try to use everything using Reflection, may be they love the Reflection too much, or they have already created a Reflection engine right and do not want to mix up unknown types with known ones. May be they would make their code clear by calling the known types to the same module that is built up for dealing with unknown types.

Download Sample - 60 KB

Author's new book

Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!