Monday, February 27, 2012

DotNet Watcher - To find out eaten exceptions at runtime

One of my current .Net projects, which started from the VB 6.0 days has lot many areas where exceptions are eaten using empty catch blocks. As the project is in Agile methodology where people give more importance to delivery than quality, we cannot blame developers for writing this type of code. On a build day, if the app shows an exception dialog, the best way they are finding is the empty try-catch block and handle the consequences as bugs.

When we went to MSFT for reviewing the app, this caused so many troubles and they introduced us to their internal tool which captures the eaten exceptions. That was really helpful for debugging the application in the production environment. There are so many tools available public to track the same but this tool is so simple and easy to use. I was really excited and wanted to blog about the same. But not sure whether there were any permission or other license-related issues as the tool is Microsoft internal.

Days were happy when we were on .Net 3.5. But when we migrated our project to .Net 4.0, the MSFT tool stopped its support. It was targeted to the .Net 2.0 base run time and we were forced to recompile against .Net 4.0. The process of reflecting on the tool and google started in parallel and the reflecting wins and we got the tool in 4.0. But the interesting thing I got during the google is a link to Mike Stall's .Net blog which explains the basics of that tool.Yes.I can blog about the tool as the details are already available to the public.

How the tool works

The tools work based on MDbgCore.dll1 engine provided by Microsoft. It can either start an application in the attached mode or attach itself to a running process. Then it hooks to the debug points and other operations that are happening on the target application. Once a hooked operation happens it passes the control to our debugger host application where we can print or log the details.

Coding a Debugging host 

From the programming aspect, things are more clear. You need to refer the MDbgCore.dll to your application. Then create an instance of MDbgEngine to start or attach to a process that will give you MDbgProcess instance. The processInstance.Go.WaitOne() will wait for the notification from the target application. Once a notification comes, it will be an instance of the BuiltInStopReason derived class.Handle that accordingly.
            MDbgEngine debugEngine = new MDbgEngine();

            if (int.TryParse(args[0], out processId))
            {
                proc = debugEngine.Attach(processId);
            }
            else
            {
                proc = debugEngine.CreateProcess(args[0], ""DebugModeFlag.Debug, null);
            }
            while (proc.IsAlive)
            {
                // Let the debuggee run and wait until it hits a debug event.
                ManualResetEvent handle = proc.Go() as ManualResetEvent;
                handle.WaitOne();
                object o = proc.StopReason;
                // Process is now stopped. proc.StopReason tells us why we stopped.
                // The process is also safe for inspection.            
                ExceptionThrownStopReason m = o as ExceptionThrownStopReason;
                if (m != null)
                {
                    ProcessException(m, proc, callback);
                    continue;
                }
            }

Note: Important thing here is you need to run this in a separate thread or use async delegate to avoid the application waiting endlessly.  This was not in the sample provided by Mike Stall :-).

Modifications I did

Mike Stall's blog explains the basics such as how to attach to the target application and print the exception. I took it a little further to have a UI around. Also planning to add more scenarios such as capturing when the classes are being loaded along with capturing eaten exceptions.

Intended audience

Mainly the developers who are coding in .Net for years but don't know how the .Net application works internally. Then the developers who are in the same state as mine where they had to deal with so many eaten exceptions. Finally, developers who are interested in writing their own debugging tools. I know there are so many apps available that do the same. But seems a little difficult to make suitable for our purpose.

Source code

As I am planning to add more features I am not attaching it with this blog post. You need to go codeplex for the sample ie the application named DotNet Watcher  GitHub for the application source code. This is my first published project in CodePlex.

1 Locate the dll at :\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\MdbgCore.dll

Tuesday, February 21, 2012

Indian campus way of problem solving

Couple of weeks back, I had to go an engineering college campus nearby, related to recruitment in to our company.  It is a self financed private college running very well with good discipline and all. But I could see the art works of students in the desks like a government college:-). According to me the desks or tables are the initial area where students can show their drawing skills.

As usual I could see students from all the branches coming to attend the interview for Software Development job.There were 5 rounds to be passed to get the job.First the aptitude test,next round is a group discussion. Third a technical / programming test followed by a technical interview.Finally a management interview ie HR interview (Human Resource).

My part mainly started with the technical test and ended with the technical interview. When I corrected the papers, I could see that the theory questions are very well answered such as "What is the difference between while and do while loops ?","Characteristics of OOPS ?" etc.. But when the programming question is answered, I could see a struggle for students especially the non-computer science or students who are not interested in programming. Most of the students in non-computer science stream didn't attend the programming questions.Even if somebody attempted they just wrote the initial 2 lines of a C program which they might have seen in their 3rd semester.


#include <stdio.h>
void main()
{
}

The characteristics of computer science and non computer science students is not our interest .I am just about to say the problem solving attitude of 2 candidates who attended that interview process.The answers took my attentions are

Qn : What is the result of below code ? If its a compilation issue how to correct?

