27 August 2013

Tracing in Asp.Net

Tracing displays the details about how the code was executed. It refers to collecting information about the application while it is running. Tracing information can help you to troubleshoot an application. 
It enables you to record information in various log files about the errors that might occur at run time. 
You can analyze these log files to find the cause of the errors.

In .NET, we have objects called Trace Listeners. A listener is an object that gets the trace output and stores it to different places, 
such as a window, a file on your locale drive, or a SQL Server.

The System.Diagnostics namespace contains the predefined interfaces, classes, and structures that are used for tracing. It supplies two classes, Trace and Debug, which allow you to write errors and logs related to the application execution. Trace listeners are objects that collect the output of tracing processes.
Page level Tracing
ASP.NET tracing can be enabled on a page-by-page basis by adding "Trace=true" to the Page directive in any ASP.NET page:
<%@ Page Language="C#" Trace="true" TraceMode = "SortByCategory"
 Inherits  ="System.Web.UI.Page" CodeFile="Default.aspx.cs" %>
Additionally, you can add the TraceMode attribute that sets SortByCategory or the default, SortByTime. You can use SortByTime to see the methods that take up the most CPU time for your application. You can enable tracing programmatically using the Trace.IsEnabled property.
Application Tracing
You can enable tracing for the entire application by adding tracing settings in web.config. In below example, pageOutput="false" and requestLimit="20" are used,
so trace information is stored for 20 requests, but not displayed on the page because pageOutput attribute is set to false.
<configuration>
    <appSettings/>
    <connectionStrings/>
    <system.web>
        <compilation debug="false" />
        <authentication mode="Windows" />
      <trace enabled ="true" pageOutput ="false" requestLimit ="20" traceMode="SortByTime " />        
    </system.web>
</configuration>
The page-level settings take precedence over settings in Web.config,
 so if enabled="false" is set in Web.config but trace="true" is set on the page, tracing occurs.

Web.Config Vs Machine.Config

Machine.Config:-

1) This is automatically installed when you install .Net Framework.
2)Only one machine.config file can exist on a server.
3) This file is at the highest level in the configuration hierarchy.
4)Its like a common repository for standard items and its over ridden by web.config file.
5)With out the Machine.Config file Application can not be executed.

Web.Config:-

1) This is automatically created when you create an ASP.Net web application project.
2)This file inherits the settings from the machine.config
3)With out the Web.Config file Application can still be executed.


1. web.config and machine.config both are the configuration  files
2. web.config files contains settings specific to a web application, 
machine.config file contains settings to computer.

