Thursday 28 April 2016

[Solved] How to trace all calling function in C#?

If you want to reverse trace the all called method name and other information about the flow of execution of your code then
its for you. By using StackTrace Tracing Utility you can get list of all function executed in calling a method.

Example Code to tracing this:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Trace_All_Calling_Function_Name
{
    class Program
    {
        static void CallingFunction()
        {
            StackTrace stackTrace = new StackTrace();
            StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)
            // write call stack method names
            int functionIndex = 0;
            foreach (StackFrame stackFrame in stackFrames)
            {
                functionIndex = (functionIndex+1);
                Console.WriteLine("Function : " + functionIndex);
                Console.WriteLine("Method Name : " + stackFrame.GetMethod().Name);
                Console.WriteLine("FileName : " + stackFrame.GetFileName());
                Console.WriteLine("FileLineNumber : " + stackFrame.GetFileLineNumber());
                Console.WriteLine("FileColumnNumber : " + stackFrame.GetFileColumnNumber());
                Console.WriteLine("DeclaringType.Name : " + stackFrame.GetMethod().DeclaringType.Name);
                Console.WriteLine("DeclaringType.Module.Name : " + stackFrame.GetMethod().DeclaringType.Module.Name);
                Console.WriteLine("");
              
            }

        }

        static void Method_1()
        {
            Method_2();
        }

        static void Method_2()
        {
            CallingFunction();
        }

        static void Main(string[] args)
        {
            Method_1();
            Console.ReadLine();
        }

    }
}