Pranay Rana: 2014

Wednesday, February 12, 2014

Help Yourself in Debugging (Part-3) StackTrace and Caller Information attribute

Read below post related to same topics
  1. Help yourself in Debugging by using Call Stack and Immediate Window  
  2. Help Yourself in Debugging (Part-2) using Breakpoint/Tracepoint
This post is about two feature in C# Caller Information Attribute and StackTrac class , which are helpful to get information at runtime from where the call came i.e. both provide information about caller. As purpose of both is same but there is significant difference between both of them. Information provided by both can be used by developer application to provide trace information.

Before start with StackTrace and Caller information following image shows structure of the code.



So the project is divided in three layer UI, Business and DataLayer.

Front Layer code 

class Program
    {
        //Program p = new Program();

        public int i = 10;
        public static void Main(string[] args)
        {
            try
            {
                var str = (new BusinessEmployee()).GetEmployeeList();
                Console.WriteLine(str);
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                global::System.Windows.Forms.MessageBox.Show(ex.Message);
            }

        }
    }
As you see in above code Font layer calling “GetEmployeeList” method to get list of all employee.

BusinessLayer code 
 
    public class BusinessEmployee
    {
        private readonly DataEmployee dataEmployee;

        public BusinessEmployee()
        {
            dataEmployee = new DataEmployee();
        }

        public  void GetEmployeeList()
        {
            dataEmployee.GetEmployeeList();
        }
    }
In this layer Business class calling DataLayer to get employee list from the database.

DataLayer code

    public class DataEmployee
    {
        //Data layer class for employee 
        public  void GetEmployeeList()
        {
            //code goes here for retiving from DATABASE
        }
    }
This layer return employee list, but for the example its returning exception.

 

StackTrace

Class in C# part of System.Diagnostics name space which provide information same as Call Stack window (Read more about Call stack window ) at runtime.

To understand it better way lets consider change in above code in DataLayer
        //Data layer class for employee 
        public string GetEmployeeList()
        {
            //// get call stack
            StackTrace stackTrace = new StackTrace(true);

            StringBuilder sb = new StringBuilder();

            foreach (StackFrame frame in stackTrace.GetFrames())
            {

                sb.AppendLine(" Method Name: " + frame.GetMethod().Name + " File Name:" + frame.GetMethod().Module.Name + " Line No: " +                   
                                   frame.GetFileLineNumber());
            }

            return sb.ToString();
        }

As you can see in code it create StackTrace class and when creating new object of class "true" is passed as argument to the constructor of StackTrace class for capturing the file name, line number, and column number.
After the object get created GetFrames method is usd to get information about each frame(each method call is represented by one frame) and finally each frame details is appeded using StringBuilder, then it displayed by front end.

Following is output get recieved once the code run


So output prints each call made from one layer to antoher if you see above code call is coming from the fron layer to database layer.

Advatage 
  • StackTrace provide detail informaiton about from where call came from the beggining till end. This is one resason devloper can use StackTrace when there is need to get i.e. trace details level information. 
  • Also StackTrace frame also provide control on the caller method, provide assebmbly from where call is coming. 
Disadvantage
  • Inline method  is not get listed when code compiled in Relase mode, which is get listed when code compiled in Debug mode.
         To understand it cosider below code changes in front layer code.



 Now if you compile code in Debug mode with below configuration
  

  
It will generate below output for you , where you can see four line i.e. on extra line of calling to method "GetEmployeeList1".



So debug list all method calls But Now if you compile code in Release mode with below configuration




It will generate below output for you , where you can see three line.  The line of calling method "GetEmployeeList1" is missing.


So StackTrace doesn't list out methods which is converted to inline method by compiler. if you want to list out you can mark method as [MethodImpl(MethodImplOptions.NoInlining)]



if devloper mark method as [MethodImpl(MethodImplOptions.AggressiveInlining)] than the method also no get list in debug
So StackTrace information can be spoof by making method inline.
  • As StackTrace provide every minute detail, StackTrace will show the full trace right into the core MS sourced assemblies, and will reveal details about what technologies you're using, and possible versions as well. This gives intruders valuable info on possible weaknesses that could be exploited. So always careful before displaying this information and put security on this.
Advantage over Caller Information attribute
  • It provides minute details which is not possible with Caller Inormation attribute.
  • Line number, Filename and Method Name information is given by StackFrame which cannot be changed by devloper But in case of Caller Information attribute devloper can spoof by passing wrong value in caller information parameter.

 

Caller Information attribute

