Pages

Tuesday, July 12, 2011

Delegates and Anonymous Methods in c#.net

Anonymous Method:
        It is a method without any name.i.e. A normal method is one which will have a name, a return type, optionally arguments and an access modifier. So an anonymous method is a feature to have methods without name.

Where should i use an Anonymous method??
        Anonymous method could be used in place where there is a use of delegate.

Delegate:
        A delegate is similar to function pointer in C++ and C. A function pointer in C is a variable that points to a function. Similarly a delegate is a reference type in .net that is used to call the methods of similar signature as of the delegate.
Ex.
void PrintName(string name)
{
       Response.Write("Name is " +  name  + "<\br>");
}
To call the above method using delegate, we should declare a delegate with similar signature.
Ex.
delegate void DelegateTest(string n);

Before calling we should initialize or register the delegate with the method.
Ex. 
DelegateTest del = new DelegateTest (this.PrintName);

Finally, can call the function by,
Del("Malathy");

The difference between the function pointer in C language and a delegate is, at a given time a function pointer can point to a single funtion only. But delegate are by default they are multicast delegate. ie. they can be used to call multiple functions at a time.

Ex. Consider the function,
void PrintAddress(string address)
{
       Response.Write("City he lives is " + address);
}
To call both PrintName and PrintAddress using delegate, declare as follows.
DelegateTest del = new DelegateTest (this.PrintName);
del += new DelegateTest (this.PrintAddress);
del("Chidambaram");

Now the output is,
Name is Chidambaram.
City he lives is Chidambaram.

By the use of += operator we add new methods to delegates. Thus += operator is used to register a function and -= will remove the registration from the delegate.

Delegate del = new DelegateTest(this.PrintName);
del += new DelegateTest(this.PrintAddress);
del -=  new DelegateTest(this.PrintAddress);
del("Chidambaram");

Now the output is
Name is Chidambaram.

The other difference between a delegate and a function pointer is, a delegate is a type safe, ie.it will throw a compilation error if a method with different signature is assigned to the delegate.

Other than the above examples, the delegates are used in event handling, for callbacks ets. For example, in Webform designer code in VS, there will be,
btnCheck.Click += new EventHandler(this.btnCheck_Click);
Here the event handler is a delegate that is registered with btnCheck_Click event.

Anonymous Methods
        The syntax consists of the keyword delegate, an optional parameter list and method body enclosed in parenthesis.
Ex.
delegate(Optional parameters)
{
     Body of the method.
}

Where to use Anonymous Methods??
       The anonymous representation to implement the PrintName method will be,
delegate void DelegateTest(string n);
protected void Page_Load(object sender, EventArgs e)
{
     DelegateTest PrintName = delegate (String Name)
     {
           Response.Write("Name is " + Name );
     };
}
 
Can be called by
PrintName("Malathy");

And the outpt is
Name is Malathy.

Similar to delegate, we can use += operator to call multiple methods.
Ex.
delegate void DelegateTest (string n);
protected void Page_Load(Object sender, EventArgs e)
{
      DelegateTest test = delegate (StringName)
      {
             Response.Write("Name is " + Name );
      };
      test += delegate (String Address)
      {
            Response.Write("City he lives is " + Address);
      };
      test("Chidambaram");
}

The output is
Name is Chidambaram
City he lives is Chidambaram

An anonymous method without any argument will be like,

delegate void DelegateTestWithoutParam();
protected void Page_Load (object sender, EventArgs e)
{
      DelegateTestWithoutParam delparam = delegate()
      {
            Response.Write("Parameterless anonymous method");
            Response.Write("Name is Malathy");
      };
      delparam();
}

Here the output will be,
Name is Malathy.


Use of Anonymous Methods in Event Handling:
        We can use anonymous methods for events like button click, .
Ex.
btnCheck.Click += new EventHandler(this.btnCheck_Click);
Here btnClick is expecting a delegate and hence we can use anonymous methods. So the event can be written as,
protected void Page_Load(object sender, EventArgs e)
{
       btnClick.Click += delegate(object s, EventArgs ee)
       {
             Response.Write ("Name is Malathy");
        };
}

Here the output on clicking the button is
Name is Malathy.

