Delegates in .NET

Delegates

 

Introduction

            In this article, i am going to discuss about Delegates and how to use a delegate other than event handling. 

            

What is a Delegate?

            Delegate is described as a TYPE SAFE / SELF DESCRIBING FUNCTION POINTER (A Function Pointers are pointers, i.e. variables, which point to the address of a function). A type safe or Self Describing is nothing but, a return type and argument types are defined explicitly in delegate definition. So, onlyamethod, Which has the same signature can be added to the delegate. A delegate object is used to hold the address(reference) of a function.

 

How to Use?

 

To create and use a delegate we have to follow 3 steps. 

 

1. Declaration

2. Instantiation

3. Invocation

 

Steps to Create a delegate

 

1. Declaration:

 

Syntax (C#)

 

delegate result-type Name-of-the-delegate([parameters])

 

for eg. 

        public delegate void MyDelegate();

  

This will holds the address of any functions, which has no return type and no parameters

    

        public delegate int MyParamDelegate(int param1, string param2);

 

This will holds the address of any function, which has return type as integer and accepts two parameters ( integer and string)

 

2. Instantiation:

 

Inside the class you can instantiate a delegate as like creating a instance to the class. But there are lot of difference between the class instantiation and Delegate instantiation

 

Syntax (C#)

       delegate-name instance-name = new delegate-name(function-name);

 

For eg.

        // Declaration 

        public delegate void MyDelegate();

        .

        .

        .

        // Instantiation – inside the class

        MyDelegate delObj = new MyDelegate(MyFunc);

        .

        .

        .

        // MyFunction Definition

        public static void MyFunc()

        {

                // Code here

        }

 

Please note that the signatures of the myFunc and MyDelegate are matching. i.e., myFunc doesn’t have any return type and parameters similar to MyDelegate.

 

You can pass static method as well as instant method. In the case of instant method, you have to pass like instance-name.myFunc()

 

3. Invocation:

 

delObj() – the invocation part is as simple as like invoking a method.

 

Here is the complete code for a simple delegate example

 

namespace ConsoleHarness

{

    // Step 1. Declaration

    public delegate void MyDelegate();

 

    class Program

    {

        static void Main(string[] args)

        {

            //Step 2. Instantiation

            MyDelegate delObj = new MyDelegate(MyFunction); 

 

            //Step 3. Invocation

            delObj();

 

            Console.ReadLine(); 

         }

        

        // MyFunction which has the same signature as delegate

        public static void MyFunction()

        {

            Console.WriteLine(“Message from MyFunction”); 

        }

    }

}

 

Multicast Delegate:

         It is nothing but a delegate which has references to more than one function. For a multicast delegate, the declaration and invocation are similar to the normal delegate. It differs in instantiation to usual delegate. 

 

Here is the Instantiation part of Multicast Delegate (C#)

 

//Step 2. Instantiation

MyDelegate delObj = null; 

delObj += new MyDelegate(MyFunction); 

delObj += new MyDelegate(MyFunction2);

 

Please note that delegate object should be initialized with null value is mandatory in C#. Whereas vb.net it is not required.

 

More Example:

 

All of us heard / read, that delegates are extensively used in Event handling. So i am not going to explain delegate with Event handling. Instead i choose,  Create a custom Sorting by using a delegate.

 

namespace ConsoleHarness

{

    // Customer Class

    public class Customer

    {

        public string Name { get; set; }

        public int Age { get; set; }

    }

 

    // Step 1. Declaration

    public delegate int MyCompare(Customer obj1, Customer obj2);

 

    class Program

    {

        static void Main(string[] args)

        {

            //Step 2. Instantiation

            MyCompare delCompare = new MyCompare(Compare);

  

            List<Customer> custList = new List<Customer>{ 

                        new Customer{Name=”Anbu”},

                        new Customer{Name= “Manik”},

                        new Customer{Name= “Vidhya”},

                        new Customer{Name= “Agil”}, 

                        new Customer{Name= “Kanchi”} 

                        };

 

            MySort(custList,delCompare);

 

            foreach(Customer cust in custList)

            {

                Console.WriteLine(cust.Name); 

            }

            Console.ReadLine(); 

         }

              

        public static void MySort(List<Customer> c,MyCompare delObj)

        {

            bool isSwapped;

            do

            {

                isSwapped = false; 

                for(int i = 0; i < c.Count – 1;i++) 

                {

                    //Step 3. invocation

                    if (delObj(c[i], c[i + 1]) > 0)

                    {

                        var temp = c[i];

                        c[i] = c[i + 1];

                        c[i + 1] = temp;

                        isSwapped = true;

                    }

                }

            } while (isSwapped);  

        }

        // MyFunction which has the same signature as delegate

        public static int Compare(Customer cust1, Customer cust2)

        {

            return cust1.Name.CompareTo(cust2.Name);

        }

    }

 

}

 

Summary

 

In this article, i have explained what is a delegate, how to declare and invoking a delegate, multicasting a delegate and a custom sorting method, which uses a delegate.

 

 

Advertisements

How to debug stored procedures in Visual Studio .NET

This step-by-step article explains two ways that you can debug SQL Server stored procedures and the necessary configuration settings and steps for each approach. A Visual Studio .NET developer can use the Server Explorer to debug SQL Server stored procedures independently of any Visual Studio project, or the developer can step into the code of the stored procedure directly from managed code in a Visual Basic, Visual C#, or Visual J# project.Option 1: Debug a stored procedure in standalone mode

1. Open Server Explorer.NOTE: It is not necessary to add a Data Connection to work with a SQL Server server because SQL Server servers are listed under the Servers node also. You will use the Servers node in the steps that follow; however, you can use a Data Connection to you SQL Server server in the same way.
2. Under the Servers node in Server Explorer, expand the SQL Server machine name, expand the SQL Servers node, expand the SQL Server instance, expand the Northwind database node, and then expand the stored procedures node.
3. Right-click the CustOrderHist stored procedure and then click Step Into Stored Procedure.
4. The Run stored procedure dialog box opens, which lists the parameters of the stored procedure. Type ALFKI as the value for the @CustomerID input parameter and then click OK.
5. In the Visual Studio design environment, a window opens that displays the text of the stored procedure. The first executable line of the stored procedure is highlighted. Press F11 to step through the stored procedure to completion.
6. In the Output window, the following message is displayed, which indicates successful execution: The program ‘SQL Debugger: T-SQL’ has exited with code 0 (0x0).

Option 2: Step into a stored procedure from managed code

1. Create a new Visual Basic Windows Application project.
2. Drag a Button control from the toolbox to Form1. At the top of the Form1 code window, add the following line of code:Imports System.Data.SqlClient
3. Copy the following code into the Button1_Click event procedure:NOTE: Modify the connection string as necessary for your environment.

Dim cn As SqlConnection
        Dim strCn As String
        Dim cmd As SqlCommand
        Dim prm As SqlParameter
        strCn = “Data Source=(local);Initial Catalog=Northwind;” & _
            “Integrated Security=SSPI”
        cn = New SqlConnection(strCn)
        cmd = New SqlCommand(“CustOrderHist”, cn)
        cmd.CommandType = CommandType.StoredProcedure
        prm = New SqlParameter(“@CustomerID”, SqlDbType.Char, 5)
        prm.Direction = ParameterDirection.Input
        cmd.Parameters.Add(prm)
        cmd.Parameters(“@CustomerID”).Value = “ALFKI”
        cn.Open()
        Dim dr As SqlDataReader = cmd.ExecuteReader
        While dr.Read
            Console.WriteLine(“Product ordered: {0}”, dr.GetSqlString(0))
        End While
        dr.Close()
        cn.Close()

4. In Solution Explorer, right-click the project (not the solution) and open the Property pages. Click Configuration Properties in the tree and then click to select the SQL Server Debugging check box on the Debugging page to enable stored procedure debugging.
5. Set a breakpoint on the following line of code:Dim dr As SqlDataReader = cmd.ExecuteReader
6. In Server Explorer, locate and open the CustOrderHist stored procedure as described in Option 1. Right-click the stored procedure and then click Edit Stored Procedure.
7. Set a breakpoint in the stored procedure on the SELECT statement, which is the only line of executable code.
8. Press F5 to run the Visual Basic project.
9. When Form1 appears, click the command button. The code will run to the breakpoint that you set before the stored procedure is called.
10. Press F11. Code execution steps from the ExecuteReader method into the stored procedure window.
11. Press F11 again. The single line of code in the stored procedure, the SELECT statement, executes. Then control returns to your Visual Basic project, and the project runs to completion.
12. To continue to step through the Visual Basic code after you step out of the stored procedure, you must set a second breakpoint in the Visual Basic code after the call to the stored procedure. For example, in the sample code shown in this section, you can set the second breakpoint on the following line:While dr.Read

Troubleshooting

To step from Visual Studio code into a stored procedure, you must enable SQL Debugging in the Project Properties on the Debugging page.
To step through stored procedure code, you must set a breakpoint in the stored procedure itself. Otherwise, debugging steps over the stored procedure and the window for the stored procedure does not open.
To continue to step through Visual Studio code after debugging steps out of a stored procedure, you must set a breakpoint in the project code at a point after the execution of the stored procedure. Otherwise, the code runs to completion after debugging steps out of the stored procedure.
For setup and configuration issues, refer to the section entitled “Setting Up SQL Debugging” in the Visual Studio .NET documentation.

Limitations of stored procedure debugging

The following is a list of limitations that you may encounter when you debug stored procedures and that you do not encounter when you debug Visual Studio code:

You cannot “break” execution.
You cannot “edit and continue.”
You cannot change the order of statement execution.
Although you can change the value of variables, your changes may not take effect because the variable values are cached.
Output from the SQL PRINT statement is not displayed.

Date Time Format in Sql Server

Reference for DateTime format in Sql Server :

SQL Server provides a number of options you can use to format a date/time string. One of the first considerations is the actual date/time needed. The most common is the current date/time using getdate(). This provides the current date and time according to the server providing the date and time. If a universal date/time is needed, then getutcdate() should be used. To change the format of the date, you convert the requested date to a string and specify the format number corresponding to the format needed. Below is a list of formats and an example of the output:

Format # Query (current date: 12/30/2006) Sample

1 select convert(varchar, getdate(), 1) 12/30/06
2 select convert(varchar, getdate(), 2) 06.12.30
3 select convert(varchar, getdate(), 3) 30/12/06
4 select convert(varchar, getdate(), 4) 30.12.06
5 select convert(varchar, getdate(), 5) 30-12-06
6 select convert(varchar, getdate(), 6) 30 Dec 06
7 select convert(varchar, getdate(), 7) Dec 30, 06
10 select convert(varchar, getdate(), 10) 12-30-06
11 select convert(varchar, getdate(), 11) 06/12/30
101 select convert(varchar, getdate(), 101) 12/30/2006
102 select convert(varchar, getdate(), 102) 2006.12.30
103 select convert(varchar, getdate(), 103) 30/12/2006
104 select convert(varchar, getdate(), 104) 30.12.2006
105 select convert(varchar, getdate(), 105) 30-12-2006
106 select convert(varchar, getdate(), 106) 30 Dec 2006
107 select convert(varchar, getdate(), 107) Dec 30, 2006
110 select convert(varchar, getdate(), 110) 12-30-2006
111 select convert(varchar, getdate(), 111) 2006/12/30

Find an element in Array ( .NET )

Most of us will often need to find an element in an array.  In C or C++, we can do this by using the FOR loops. In .NET 2.0, we have a build-in method, which is very simple and powerful too. It is similar to ArrayList’s Contains method. The following code snippet will show this. 

Private Function MyMethod() as string
  Dim countryCodes() As String
  countryCodes = “IND,CHI,JPN”.Split(“,”.ToCharArray)
  If Array.Exists(countryCodes, AddressOf CountryCodeStartsWith) Then
  Return “Exists”
  Else
  Return “Not Exists”
  End If
End Function

Private Function CountryCodeStartsWith(ByVal countryCode As String) As Boolean
  dim Country as string = “INDIA”
  If Country.startsWith(countryCode) Then
     Return True
  Else
     Return False
  End If
End Function

The Array.Exists has two parameters. The first one is nothing but an array where the element is to searched. The second part of the code , which will be confusing for beginners, is a delegate for the function. At the time of execution the elements in CountryCodes – Our Array – will be passed as a parameter to this delegate. also we can customize this matching function very easily.
Hope this will help you.

Difference between two Dates in C#.NET ?

To find the difference between two dates is very simple in VB — By using DateDiff method. But in C#, there is no direct method to do so. but there is a way to achive this. For this we need to understand TimeSpan Class.

The following code snippet will show you how to find the difference.

DateTime startTime = DateTime.Now;
DateTime endTime = DateTime.Now.AddSeconds( 75 );
TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( “Time Difference (seconds): ” + span.Seconds );
Console.WriteLine( “Time Difference (minutes): ” + span.Minutes );
Console.WriteLine( “Time Difference (hours): ” + span.Hours );
Console.WriteLine( “Time Difference (days): ” + span.Days );

By concatenating all this you will get the difference between two dates. You can also use span.Duration().

There are certain limitations to. The TimeSpan is capable of returning difference interms of Days, Hours, mins and seconds only. It is not having a property to show difference interms of Months and years.

Hope this will help you… 

First make your habits and then your habits make U!!!

PLAN while others are Playing.
STUDY  while others are Sleeping.
DECIDE while others are Delaying.
PREPARE while others are Daydreaming.
BEGIN while others are Procrastinating.
WORK  while others are Wishing.
SAVE while others are Wasting.
LISTEN while others are Talking.
SMILE while others are Frowning.
COMMEND while others are Criticizing.
PERSIST while others are Quitting.