This is new feature introduce in C# 5.0. and attributes are part of System.Runtime.CompilerServices namespace. These attributes required to be added as optional parameter in the method for which need to get caller information.
 Example
Accessiblity ReturnType MethodName (Type parameterName,....,         
                                    [CallerMemberName] string memberName = "",
                                    [CallerFilePath] string sourceFilePath = "",
                                    [CallerLineNumber] int sourceLineNumber = 0

Name Type Description
CallerMemberName string Provide caller method Name
CallerFilePath string Provide caller method File Name
CallerLineNumber int Provide caller Line number in File from where method get called


Note :
Caller of the method can aslo pass this value as this attribute added as parmeter to method.

Example when calling method which is decorated by caller information attribute


To understand this let do change in the DataLayer method like this
        
         //Data layer class for employee 
        public string GetEmployeeList([CallerMemberName] string memberName = "",
                                     [CallerFilePath] string fileName = "",
                                    [CallerLineNumber] int lineNumber = 0)
        {

            return " Method Name: " + memberName + " File Name:" + fileName + " Line No: " + lineNumber;
        }
 So running above code provide below output


Advantage
  • Information of caller attribute cannot be spoofed till devloper pass informaton in method parameter.
  • There is no rutime cost for this i.e. it doesnt affect performance of the code as attribute are compile time.
  • Very hepfull to find out when call is coming from some unknonw location like in case of "PropertyChange". 
Disadvatage
  • Information of caller can be spoofed by devloper if devloper pass wrong information in the parameter of the caller information.
  • There is only one StacFrame i.e. it will give information about who called method(immediate caller of method) but doesnt provide detail information like StackTrace. 
  • It's part of C# 5.0 so its not working with older version of framework. 
Advantage over StackTrace
  • As its complied time there is no rutime cost like StackTrace ( we need to create object of StackTrace runtime to get information).
  • Information provided by attribute cann not be Spoofed by method attributes.
Do Comment if the information is missing or wrong.

Referenced from 

Monday, January 27, 2014

Getting Exact Location of Exception in C# Code

Post is about locating exact location of the Exception in the code. There is always problem for the developer to locate exact location from where Exception raised, because of that it difficult for the developer what actually went wrong. Most of the time problem occurs when there is too many libraries referenced i.e. used in project.

To understand let’s consider below example:
In following example application is divided in three layers
  1. Font end - Layer though which user interact with application and Displays data to end user of application.
  2. Business -Layer which is having business logic, code to call datalayer and the info classes which transport between font and data layer.
  3. Data - Layer which interact with database and supply data to business layer.
Front Layer code 

class Program
    {
        //Program p = new Program();

        public int i = 10;
        public static void Main(string[] args)
        {
            try
            {
                (new BusinessEmployee()).GetEmployeeList();
            }
            catch (Exception ex)
            {
                global::System.Windows.Forms.MessageBox.Show(ex.Message);
            }

        }
    }
As you see in above code Font layer calling “GetEmployeeList” method to get list of all employee.

BusinessLayer code 
 
    public class BusinessEmployee
    {
        private readonly DataEmployee dataEmployee;

        public BusinessEmployee()
        {
            dataEmployee = new DataEmployee();
        }

        //Business layer class for employee 
        public  void GetEmployeeList()
        {
            dataEmployee.GetEmployeeList();
        }
    }
In this layer Business class calling DataLayer to get employee list from the database.

DataLayer code

    public class DataEmployee
    {
        //Data layer class for employee 
        public  void GetEmployeeList()
        {
            throw new Exception("Not able to fetch employee");
        }
    }
This layer return employee list, but for the example its returning exception.

Now if you run above code by putting it into respected layer, then when exception thrown by the actual code debugger break execution in the front layer code. Below image shows same thing.



So it becomes difficult for the developer what went wrong if there is actual complex code is there.

Solution
 In Visual studio there is option as given in below image that allows to break debugging at the point i.e. at the code from where exception is coming.



Once you clicked on menu option it will open up dialog box where you can mark tick on “Common Language Runtime Exception” as in below image and click ok.



Now if you run same code than debugger will stop at exact location from where exception is coming, you can also see below image.


So breaking at exact location from where error is coming you can find out which part is actually causing problem and help to resolve error easily.


Conclusion
Visual studio option to locate exception also very helpful when there is multiple threads doing operation and throws exception. Also locate exceptions dialog provide other option that is also help full when you are using JavaScript, com component etc. that you can try by yourself.

Saturday, January 18, 2014

Dependency Injection Part - 1

In this Article I am going to discuss about "Dependency injection" on which I am working and exploring. In this article I am going to discuss about what is dependency injection and why there is need of this software design pattern.

Dependency injection

To understand dependency injection better way, let’s consider below code,

Public class client
{
     Public static void main()
     {
        NeedDependencyClass a = new NeedDependencyClass();
     }
}

public class NeedDependencyClass
{
  Private readonly DependencyClass _b;
  public NeedDependencyClass ()
  {
     _b = new DependencyClass();
  }
  public void Test()
  {
     _b.Test();
  }
}

public class DependencyClass
{
  public void Test()
  {
    // code for text method
  }
}
In above code class client creates NeedDependencyClass and use it, then class NeedDependencyClass consume service of class DependencyClass to perform task i.e. class NeedDependencyClass is depend on class DependencyClass to perform task. This kind of the code is hardcoded dependency.
Image above shows the representation of creation and use of the objects.


Problem with code is
  1. Class NeedDependencyClass itself responsible for creating its own dependency.
  2. Code is tightly coupled, because dependency cannot be replaceable.
  3. Code also violate “Open Closed” rule of SOLID principal which says that "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification". Because do changes in the Test method I need to modify DependencyClass.
  4. Testing of Class NeedDependencyClass becomes difficult as I cannot replace Dependency class DependencyClass with other dependency.
Dependency injection is software development pattern which introduced to resolve above problems.

Definition of this pattern is: Remove hard coded dependency and make it possible to replace at run-time or compile time.

In following section I am going to describe how problem listed above get resolved with the Dependency injection pattern.

Solution

1)Make client i.e. first class in dependency graph which consume service to create all dependent object
Resolution to the first problem of code above, pass the responsibility of supplying all required dependency to the first in dependency graph i.e. client class which is first class of the dependency graph.

