Wednesday, November 29, 2017

Method Overriding in C#

n this blog, I'm trying to explain the concept of method overriding.

Method overriding is the concept of polymorphism and also uses the inheritance. In method overriding, firstly we inherit the base class method into derived class and then changes its functionality according to our need.

When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same prototype.

Method Overriding requires:

1-Same method name in both base class and derived class

2-Number of parameters should be same.

3-Data type of parameters should be same.

Method overriding is possible only in derived classes, but not within the same class. When derived class needs a method with same signature as in base class, but wants to execute different code than provided by base class then method overriding will be used.

To implement the method overriding:

1-virtual or abstract keyword is used with method in base class.

2-override keyword is used with method in derived class.

Example 1

Using virtual and override keyword

using System;

 

namespace MethodOverridingConsoleApplication

{

    class BaseClass

    {

        /// <summary>

        /// cityname() with virtual keyword

        /// </summary>

        /// <returns></returns>

        public virtual string cityname()

        {

            return "New York";

        }

    }

    class DerivedClass : BaseClass//inherit the base class

    {

        /// <summary>

        /// cityname() with override keyword

        /// </summary>

        /// <returns></returns>

        public override string cityname()

        {

            return "London";

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            BaseClass bc = new BaseClass();

            DerivedClass dc = new DerivedClass();

            //calls the method

            Console.WriteLine("Your city :"+bc.cityname());

            Console.WriteLine("Your city :" + dc.cityname());

        }

    }

}

Output :

Your City : New York

Your City : London

In this example , i have created a method cityname() in base class and overrides it in derived class. In class Program , objects of base class bc and derived class dc are created and calls the same method one by one ,see the difference in output - when cityname() called with base class object bc outputs comes "New York" and when cityname() called with derived class object dc the output comes "London" ,it means that the functionality of cityname() method only changed for derived class, not for base class.

Example – 2

Using abstract and override keyword

using System;

 

namespace MethodOverridingConsoleApplication2

    {

        /// <summary>

        /// cityname() with abstract keyword in abstract class

        /// </summary>

        abstract class BaseClass

        {

            public abstract string cityname();

        }

        class DerivedClass : BaseClass

        {

            /// <summary>

            /// cityname() with override keyword

            /// </summary>

            /// <returns></returns>

            public override string cityname()

            {

                return "London";

            }

        }

        class Program

        {

            static void Main(string[] args)

            {

                DerivedClass dc = new DerivedClass();

                Console.WriteLine("Your city :" + dc.cityname());

            }

        }

    }

}

Output :

Your City : London

JAGGED ARRAYS IN C#

Jagged Arrays in C#

In this post, we will learn about Jagged Arrays in C# with an example.
Description

A Jagged array is an array of arrays. Jagged Array is also called "array of arrays" because its elements are arrays. The element size of a jagged array can be different. 

Types of Arrays in C#

Arrays can be divided into the following three categories.

    Single-dimensional arrays
    Multidimensional arrays or rectangular arrays
    Jagged arrays

Declaration of Jagged Array

Declare jagged array that has two elements.

    int[][] _RollNumber = new int[2][];

Initialization of Jagged Array

Write the below lines to initialize a Jagged Array. The size of the elements can be different.

_RollNumber[0] = new int[2];    
_RollNumberr[1] = new int[3]; 

Now, create a  in Visual Studio and write the below lines of code in it.

    using System;    
    using System.Collections;    
    using System.Collections.Generic;    
    namespace ConsoleDemo    
    {    
        class Program    
        {    
            static void Main(string[] args)    
            {    
                // Jagged Array Example    
                int[][] _JaggedArrayExample = new int[2][];// Declare jagged array      
                _JaggedArrayExample[0] = new int[] { 11, 21, 31, 41 };// Initialize the array with value           
                _JaggedArrayExample[1] = new int[] { 42, 52, 62, 72, 83, 93 };    
                // Raed and print array elements      
                for (int i = 0; i < __JaggedArrayExample.Length; i++)    
                {    
                    for (int j = 0; j < __JaggedArrayExample[i].Length; j++)    
                    {    
                        System.Console.Write(__JaggedArrayExample[i][j] + " ");    
                    }    
                    System.Console.WriteLine();    
                }    
                Console.ReadKey();    
            }    
        }        
    }   

Output

11 21 31 41
42 52 62 72 83 93

HOW TO IMPORT OR EXPORT SQL SERVER TABLE DATA IN MS-EXCEL SHEET USING C# CODE

In this blog I will show you how to export SQL Server table data in Excel sheet using c# code. Here I'm making application which import excels data in data table and export SQL Server data into excel sheet file.

Here I've two buttons; Import and Export which are using to import and export data from Excel to SQL Server and SQL Server to Excel.

Application Code:

private void btnImport_Click(object senderEventArgs e)

        {

             // Create Data Table for MS-Office 2007 or 2003

            System.Data.DataTable dtExcel = new System.Data.DataTable();

            dtExcel.TableName = "MyExcelData";

            string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\Sachindra\Desktop\MyExcel2003.xls';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";

            OleDbConnection con = new OleDbConnection(SourceConstr);

            string query = "Select * from [Sheet1$]";

            OleDbDataAdapter data = new OleDbDataAdapter(querycon);

            data.Fill(dtExcel);

 

            MessageBox.Show("Data Imported Successfully into DataTable");

        }

 

        private void btnExport_Click(object senderEventArgs e)

        {

            // Create sql connection string

             string conString = @"Data Source =  XXXX ; Initial Catalog = XXXX; User Id = XXXX; Password = XXXX;";

            SqlConnection sqlCon = new SqlConnection(conString);

            sqlCon.Open();

 

            SqlDataAdapter da = new SqlDataAdapter("select * from tblTest"sqlCon);

            System.Data.DataTable dtMainSQLData = new System.Data.DataTable();

            da.Fill(dtMainSQLData);

            DataColumnCollection dcCollection = dtMainSQLData.Columns;

             // Export Data into EXCEL Sheet

            Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = newMicrosoft.Office.Interop.Excel.ApplicationClass();

             ExcelApp.Application.Workbooks.Add(Type.Missing);

             // ExcelApp.Cells.CopyFromRecordset(objRS);

            for (int i = 1i < dtMainSQLData.Rows.Count + 1i++)

            {

                 for (int j = 1j < dtMainSQLData.Columns.Count + 1j++)

                {

                    if (i == 1)

                        ExcelApp.Cells[ij= dcCollection[j - 1].ToString();

                    else

                        ExcelApp.Cells[ij= dtMainSQLData.Rows[i - 1][j - 1].ToString();

                 }

             }

             ExcelApp.ActiveWorkbook.SaveCopyAs("C:\\Users\\Sachindra\\Desktop\\test.xls");

             ExcelApp.ActiveWorkbook.Saved = true;

             ExcelApp.Quit();

             MessageBox.Show("Data Exported Successfully into Excel File");

        }

     }

 So with the help of this application you could import data in SQL Server data table from Excel Sheet and export data from SQL Server table to Excel Sheet using C# code.  Thanks for reading this article.

If you're using any third party tool to perform this task or something like this task, there is one famous tool MindStick DataConverter which provides import export functionality.

How to Create Log File in C#

Log file can be simple text fileXML document or we can also use tables in database to create log. Here I have used .txt file. In this file we have stored information about generated exception of application. Using this log file we have easily find out error list. In this file we have stored information according our requirement. For example in log file we have stored file nameexception namedate and timeerror line numberevent name, Controls name etc.

Now let's to implementation

Step 1: Write down below line of code in global area within your application such that global class or used it as global.

public void LogFile(string sExceptionName, string sEventName, string sControlName, int       nErrorLineNo,string sFormName)

        {

            StreamWriter log;

            if (!File.Exists("logfile.txt"))

            {

                log = new StreamWriter("logfile.txt");

            }

            else

            {

                log = File.AppendText("logfile.txt");

            }

            // Write to the file:

            log.WriteLine("Data Time:" + DateTime.Now);

            log.WriteLine("Exception Name:" + sExceptionName);

            log.WriteLine("Event Name:" + sEventName);

            log.WriteLine("Control Name:" + sControlName);

            log.WriteLine("Error Line No.:" + nErrorLineNo);

            log.WriteLine("Form Name:" + sFormName);

            // Close the stream:

            log.Close();

        }

    }

Note

·         Include System.IO namespace.

·         LogFile method call by catch section when any exception is triggered.

·         LogFile method takes five arguments that used to write within logfile.txt.

·         logfile.txt is file that stored in your application bin/debug folder.

Step 2: Write below ExceptionHelper class (line of code) that return occurred error line number.

public static class ExceptionHelper

    {

        public static int LineNumber(this Exception e)

        {

           int linenum = 0;

            try

            {

                linenum = Convert.ToInt32(e.StackTrace.Substring(e.StackTrace.LastIndexOf(":line") + 5));

            }

            catch

            {

                //Stack trace is not available!

            }

            return linenum;

        }

    }

Step 3: Now put your line of code within try and catch blog and call LogFile method as below

try

            {

                //put here your code

            }

            catch (Exception exe)

            {

               //call LogFile method and pass argument as Exception message, event name, control         name, error line number, current form name

                LogFile(exe.Message, e.ToString(), ((Control)sender).Name, exe.LineNumber(), this.FindForm().Name);

            }

Step 4: If any exception is generated then LogFile.txt look like as below

Data Time:3/6/2013 4:29:47 PM

Exception Name:Input string was not in a correct format.Couldn't store <LineNumber> in salary Column. Expected type is Double.

Event Name:System.Windows.Forms.MouseEventArgs

Control Name:btnUpdate

Error Line No.:106

Form Name:Opereation