Translate

Saturday, April 30, 2011

c# delegates tutorial


What is a Delegate?

In the English language one of the meanings of a delegate is "To commit or entrust to another". Thats precisely what a delegate does in C#. When called, it entrusts (delegates) the job to another method (function). If you are coming from the C++ world, you must note that in C++ delegate is implemented as a function pointer, but C# it is implemented as a class.

In the example below I define a delegate. Then I use instances of that delegate to call two different methods.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegateExample
{
    class Program
    {

        /*DECLARE THE DELEGATE WITH THE SAME SIGNATURE AS THE FUNCTION TO BE CALLED*/
        delegate void myDelegate();
      

        static void Main(string[] args)
        {
            /*INSTANTIATE THE DELEGATE INSTANCE TO THE FUNCTION THAT NEEDS TO BE CALLED*/

            myDelegate myDel1= SayHello;

            myDelegate myDel2 = SayGoodBye;


            myDel1();
            //Displays Hello!


            myDel2();
            //Displays Bye!
        }

        private static void SayHello()
        {
            Console.WriteLine("Hello!");
        }


        private static void SayGoodBye()
        {
            Console.WriteLine("Bye!");
        }

    } 

}


Output window


















One important thing to remember about delegates is that, it can be passed as a parameter (which you cannot do with methods)


Using Delegate as a parameter to a method


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Delagate
{
    class Program
    {
        delegate int myDelegate(int x, int y);
        static void Main(string[] args)
        {
            int a = 2;
            int b = 3;

            bool doYouWantToAdd = false;
            myDelegate myDel;

            if (doYouWantToAdd == true)
            {
                myDel = Add;
            }
            else
            {
                myDel = Subtract;
            }

            int z = AddOrSubtract(myDel, a, b);
            Console.WriteLine(z);
        }

        static int Add(int a, int b)
        {
            return (a + b);
        }

        static int Subtract(int a, int b)
        {
            return (a - b);
        }

        static int AddOrSubtract(myDelegate myDel, int a, int b)
        {
            //This method accepts a delegate as a parameter
            return myDel(a, b);
        }
    }
}


Using Delegate to create an anonymous method

Anonymous method is a shorthand way to assign a method to a delegate without having to declare a method separately. Anonymous method is an important (but simple) concept to be learned before you can learn Lambda expressions.

In this example below, instead of separately creating an add method, I will directly declare it when I instantiate the delegate.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegateExample
{
    class Program
    {

        delegate int myDelegate(int a,int b);

        static void Main(string[] args)
        {

            myDelegate myDel1 = new myDelegate(delegate(int a, int b) { return (a + b); });//the add method is an anonymous method here

            int addResult=myDel1(1, 2);
            Console.WriteLine(addResult);//displays 3

        }     

    }

}



Extension methods example C#

Using this technique you can add methods to existing types. Say you want a method in the type string which returns the characters in the string in the reverse order
 You could probably
1>Inherit from the class System.String, (suppose you called this inherited class as MyStringExtension )add the new method called Reverse() to the inherited class. Then declare a variable of the type MyStringExtension instead of declaring it a string. Then call the method Reverse() on it.
OR
2>Take the faster route and declare an extension method on the type string.

In the code below I have declared an extension method on the type string, that just returns the string  "Dilbert" when called.


Adding an extension method to the type string

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExtensionMethodExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string s="";
            //Here ReplaceDilbert() is an extension method on the type string
            Console.WriteLine(s.ReplaceDilbert());
            //Displays Dilbert
        }       
    }


    static class StringExtension
    {
        //This method must be static
        public static string ReplaceDilbert(this string s)//notice there is a this keyword
        {
            return "Dilbert";
        }
    }
}


Adding an extension method to the type float

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExtensionMethodExample
{
    class Program
    {
        static void Main(string[] args)
        {
            float f= 10;
            Console.WriteLine(f.GetInverse());
            //Displays 0.1
        }       
    }


    //This class must be static
    static class StringExtension
    {
        //This method must be static
        public static float GetInverse(this float f)//notice there is a this keyword
        {
            return 1 / f;
        }
    }
}

You can define your extension method in a different class or namespace, just make sure that it (the class and namespace containing the extension method) is accessible to the calling code.




Anonymous Types C# example


Instead of explicitly defining the types, you can let the compiler create that type for you in the background. These types where you do not explicitly declare the type, are called anonymous types.