Response.Write Vs Response.output.write()
Simply Response.write() is used to display the normal text and Response.output.write() is used to display the formated text.
Example:
Response.Output.Write(".Net{0},"ASP"); // Its write
Response.Write(".Net{0},"ASP"); // Its Wrong
Response.Redirect Vs Server.Transefer
1.Response.redirect sends message to the browser saying it to move to some different page while Server.transfer does not send any message to the browser but rather redirects the user directly from the server itself.So in Server.transfer their is no round trip while Response.redirect has a round trip hence puts a load on the server. 
2.Using Sever.transfer you cannot redirect to a different server itself while using Response.redirect you can redirect to a different server also. 
3.With Server.transfer you can preserve your information.It has a parameter called as "preserve form",so the existing query string etc will be avilable in the calling page.This is not possible in Response.redirect 
Response.Redirect() Vs  Response.RedirectParmanent()
Response.Redirect() :
Search Engine will take this redirection as Temporary(Status 301) and always keep first page in its cache. 
Response.RedirectParmanent() : 
Search Engine will take this a permanent redirection(Status 302) and will remove first page from its database and include second page for better performance on search. 
Useage: 
Response.Redirect used when your page is temporarily changed and will again be reverted to original within a short time. 
Response.RedirectParmanent() when you are thinking of deleting the original page totally after the search engines changes its database. 

Delegate

A delegate is simply a variable pointing to a method (or a list of methods)

Delegate type in .Net is type safe object that points to a method(or list of methods) that can be invoked whenever you want.
Basically delegate has to contain three elements

  • The name (or Address) of method which it is calling
  • Arguments, if method contains any
  • Return value, if method returns any

You can invoke method synchronously or asynchronously by using delegate. Delegate uses three methods to invoke any method. Those are Invoke(), BeginInvoke() and EndInvoke(). Invoke() is used to invoke the method synchronously. BeginInvoke() and EndInvoke() methods are used to invoke the method asynchronously.

Creating Simple Delegate:
If you want to create a delegate in C#, you have to use “delegate” keyword. You can give any name to your delegate, but signature (parameters, return type) has to match with the method.

For example if you want to create simple delegate that match to Add() method which takes two integer parameters and return type is string.

public delegate string SimpleDelMath(int i, int j);

As shown above we are creating the simple delegate in C# which has same signature as compared with Add() method.

namespace DelegatesinCSharp
{
    class SimpleDelegate
    {
        public static string Add(int x, int y)
        {
            return "Sum of " + x + " and " + y + " is : " + (x + y);
        }
    }
}

Invoke the Add() method by using SimpleDelMath delegate as shown below.

namespace DelegatesinCSharp
{
    class Program
    {
        public delegate string SimpleDelMath(int i, int j);       
 
        static void Main(string[] args)
        {
            SimpleDelMath objDel = new SimpleDelMath(SimpleDelegate.Add);
            Console.WriteLine(objDel(1, 2));
            Console.ReadLine();          
        }
    }
}

First we created the object for delegate SimpleDelMath, then we are invoking the method by passing the required parameters to delegate object as shown below.

objDel(1, 2);

Multicast Delegate in C#:
Multicast Delegate in C# means ability to invoke multiple methods by using delegate. To invoke multiple methods by using delegate, methods have to follow some rules.

For Multicast Delegate in C#, methods does not have return type and all methods need to have same signature.

namespace DelegatesinCSharp
{
    class MulticastDelegate
    {
        public static void Add(int x, int y)
        {
            Console.WriteLine("Sum of " + x + " and " + y + " is : " + (x + y));
        }

        public static void sub(int x, int y)
        {
            Console.WriteLine( "Sub of " + x + " and " + y + " is : " + (x - y));
        }
    }
}

namespace DelegatesinCSharp
{
    class Program
    {
        public delegate void MultiDelMath(int i, int j);
        static void Main(string[] args)
        {
            MultiDelMath objMultiDel = new MultiDelMath(MulticastDelegate.Add);
            //Adding another method to the delegate object
            objMultiDel += new MultiDelMath(MulticastDelegate.sub);
            objMultiDel(1, 2);
            Console.ReadLine();
        }
    }
}

As shown above, created the delegate object MultiDelMath. At first added the Add() method to MultiDelMath delegate and next added the Sub() method to MultiDelMath delegate b y using += operator as shown below.

            MultiDelMath objMultiDel = new MultiDelMath(MulticastDelegate.Add);
            //Adding another method to the delegate object
            objMultiDel += new MultiDelMath(MulticastDelegate.sub);  

And we are invoking these two methods at a time by passing parameters as shown below.

            objMultiDel(1, 2); 

The output of multicast delegate is as shown below.




If you want, even you can delete method from delegate at any time as shown below. 

namespace DelegatesinCSharp
{
    class Program
    {  
        public delegate void MultiDelMath(int i, int j);
        static void Main(string[] args)
        {
            MultiDelMath objMultiDel = new MultiDelMath(MulticastDelegate.Add);
            //Adding another method to the delegate object
            objMultiDel += new MultiDelMath(MulticastDelegate.sub);
            objMultiDel(1, 2);
            //removing sub method from delegate object
            objMultiDel -= new MultiDelMath(MulticastDelegate.sub);
            objMultiDel(1, 2);
            Console.ReadLine();
        }
    }

As shown above, you are deleteing method sub by using below code. 

objMultiDel -= new MultiDelMath(MulticastDelegate.sub); 

The output after deleting the second method is as shown below, only invoke first method Add().

26 August 2013

Javascript Calling from Code behind in ASP.NET

Calling a javascript function in an aspx page is a general scenario but calling the same function from code behind and registering a javascript in the code behind and dynamically calling that function is something new and have to learn. So in this article you can find out different scenarios of calling a javascript function.

1.       Calling a javascript function from aspx page (general way)
2.       Calling a javascript function from code behind
3.       Registering a javascript function dynamically and calling it through an event.
4.       Dynamically calling a dynamically registered javascript function.

ASPX PAGE:
In the aspx page we can simply writes the code like as following and in an any events of control we can fire the function.

Default.aspx:  
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
    function CallingFun()
    {
        alert('Hi, Iam javascript function. Calling from asp.net');
    }
    function test()
    {
        alert('Hi, This is from button(general way)’);
    }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
<%--calling test function here--%>
    <input type="button" value=”Click Me” onclick=”test()” />

<%--calling testing function which is dynamically registered from code behind--%>
    <input type="button" runat="server" id="btnclick" value="Call Code behind Javascript method" onclick="testing()"/>
    </div>
    </form>
</body>
</html>


Code Behind:
using System;
using System.Web.UI;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        javaScript();
        System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "Script""CallingFun();"true); 
    }
    private void javaScript()
    {
        string script = @"<script type=""text/javascript"" language=""Javascript"">
            function testing()
            {
                            alert('Hey Dude, Im from code behind');                                                                                                                 
            }
            </script>";
        Page.ClientScript.RegisterClientScriptBlock(GetType(), "sivagtest", script);
    }
}

Implementing Multiple Interfaces which have same method name and same signature in C#

n C#, we cannot inherit multiple classes but we can accomplish multiple inheritance through interfaces. That means we can implement multiple interfaces.

There are some situations where we have requirement to implement multiple interfaces which has method same name and same signature. In this scenario, we cannot find which interface method class implements. To solve this issue, you have to mention interface name before the method name whenever you are implementing the interface method in class.

For example you have two interfaces EmpInterface1, EmpInterface2 which method empName() with the same signature as shown below.

interface EmpInterface1
{
        string empName();
}

interface EmpInterface2
{
        string empName();

Now whenever you are implementing the these two interfaces mention interface name also before the method name as shown below.

class Employee:EmpInterface1,EmpInterface2
 {
        #region EmpInterface1 Members 

        string EmpInterface1.empName()
        {
            return "ABC";
        }

        #endregion

         #region EmpInterface2 Members

        string EmpInterface2.empName()
        {
            return "DEF";
        }

        #endregion
}

As shown above, we are implementing the EmpInterface1 empName() method as EmpInterface1.empName() and EmpInterface2 empName() method as EmpInterface2.empName().

To access these two methods from client through by creating the object for Employee class and access this object through EmpInterface1 and EmpInterface2 interfaces as shown below.

class Program
{
        static void Main(string[] args)
        {
            EmpInterface1 objEmp1 = new Employee();
            EmpInterface2 objEmp2 = new Employee();

            Console.WriteLine("EmpInterface1 empName() method result: {0} \nEmpInterface2 empName() method result: {1}", objEmp1.empName(), objEmp2.empName());

            Console.ReadLine();
        }
}

Here you are accessing the EmpInterface1 empName() method through EmpInterface1 reference and EmpInterface2 empName() method through EmpInterface2 reference.

The output displays as shown below.


Pass By Value and Pass By Reference in C#

In C#, when argument is passed by value, the called method receives the copy of the variable value while argument is passed by reference the called method receives only reference not value. 
In the case of Pass by value in C# called method cannot change the received variable value because it receives value. In the case of Pass by reference the called method can change the received variable value because it receives reference and in the case of pass of pass by reference only one copy of variable value is maintained, only references are passed to called methods. But in the case of pass by value the number of copy variable value is depend on the number of called methods, that means if there are five called methods then there are five copies are maintained. 
Pass By Value in C#:
using System;

namespace CSharpPassByValueReference 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            int j = 10; 
            Console.WriteLine("Before Pass By Value: " + j.ToString()); 
            Display(j); 
            Console.WriteLine("After Pass By Value: " + j.ToString());  
            Console.ReadLine();   
        } 

        private static void Display(int i) 
        { 
            i = 20;               
        } 
    } 
}

As shown above, we are passing the arguments to the Display() method by value and the output is as shown below. 

As output shown, the value of the passed variable is same before and after calling the method in the case of pass by value. 
Pass By Reference in C#: 
using System;
namespace CSharpPassByValueReference 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            int j = 10; 
            Console.WriteLine("Before Pass By Value: " + j.ToString()); 
            Display(ref j); 
            Console.WriteLine("After Pass By Value: " + j.ToString());  
            Console.ReadLine();  
        }

        private static void Display(ref int i) 
        { 
            i = 20;               
        } 
    } 
}

As shown above, we are passing the arguments to the Display() method by ref and the output is as shown below. 
  
As output shown, the value of the passed variable is different before and after calling the method in the case of pass by reference.