So the code will change like this

Public class client
{
     Public static void main()
     {
        NeedDependencyClass a = new NeedDependencyClass(new DependencyClass());
      }
}

public class NeedDependencyClass
{
  Private readonly DependencyClass _b;
  public NeedDependencyClass(DependencyClass b)
  {
     _b = b;
  }
  public void Test()
  {
     _b.Test();
  }
}

public class DependencyClass
{
  public void Test()
  {
    // code for text method
  }
}
Image below shows object creation only done by client class object and others class down the line use supplied defendant object.



2)Removes tight coupling between object i.e allow to define loose coupling
To understand the second problem better way, let’s consider with the real life scenario of Computer or laptop.
 

 

As you can see in the above image we have the port for each device external device to which I can associate external device and do our work.

But problem with this is I cannot attach my keybord on printer port and vice versa, same problem occurs with the other devices. So this is like tight coupling that I cannot change my external device on the give interface i.e. on which I am depends.

Solution to this is USB port.

If I have USB port than I can easily attach any device to my machine and perform my task.



What is tight coupling between classes? (In programming)

Let start with simple example:

public class NeedDependencyClass
{
  Private readonly DependencyClass _b;
  public NeedDependencyClass(DependencyClass b)
  {
     _b = b;
  }
  public void Test()
  {
     _b.Test();
  }
}

public class DependencyClass
{
  public void Test()
  {
    // code for text method
  }
}

Now as you see in above code class NeedDependencyClass utilized class DependencyClass, this means that class NeedDependencyClass is depend on class DependencyClass. This type of dependency is tight dependency between class NeedDependencyClass and class DependencyClass. Because class DependencyClass is passed as parameter to class NeedDependencyClass and class NeedDependencyClass utilizing method of class DependencyClass. Now if the why it called as tightly coupled. If code is like this to create

NeedDependencyClass a = new NeedDependencyClass(new DependencyClass()); 

now if I created class DependencyClass1 like as follows public

class DependencyClass1 { 
      public void Test() 
      { //code for text method } 
}

and I want to pass DependencyClass1 instead of DependencyClass in class and want to call test method

NeedDependencyClass a = new NeedDependencyClass(new DependencyClass1()); 

This will give compiler error because I am trying to pass DependencyClass1 object as parameter. So this means Class NeedDependencyClass cannot accept any another class than Class DependencyClass.

Solution to this problem is define and interface as below which get implemented by classes

Interface IDependencyClass
{
   Void Test();
}

Class DependencyClass : IDependencyClass
{
 ……
}
Class DependencyClass1 : IDependencyClass
{
 ……
}

So the code become like this

public class NeedDependencyClass
{
  Private readonly IDependencyClass _b;
  public NeedDependencyClass(IDependencyClass b)
  {
     _b = b;
  }
  public void Test()
  {
     _b.Test();
  }
}

And this code will work both the class DependencyClass and DependencyClass1

Image below shows DependencyClass object creation only done by client class object and others class down the line use supplied dependent object. And class NeedDependencyClass is depends on the interface IDependencyClass, which can be implemented and replicable by any new class DependencyClass.

3) Make your class depend on Abstraction
Now there is requirement like only authenticated user of the application can run Test method in the application, than developer of the class need to modify the Test method like this.

