Friday, October 17, 2014

Help Yourself in Debugging (Part-2) using Breakpoint/Tracepoint

Read Part 1 : Help yourself in Debugging by using Call Stack and Immediate Window
In this post I am going to discuss about the “BreakPoint” which is one of the most used feature by developer to debugging application by breaking execution of program runtime at certain point. I am going to describe the feature provided in visual studio for breakpoint and how it’s useful for debugging code easily. 

What is Breakpoint? 
Breakpoint is feature provided in Microsoft Visual Studio which allows breaking execution of code at runtime when debugging application. 

For Example:
 
When you click on side of the code in visual studio it setup break point in you code as displayed in above image. So when you start execution code it will break execution at this point. 


BreakPoint Menu (Option for the Break)

 

Above image display the context-menu for breakpoint i.e breakpoint menu. Following describe the all the option one by one. 
  1. Delete Breakpoint
  2. This option of the breakpoint menu allows removing breakpoint.
  3. Disable Breakpoint
  4. This option of the breakpoint menu allows disabling breakpoint, so the breakpoint just get disable and become gray. Useful when developer just want to execute code without stopping at breakpoint and later on enable when want to use it back.
  5. Location…
  6. This menu option allows setting break point at given location i.e. at given line in source code file.



    When click on the menu it display dialog that provide information about source code file, line number in code and character. This dialog allows changing line and character information.

    For Example:


    Change line number to 26 in the in dialog than it breakpoint change to line number 26.



  7. Condition…
  8. When this option clicked it below dialog get displayed which has two options. 
    • (A).   IS true
    • This option allows setting condition for breakpoint, so according to this execution during debugging get stopped at breakpoint i.e. breakpoint get hit when condition satisfied.
      Fox Example:



      As in above image condition set is “i==1000” that means this breakpoint get hit when this condition is true i.e. satisfied.

      This is very helpful when you want to stop execution of the application when certain condition met specially as in example loop having many number of element and want to stop at given location.

      Once condition set breakpoint displayed as below.



      Breakpoint changed to read icon having + sign in it. When mouse get over on breakpoint visual studio display information related to breakpoint with condition in tooltip.
    • (B).   Has changed
    • This option allows breaking execution of code at breakpoint when there is change in the variable or object.
      For Example:



      Over here variable “i” is entered in the dialog i.e. if the value of variable “i” get changed than execution of program get stopped at breakpoint.

      Below image shows the tooltip on breack point once condition set.



      When this option utilize than in breakpoint context menu condition option get check as in below image.

  9. Hit Count…
  10. This option display count number of time breakpoint hit when executing program.



    This dialog box has three options which allow to set hit count and if the hit count matches than program execution get stop at breakpoint. Each option is self-explanatory you can see in following image.



  11. Filter…
  12. This option allow to set condition related to “Machinename and Process” according to which breakpoint get hit. Following image explain more detail about it.



  13. When Hit…
  14. This option allows setting the message than get print to output window when program executions pass the breakpoint.

    This option converts breakpoint to Tracepoint i.e. so the developer can do tracing of the import variable or things by printing message on the output window when code at trace point get executed.
    For Example:



    As in above image to read value of the variable developer created message that get printed on output window each time code in for loop get executed.

    You can read the text in dialog which also provides information about how to provide information in the textbox so that it gets print to output window.

    Once developer press ok by setting the tracing message breakpoint get display like square as in below window.



    So when this program gets executed in visual studio, messages get printed to output window as shown in below image.



  15. Edit Labels…
  16. This option allows setting label for your breakpoint. So it display dialog like this.



    This is helpful when developer exporting breakpoint from visual studio, help to remember how important breakpoint it via label, create of useful breakpoint by using same name etc.
  17. Export…
  18. This option allows exporting breakpoint set by developer.



    This exported breakpoint information get saved as “XML” as show in above image. Exported XML file for breakpoint look as below



    This option is helpful when developer want to export breakpoint and save it as XML than remove it. When there is need to same breakpoint he/she can load same breakpoint by loading XML file using Debug window of Visual studio.
BreakPoint window
Breakpoint/tracepoint set by developer in code is get displayed by this window. This window also displays breakpoint with other information. 

Following is way which shows how one can start breakpoint window. 

 

So one can either use debug menu and start breakpoint window or make use of short cut Ctrl+D,B. 

Following is image of breakpoint window. 

 

This window also has toolbar which allows following, which is also supported by breakpoint menu discussed above. 
  1. Set new breakpoint
  2. Remove breakpoint
  3. Delete all breakpoint
  4. This option allows to delete all breakpoint which is selected in breakpoint grid.
  5. Enable/Disable breakpoint
  6. Export breakpoint
  7. Import breakpoint
  8. This option is not part of the breakpoint menu; it is used for importing breakpoint/tracepoint.



    When this button clicked by developer, visual studio open file browser window to browse xml file for breakpoint / tracepoint.



    So after loading this file breakpoint/tracepoint get set again in the code.



  9. Go to Source Code
  10. Go to Diassembly
  11. Columns
  12. This tool menu allows to set number of column in the below grid i.e. in breakpoint window grid which is below toolbar.



  13. Search
  14. Search allows searching breakpoint in the breakpoint grid of breakpoint window. Following is image of the same. As per the criteria specified breakpoint grid window display searched breakpoints.



Breakpoint Grid

This grid window displays all the breakpoint set by developer in source code. This grid provides information about each breakpoint according to columns set by developer in grid. 



Conclusion