double number=546.4;
int newNumber=number;

Ans : Compilation error .New code
double number=546.4
double newNumber=number

Simple isn't it? No casting .No conversion etc...

Qn : Display the below using for loop ?
$1$$2$$$3$$$$4$$$$$5
Ans:
for (int i=0;i<1;i++)
 Console.WriteLine ("$1$$2$$$3$$$$4$$$$$5");

There were so many answers which accepts an input number and displays dollars using loop.Even we expected the same answer.But if we closely look at the question there is nothing specified about getting an input number and display the string in the given pattern. Smart answer .Isn't it? Not many people can think in this way. This was from a mechanical student but unfortunately we were not able to get him due to next rounds :( 

Saturday, February 18, 2012

Reinventing the wheel

Below are some funny scenarios, I came across in my developer life. These type of incidents mainly happen when the managers see their developers learning new things which are not part of the project or an entirely new technology. Sometime this happen when there is nothing to deliver to the clients for billing.

Manager : You know something, our build guys are really struggling to change the configuration (web.config) when they create installers for different environments. You need to seriously think about a tool which can accept input word or pattern through its UI and replaces with another word in single or multiple files.
Developer (After thinking a little) : I know one tool which works great for single file in case of replace.Run the tool and just press Ctrl+H.

Manager : Oh really.We mainly need to replace text in our web.config..What is that tool? Is it free?
Developer : People often call it as Notepad!!!

Manager : If any error happens in application we are logging it.In case of machine failures system is too writing the logs. But end users have no option to view the logs. We need to write a tool to show the system event log and log files of SQL server.
Developer : I think if the user is too brilliant to understand the error logs generated by system and sql server he knows how to get the logs.Excuse me, I mean how to open the eventvwr.msc to view the system event log and notepad to view the sql log files located at
[InstallDrive]:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log

Tuesday, February 14, 2012

Handling WCF FaultContract & FaultException in Silverlight

What is FaultContract in WCF and how to handle fault exception in a windows application has been posted 1 year ago in this same blog itself. Some time back we one of colleague was trying to implement the same in his Silverlight application and he was not able to leverage my post to accomplish his task as Silverlight uses async pattern to call the service and the binding is basicHttp. The basicHttpBinding uses the SOAP protocol and it returns the fault using the HTTP 500 series status code which cannot be understood by Silverlight. So we modify the WCF response using custom EndPointBehavior and a MessageInspector to return using HTTP 200 code.

All those details are specified in the MSDN itself. What I am doing here is to post a sample in Silverlight 4.0 :-)
http://msdn.microsoft.com/en-us/library/ee844556(v=vs.95).aspx

No its not just a sample. It describes how to write client side code which is not mentioned in the MSDN article.Mainly where to put try catch to catch the fault exception. For the server side code and configurations just look at the MSDN article. Client side code you can get from below section.


   1:  private void GetChar(String ipString, int position)
   2:  {
   3:          MyServiceReference.MyServiceClient client = new MyServiceReference.MyServiceClient();
   4:          client.GetCharCompleted += (sender, e) =>
   5:          {
   6:              try
   7:              {
   8:                  if (e.Error != null) throw e.Error;
   9:                  MessageBox.Show("Extracted character: " + e.Result.ToString());
  10:              }
  11:              catch (FaultException<MyServiceReference.MyException> ex)
  12:              {
  13:                  MessageBox.Show("FaultException occurred " + ex.Detail.ExMessage);
  14:              }
  15:              catch (FaultException ex)
  16:              {
  17:                  MessageBox.Show(ex.Message);
  18:              }
  19:          };
  20:          client.GetCharAsync(ipString, position);
  21:  }

The main difference is the position of try catch blocks .In the sync service calls it will be wrapping the service call itself.Here we have 2 ways as the exception comes through the e.Error property.Either we can check the type in the handler itself or throw to handle by the callers.

Saturday, February 11, 2012

Format code and paste to blog

Life was running smoothly when I used windows live writer for writing posts which need to have code snippets in it. It has a very good plug-in for pasting almost all types of code snippets.

On a fine day I became conscious about security of my google account and enabled mobile validation for login. The issues started from then. The live writer don't know how to handle the accounts which has mobile verification activated.Thus the live writer started failing to publish posts to blogger.ie Not able to publish posts from live writer to blogger after enabling mobile verification in google accounts.

There are various ways to overcome this. Or I can still use live writer for writing posts and before publishing I can take the html code and just paste in blogger site. But that will not give the flexibility of storing the drafts in the online system. There are chances that the local system may crash at any time which may lose all our works. So better option is to find out alternative to format the code snippet to paste into posts and keep the drafts in blogger itself.

There are mainly 2 options to do this


There are chances the links may broke, if you upload the code and share the link because the provider may stop the service at any time.Also the code belongs to them.

These are the sites which I am using. If you want to explore more sites like this use the similar site search providers.