Important Notes:
1. If a variable is declared outside the anonymous method then, it can be accessed inside the anonymous method.
2. Variables declared inside the anonymous methods are not accessible outside the anonymous method.
3. When a anonymous mehtod is declares without parenthesis, then it can be assigned to a delegate with any signature.


In short:
    We can define an anonymous method as a method without name which allows us to define the body inline.

Why should we use Anonymous Method???
     We can reduce the code by preventing delegate instantiation and registering it methods.
      It increases the readability and maintainability of our code by keeping the caller of the method and the method itself as close to one another as possible.

Thursday, July 7, 2011

Retrieve unique column values from a datatable

This blog explains how to retrieve unique column values from the given System.datatable.

For example assume that the datatable contains the values as follows:
Now when you want to retrieve the unique values of Col3, then it can be achieved as follows.

This code returns the unique column values of the "Col3". Thus the datatable dt2 contains the unique values of  column "Col3" from the dt table.

Retrieve the Filtered records in the form of datatable from the given system.datatable.

In some cases we require to retrieve the records from system.datatable using some Filter criteria and store back in a new datatable. This can be done by the following code.
For example assume that the datatable dt contains the values as follows.
Now to add filter to the dt we use, dt.Select("Filter condition"); But this would return as array of rows only. But when you want return records as datatable we get the help of DataSet as follows:
Thus we get the resultant records in the form of datatable. :) :)

Wednesday, July 6, 2011

Basics of DBMS

Data Base Management System:
        DBMS are collection of tools to manage databases. The four basic functions performed by all DBMS are
            1. Create, Modify, Delete data structures, e.x. tables
            2. Add, Modify, Delete data.
            3. Retrieve data selectively.
            4. Generate reports based on data.

Database:
       A database is a collection of related tables. It can also include other objects like queries, forms and reports. The structure of database is the relationships between its tables.

Components of Database:
       Databases are composed of related tables, which in turn are composed of fields and records.
Field:
       Field is an area( within a record) reserved for a specific piece of data.
       Fields are defined by
               - Field name
               - Data type
               - Field size.
Record:
       It is the collection of values for all the fields pertaining to one entity.
Table:
       It is a collection of related records. In a table records are represented as rows and fields are represented as columns.

Relationships:
       There are 3 types of relationships which can exist between tables:
              - One to One
              - One to Many
              - Many to Many
        Most common relationships in a relational database are One to Many and Many to Many
        Example of One to Many - Customer table and Order table. Each order has only one customer, but a customer can take many orders. They contain 2 tables - the "one" table and "many" table
        Example of Many to Many -  Order and Purchase tables.An order can contain many products and a product can be on many orders. They contain 3 tables.two "one" tables, both in One to Many relationship with the third table.

Database Normalization:
       Normalization is the process of efficiently organizing data in a database.
Goals:
       - Eliminating redundant data
       - Ensuring data dependencies make sense.

Normal Forms:
       The database community has developed a series of guidelines for ensuring that databases are normalized. These are referred to as normal forms and are numbered from one through five.
First Normal Form:
        - Eliminates duplicate columns from the same table.
        - Create separate table for each group of related data and identify each row with a unique column or set of columns (Primary key).
Second Normal Form:
        Address the concept of removing duplicate data.
        - Should be in first normal form.
        - Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
        - Create relationships between these new tables and their predecessors through the use of foreign keys.
Third Normal Form:
        - Meet all requirements of second normal form.
        - Remove columns that are not dependent on the primary key.

Tuesday, July 5, 2011

Method To Check For Record Existence Before Inserting in DB.

In some data base management applications, while creating a new record, we would require to check for any duplication's. i. before inserting we need to check whether the record already exist or not.
This could be handled in 3 different ways.

For example say you need to add new department details. and before inserting check whether the depart already exist or not by using the department name.

Method 1:
     - From code behind (.cs) file, make a call to DB and execute a select statement with where condition to the department name. And in the .cs file have a if condition and check for the no of rows in the returned value.
     - If the row count is 0, then make a call to insert the record.
     - If the row count is more than 1, then return a message saying record already exist.

Method 2: This works out only when the DB is normalized. ie. the table should have a primary key.
     - From the code behind make a call to insert the record, and have this part inside the try catch block. Now if the record doesn't exist, then it gets added successfully, else it throws an exception of primary key constraint. Now this could be got in catch block and give a message saying the record already exist.