In the example below, the compiler creates a class with three properties Name,Course and GPA in the background.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AnonymousExample
{
    class Program
    {
        static void Main(string[] args)
        {

            //The line below is a short cut technique to create an object with the name student
            //and set three public properties
            var student = new { Name = "Dilbert", Course = "C#", GPA = 3.0 };

            Console.WriteLine(student.GetType());
            //Displays <>f__AnonymousType0`3[System.String,System.String,System.Double]

            Console.WriteLine(student.Name);
            //Displays Dilbert


            //Properties set thru Anonymous types are read only
            student.Name = "Dilton"
//Throws compiler error:Error     1     Property or indexer 'AnonymousType#1.name' cannot be assigned to -- it is read only      
           

        }
    }
}

Thursday, April 28, 2011

Object initializer C#

Consider the code of a console application below


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PlayInitializer
{



    public class Human
    {
      
        public string Name
        {
            get;
            set;
        }

        public int  Age
        {
            get;
            set;
        }

    }

    class Program
    {
        static void Main(string[] args)
        {

            Human hu1 = new Human();
            hu1.Name = "John";
            hu1.Age=39;

            Human hu2 = new Human();
            hu2.Name = "Simon";
            hu2.Age = 32;
        }
    }



}



Object initializer is a short cut technique where you can initialize the public properties of a class quickly, as shown in the code below.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PlayInitializer
{



    public class Human
    {
      
        public string Name
        {
            get;
            set;
        }

        public int  Age
        {
            get;
            set;
        }

    }

    class Program
    {
        static void Main(string[] args)
        {

            Human hu1 = new Human { Name = "John", Age = 39 };


            Human hu2 = new Human { Name = "Simon", Age = 32 };
        }
    }


}


Wednesday, April 27, 2011

How to bind a datatable to dropdownlist


I have a dropdownlist (my ddl) and I want to bind it to a datatable (myDataTable).   The datatable has two columns departmentNumber and departmentName         


 myddl.DataSource = myDataTable;
 myddl.DataTextField = "departmentName";
 myddl.DataValueField = "departmentNumber";
 myddl.DataBind(); 

Monday, April 25, 2011

Connect to db2 from asp.net using ODBC


In this article I will show you how to connect to an IBM db2 database from asp.net using an ODBC data provider and enterprise library 5.0. Enterprise library is used here just to reduce the amount of code. Its not a show stopper. But you do need to install an ODBC data provider. Usually ODBC data provider ships with an ODBC db2 connection client. Ive heard there are free versions of ODBC providers out there, but Ive never come across a reliable one. Clients I worked for usually used an IBM ODBC provider.























To connect to DB2 using an OLEDB data provider check out
http://dotnetanalysis.blogspot.com/2011/02/aspnet-db2-connect.html

Prerequisites for this article :
ODBC data provider
.net version 3.5
Microsoft enterprise library 5.0 (download page)


This is what you do.

1>Create an asp.net application and add  a grid view

            <asp:GridView ID="GridView1" runat="server" >
            </asp:GridView>


2>Add this connection string to your web.config

  <connectionStrings>

    <add name="DB2LOGIN" connectionString="Driver={IBM DB2 ODBC DRIVER};Database=DBName;Hostname=serverName;Port=446; Protocol=TCPIP;Uid=userName;Pwd=password;" providerName="System.Data.Odbc" />

  </connectionStrings>


3> Add a reference to these 5 dlls in the enterprise library 5.0

Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.Unity.dll
Microsoft.Practices.Unity.Interception.dll
Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.ServiceLocation.dll


4>Add this code to the .cs page 

using System;

using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace DB2Read
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();

            string connectionStringName = "DB2LOGIN";

              Database db = DatabaseFactory.CreateDatabase(connectionStringName);
            DbCommand dbCommand = db.GetSqlStringCommand("SELECT * FROM myTableName");
            db.LoadDataSet(dbCommand, ds, "tblName");

            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
        } 


    }
}




Run the app and what ever is in your db2 table myTableName , that will be displayed on your web page.



If you don't want to use Microsoft enterprise library, you can look at the sample code below that uses a helper class from Microsoft. Not sure if it is supported anymore. But it works very well.


public static DataTable DB2data(OdbcParameter[] Params, string spName, string connString)
        {

            DataSet ds = new DataSet();



            GotDotNet.ApplicationBlocks.Data.AdoHelper DB2Helper;
            DB2Helper = GotDotNet.ApplicationBlocks.Data.AdoHelper.CreateHelper("GotDotNet.ApplicationBlocks.Data", "GotDotNet.ApplicationBlocks.Data.Odbc");


            using (OdbcConnection DBConn = new OdbcConnection(connString))
            {
                DBConn.Open();
                ds = DB2Helper.ExecuteDataset(DBConn, spName, Params);
                DBConn.Close();
            }



            return ds.Tables[0];

        }