Breakpoints/tracepoints are very useful feature provided in visual studio, which is very usefl when you are debugging large amount of code. Visual studio provides flexibility to break execution of the code during debugging at breakpoint which is very helpful to the developer. 

Help yourself in Debugging by using Call Stack and Immediate Window

In this post I am going to show you the two important window of the Visual Studio which is useful when you debugging the project and to get the result on the fly during debug.

Call Stack Window
Most of the developer get confuse when they are debugging application "From which function call came from up to my debug point", this happens when they are working the code design by some one else or debugging code of the dll.

Following is one common scenario which I notice number of time developer does.
In the three tier application developers always put the break point in presentation layer when the break point get hit they always check the data and the do wonder that which business layer method called >> database layer method get called by presentation layer to get this data. 

The Solution is Call Stack Window which is part of the Visual Studio. Shortcut for it is 
Ctrl + Alt + C or go to menu Debug >> Windows >> Call Stack









As you can see the image with the help of the Call Stack Window you will get information about the method get called, what is parameter value, line no of the method in file, is it external call or internal, programming language in which method written.

Immediate Window
It always happen that in middle of debugging you want to execute some set of statement or some set of function or want to check the value of the variable. But as beginner you don't know how to do it at time of debug ?

You can open up the Immediate window by shortcut Ctrl + Alt + I or go to menu Debug >> Windows >> Immediate Window






Immediate window has intelligence support as we have in the Coding window of the Visual Studio so that you can easily make use of the function, which makes you task easy.

Saturday, October 11, 2014

Action Result In MVC

By default, the Controller actions will return the ActionResult object.We can return various types of results as ActionResult, which will decide how the output needs to render on the browser.
Below table shows the various ActionResult.

Name
Framework Behavior
Producing Method
Example
Contract Result
Returns a string literal
Content
Content(“nilesh”)
Empty Result
No Response


FileContentResult/FilepathResult/
FileStreamResult
Return the contents of file
File
File(Server.MapPath(“~/Content/site.css”,”text/css”)
RedirectResult
Redirects the client to a new URL
Redirect
RedirectParmanent(“http://nileshviradiya.blogspot.com”)
RedirectToRouteResult
Redirect to another action, or another controller’s action
RedirectToRoute/
RedirecttoAction
RedirectToAction(“index”,”home”,new {name=name })
RedirectToRoute(“Default”, new {controller=”home”,action=”about”})
ViewResult
PartialViewResult
Response is the responsibility of a view engine
View/PartialView

JsonResult
Returns data in JSON format
Json
Json(new { Message=”test”, Name =”nilesh”}, JsonRequestBehavior.AllowGet);
JavaScriptResult
Returns a script to execute.
Javascript

HttpUnauthorizedResult
Returns an HTTP 403 status



Saturday, September 20, 2014

Programming Stuff: What's New in C# 6

Programming Stuff: What's New in C# 6: 1) Auto property initializer: With C# 6 initialize auto properties just like a field at declaration place. The only thing to notice he...

What's New in C# 6

1) Auto property initializer:

With C# 6 initialize auto properties just like a field at declaration place. The only thing to notice here is that this initialization dose not cause the setter function to be invoked internally. the value of backing field is set directly. so here is an example:

public class User
    {
//Auto property initializer
            public Guid Id {get;}=Guid.NewGuid();
    }

2) Primary Constructor:

Primary Constructor allow us to places the parameters for a constructor immediately after the type name and use those parameters inside initializer expression in the rest of the type definition. This save us to write explicit constructor with a lot of  right to left assignment.

public class struct Money(string currency,decimal amount)
    { 
            public string Currency {get;} = currency;
            public decimal Amount {get;} = amount;
    }

3) using Static:

This feature allows you to specify a particular type in a using statement after that all static members of that type will be accessible is subsequent code.

using System.Console
 class Program
    { 
            public static void Main()
            {
                   WriteLine("Hello World");
           }
    }

4) Dictionary Initializer:

some people believed that the old way of initiailzing dictionaries was dirty so the C# team dicided to make it cleaner, thanks to them. here is an example of the old way and new way:

// the old way of initializing a dictionary
            Dictionary oldWay = new Dictionary()
            {
                { "Afghanistan", "Kabul" },
                { "United States", "Washington" },
                { "Some Country", "Some Capital city" }
            };

            // new way of initializing a dictionary
            Dictionary newWay = new Dictionary()
            {
                // Look at this!
                ["Afghanistan"] = "Kabul",
                ["Iran"] = "Tehran",
                ["India"] = "Delhi"
            };


5) ?. Operator

This operator allows to DE-reference valid pointer but it will give me  a null back instead of a null reference exception if object is null.

var name = operation ?. Method ?. Name ?? "No name"

6) Exception filters

Exception filters are already supported in VB compiler but now they are coming into C#. exception filters lets you specify a condition for a catch block. the catch block gets executed only if the condition is satisfied, this one is my favorite feature, so let's look at an example:


           try
            {
                throw new Exception("Me");
            }
            catch (Exception ex) if (ex.Message == "You")
            {
                // this one will not execute.
            }
            catch (Exception ex) if (ex.Message == "Me")
            {
                // this one will execute
            }

7) Declaration expressions:

This feature simply allows you to declare local variable in the middle of an expression. It is as simple as that but really destroys a pain. I have been doing a lot of asp.net web form projects in the past and this was my every day code:
int result = 0 ;
 foreach(var n in var odd= numbers.Where(n=> n%2 ==1).ToList())
{
 result+= n + odd.Count();
}
return result;