Method 3: works out when we use stored procedure for inserting.
     - In the SP, have an "if not exists" condition before the execution of insert command.
ex.

     - We just need to have IF NOT EXISTS condition before insert. Similar to having a if condition in the stored procedure.

Building DAL using Strongly typed data-sets in ASP.Net and SQL Server.

This post explains an sample of implementing strongly typed data set using ASP.Net and SQL server as back-end database.
for an example, we create a DAL class using class library template and add the required strongly typed data set and the code behind to access.
Finally to access these DAL methods, we create a reference of this in our web application and then call the required methods.

Now to implement DAL, the steps are as follows:
1. Create a Class library project and name it as DAL.
2. Include Strongly typed Data set:
        - right click on the project and give Add - > new item.
        - Under Data templates, select DATASET template and specify the name as Sample, and finally give add.

        - Now it includes a new data set (Sample.xsd) to the project.
3. Create connection to SQL server and include the table, queries, stored procedures.
        - To include a store procedure or a query for a corresponding table in sql server, we need to create a data table and table adapter.
        - All attribute details gets stored in the data table and the methods which define the query execution or the stored procedure execution are defined in the table adapter.
        - To add a new table adapter, right click on the xsd, and give Add-> Table Adapter.
       - Now specify the Connection string to get connected with the data base. The already used connection string gets populated in the Connection string drop down. If the required connection string does not exist in the drop down list, then click on the "New Connection" and make a new connection. Then click on next.
 
       - Need to choose the command type. Here we have three options. One - to create a new query, second -  to create a new stored procedure, and finally use the existing stored procedure defined in the corresponding   data base server.Select the required one. For sample, i select the Use existing stored procedure.Then click on Next.

       - Now we need to specify the stored procedures to the commands. Here we have 4 types of command types. Those are the Select, Insert, Update, Delete. And the stored procedures that exist in the given server gets binded to the drop down list of each command.   Every table adapter should contain at least one select command. i.e No table adapter exist without an select command.
         For this sample i just select one of the read stored procedure for the select command.

      -  Specify the methods to be generated. Also give the method name. By default we have Fill and Get methods. For our example, i select only the Get method, and give the method name as "ReadEmployees". And click on next.

      - In the final wizard just click on Finish. This will generate the specified get method, also the default select and update methods. One can access these methods using the object of table adapter.

       - This results in creating a new data table and table adapter along with the methods defined.

  4.Include a class to access the methods defined in the table adapter.
           - Right click the project and give Add - > New item. And select Class under Code template. Name this class as Datahelper.cs
           - Define this class as public as it could be accessible from other class as well.
           - Declare user defined static methods which executes the methods defined in the table adapter.
           - To access the methods, we need to declare an object of the table adapter and this object contains all the methods defined. The returned value is fetched and passed.
           - A sample code snippet resembles as follows

 Similarly it could be done for insert, update and delete.

Thus this makes DAL ready. And it could be used from any class by having a reference to it.

Monday, July 4, 2011

Import Data from Excel to SQL using MS SQL server 2008's Import Export wizard

This blog explains how to import data from excel to an SQL Server.
For this we use Import Export wizard provided by MS SQL server 2008. To run this wizard go to start -> All Programs -> Microsoft SQL Server 2008 -> Import and Export Data (32 bit).
This opens the following wizard.

Now click on next to start with import. This starts with the following wizard :
Through this wizard specify the source of the file. In the data source select Microsoft Excel, and give the path of the Excel sheet. This gives the following wizard
 Now click on Next. Here we need to specify the Destination. Provide the destination as SQL Server Native Client, Server name, Database.
Once the source is specified click on next. And now set whether its table copy or query copy. For sample i have selected the Table copy.
No on clicking the Next, it asks for the Source tables and views. Select the source "Sheet". This would automatically create a new table in the sql server and gets binded to the Destination column. Or we can specify any existing table in sql server as well. But the data type of the excel and the sql server should match for mapping.

Now the next step is to save and run the package. So click next, and in the next wizard check the Run immediately check box. and give next. In the next(Complete wizard) click on the Finish button. This will start the execution process.

This ends up the transfer process. And produces the report like the following fig.
Now when you go to SQL Server, a new table with the data in the excel sheet gets binded under the Database specified....