public class DependencyClass : IDependencyClass
{
  public void Test()
  {
    using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, 
        "YOURDOMAIN"))
 {
      bool isValid = pc.ValidateCredentials("myuser", 
       "mypassword");
               if(isValid)
         Console.Writeln(“Testing method for the data”);
               
 } 
  }
}

That’s violate SOLID principle “Open Close” which says "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification".

So to avoid it same as make use of the abstraction i.e. create interface as which already done for to resolve tight coupling, so class extension can be done easily.

Below is how to extend the code that doesn’t break “Open Close” principle.

Class DependencyClass : IDependencyClass
{
 public void Test()
  {
    Console.Writeln(“Testing method for the data”);
  }
}

Class SecureDependencyClass : IDependencyClass
{
  IDependencyClass _b; 
  public SecureDependencyClass(IDependencyClass b)
  {
    _b = b;
  }
  public void Test()
  {
    using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, 
        "YOURDOMAIN"))
 {
      bool isValid = pc.ValidateCredentials("myuser", 
       "mypassword");
               if(isValid)
         this._b.Test();   
               
 } 
  }
}

As you see in above code new class is created with the name SecureDependencyClass. This class extends the functionality of the previous class and also not breaks “Open Close” principle.

This is done by injecting exiting class DependencyClass in the new class SecureDependencyClass i.e that is also example of Dependency injection. So SecureDependencyClass consume dependency DependencyClass.

And which change consumer client code like as below

Public class client
{
     Public static void main()
     {
        IDependencyClass dependency = new SecureDependencyClass(new 
       DependencyClass());
        NeedDependencyClass a = new NeedDependencyClass(dependency);
      }
}

public class NeedDependencyClass
{
  Private readonly IDependencyClass _b;
  public NeedDependencyClass(IDependencyClass b)
  {
     _b = b;
  }
  public void Test()
  {
     _b.Test();
  }
}

Image below shows SecureDependencyClass object creation only done by client class object and others class down the line use supplied dependent object. And class NeedDependencyClass is depends on the interface IDependencyClass, which can be implemented and replicable by any new class SecureDependencyClass.


This also shows the NeedDependencyClass is not dependent on specific class but on the Abstraction.

4) Make class Testable
Now once the second step class NeedDependencyClass easily becomes testable. Because problem with original code is hardcode dependency that is not replaceable.

Example , following is the final code

public class NeedDependencyClass
{
  Private readonly IB _b;
  public NeedDependencyClass(IB b)
  {
     _b = b;
  }
  public int Test()
  {
     var c=_b.Test();
     return c*10;
  }
}

public class DependencyClass :IDependencyClass
{
  public void Test()
  {
    // code for getting value form database
    using(SqlConnection c = new SqlConnection(connectionstring))
    {
     c.open(); 
        SqlDataReader myReader = null;
SqlCommand    myCommand = new SqlCommand("select count(*) from table", c);
        return (Int32) cmd.ExecuteScalar();
  }
}

As per the code Test method of the class DependencyClass does connection with sql server and return value.

But for testing of the class NeedDependencyClass there is no need to perform expensive database connection. So we replace class DependencyClass with the TestDependencyClass class like as below.

public class NeedDependencyClass
{
  Private readonly IDependencyClass _b;
  public NeedDependencyClass(IDependencyClass b)
  {
     _b = b;
  }
  public int Test()
  {
     var c=_b.Test();
     return c*10;
  }
}

public class TestDependencyClass :IDependencyClass
{
  public void Test()
  {
     return 10;
  }
}

Public class TestClient
{
     Public static void main()
     {
NeedDependencyClass a = new NeedDependencyClass(new TestDependencyClass());
      }
}

Conclusion

So Dependency injection is one of important design pattern which allows developing maintainable code which also satisfies SOLID principals. DI not only helpful in above this problem but we can also achieve below, Other thing can be achievable by DI is
  1. Parallel programming of application
  2. Late Binding