Friday, October 23, 2015

Difference between Response.Write and Response.WriteLine

Introduction:

In this post we will discuss about the difference between Response.Write and Response.WriteLine in C#. These are the methods we used to show the output in console application. Both these methods come from class Console under namespace System. Behavior of both these are as same as except only one thing.

So what is the difference then?

The only difference is the position of the cursor. In the Write() method the after the output has been printed the cursor remains in the same line, But in case of WriteLine() the cursor shifted to the next line, that means you don't need to worry about the next line printing in WriteLine(). You have to use a new line after using Write() method if you want to continue with the next line. To do so you can use System.Environment.NewLine.

Using Console.Write():

public void Method2()
{
    // Keep the cursor in that line only.
    Console.Write("Hi this is Console.Write. ");

    // Keep the cursor on the next line.
    Console.Write("Hi this is Console.Write. "+ System.Environment.NewLine);
}

Output:


Using Console.WriteLine():

public void Method3()
{
    // Keep the cursor on the next line.
    Console.WriteLine("Hi this is Console.WriteLine. ");
}

Output:


Check the cursor position in both of the output. In the first image the cursor is in the same line and in the second output the cursor is in the next line.


Tuesday, October 20, 2015

Inheritance in OOPs C#

Introduction:

Previously we have discussed about the Abstraction and Encapsulation and their difference in this blog. Today we will go for the other two properties of OOPs in C#, these are Inheritance and Polymorphism.

Description:

As we all know OOPs has 4 properties like
  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism
Already we have discussed about the first two, abstraction & encapsulation. Lets discuss about the other two, Inheritance and Polymorphism.

Inheritance:
Inheritance means getting some thing (properties) as heredity. To get that we need an hierarchical structure. And that is provided by OOPs using Inheritance. Here in inheritance we have an concept of Base class and sub class. The base class is also known as parent class, super class etc. and the sub class is also known as child class. The properties (variables) and methods are accessible to the sub class, but keep that in mind that only the public ones. Not the private methods or variables are accessible from child class. And the methods and accessible, can be call without creating the object of that super class. 

To inherit a class from another class you have to extend the sub class to super class. Follow the bellow example.


class ClassSuper
{
    public void MethdoTestPublic()
    {
        Console.WriteLine("ClassTest.MethdoTestPublic");
    }

    private void MethdoTestPrivate()
    {
        Console.WriteLine("ClassTest.MethdoTestPublic");
    }
}
    
class ClassSub : ClassSuper // Inheriting from ClassSuper
{
    public void MethodTest()
    {
        MethdoTestPublic(); // calling the super class method
        MethdoTestPrivate(); // calling the super class private method [Error]
        Console.WriteLine("ClassTest2.MethodTest");
    }
}


Here ClassSub is extending the ClassSuper to get access to the methods and properties of the super class.

Type of Inheritance:

  1. Single Inheritance
  2. Multiple Inheritance
  3. Multi Level Inheritance
  4. Hierarchical Inheritance
Single Inheritance:
The above example is one of the example of Single Inheritance. 

class ClassSuper
{
    // Do your code
}
    
class ClassSub : ClassSuper // Inheriting from ClassSuper
{
    // Do your code
}

Multi level Inheritance:
Multi level inheritance is the joining of two or more single inheritance. Like Sub Class 2 is inheriting Sub Class 1 and Sub Class 1 is inheriting Super Class. If you watch closely there are two single inheritances are present. One is Sub Class 1 -> Sub Class 2 and second one is Sub Class 1 -> Super Class.

class ClassSuper
{
    // Do your code
}
    
class ClassSub1 : ClassSuper // Inheriting from ClassSuper
{
    // Do your code
}
class ClassSub2 : ClassSub1 // Inheriting from ClassSub2
{
    // Do your code
}

Hierarchical Inheritance:
In case of Hierarchical  interface we have multiple sub classes which are inheriting one super class. Like here Sub Class 1 and Sub Class 2 both are inheriting Super Class, This is Hierarchical Inheritance.

class ClassSuper
{
    // Do your code
}
    
class ClassSub1 : ClassSuper // Inheriting from ClassSuper
{
    // Do your code
}
class ClassSub2 : ClassSuper // Inheriting from ClassSuper
{
    // Do your code
}

Multiple Inheritance:
Multiple Inheritance is just the opposite of Hierarchical Inheritance. Here one sub class is inheriting multiple Super Classes. Like any other object Oriented Programming languages C# also don't support Multiple Inheritance. To achieve that we have to go for Interface, which we will discuss later.
Like here the only Sub Class is inheriting the two Super Classes (Super Class 1 and Super Class 2). This architecture is not possible with C# classes. So we are taking help of Interface to do so.

interface ISuper1
{
    // Do your code
}
    
interface ISuper2
{
    // Do your code
}
class ClassSub : ISuper1, ISuper2 // Inheriting from ISuper1 and ISuper2
{
    // Do your code
}

Advantages of Inheritance:
  1. Reusability: Use the base class public methods and properties from the base class, without defining or creating any instance.
  2. Extensibility : Extend the base class methods logic in the sub class without rewriting the same.
  3. Data hiding: Base class can kept some data private so that it cannot be altered by the derived class.
  4. Override: Base class methods can be overridden by sub class methods to reuse in a meaningful way.
Disadvantages of Inheritance:
  1. Tightly Coupled: In inheritance both the classes (sub and super class) are tightly coupled. So if any change occurs in super class it will affect in the base class. 
  2. Some time many data remains unused in the hierarchy. So memory wastage can be happen in case of inheritance, 

Tuesday, October 6, 2015

Restore database from .BAK frile in Ms. SQL Server

Introduction:

In this post I will show you how to restore a database from a backup file (extension of backup file is .bak). It is the most common way to restore a database though there are other several ways to do so, like through excel, access or csv. But in this section we will discuss with the .BAK files.

Description:
Its a very simple and quick process to restore a database from .BAK file. Lets see what are they..

Step 1:
Open your SQL Management Studio and right click on the Database in Object Explorer. To open Object Explorer go to View and click on the Object Explorer. Now right click on the Database and click on the option Restore Database.


Step 2:
Now select Device radio button and click on the immediate right select button. A new window will open named Select backup Device. Click on the Add button to add the .BAK file. Add the file and click on the OK button.


Step 3:
Now when you came back to the previous window after clicking on the OK button you can see that the database name is already taken by the tool automatically. If you want to change the destination Database name then you can change it otherwise keep it as it is and click on the OK button to proceed.


Step 4:
Now on the right upper corner a green color bar will move with showing percentage. It may take some time to restore the database, as it depends on the size of the database. After finishing a message will be showing with the confirmation.


Now go to your database, it will show your restored database in your Database section in Object Explorer. If it is not showing refresh your Database and it will be seen. Now try with yours one. 

Sunday, October 4, 2015

DataTable.Copy() Vs. DataTable.Clone() in C#

Introduction:

In this post we will discuss about the two major methods of DataTable in C#. One is Copy() and another one is Clone(). Though these two are sounds identical but there are huge difference between these two. Lets see what are those..

Description:

There are two things to copy or clone of a DataTable. These are structure and data. Copy and Clone are playing with these two.

Lets us create a DataTable first.

DataTable dt = new DataTable();
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("Email");
dt.TableName = "MasterTable";
//insert into DataTable
dt.Rows.Add("1", "Arka", "arka@gmail.com");
dt.Rows.Add("2", "Anusua", "anu@gmail.com");
dt.Rows.Add("3""Sayantani""sayantani@gmail.com");

DataTable.Copy():
DataTable.Copy() returns a DataTable with the structure and data of the DataTable.

//Creating another DataTable to copy
DataTable dt_copy = new DataTable();
dt.TableName = "CopyTable";
dt_copy = dt.Copy();

Result:

As here you can see the DataTable dt is being copied with the data and structure to CopyTable.

DataTable.Clone():
Unlike Copy(), DataTable.Clone() only returns the structure of the DataTable, not the rows or data of the DataTable.

//Creating another DataTable to clone
DataTable dt_clone = new DataTable();
dt.TableName = "CloneTable";
dt_clone = dt.Clone();

Result:

As here you can see DataTable dt is being clone with only the structure of the MasterTable to CloneTable.

In short:
Copy() - For both structure and data.
Clone() - For only structure.

Saturday, October 3, 2015

Access modifiers in C#.NET with exampls

Introduction:

Access modifier are the defined level of permission to access properties and methods. By declaring this access modifiers we defining a variable or a event can be access from assembly to within that class. Lets see how.

Description:

There are 4 major access modifiers in C#. These are...

  1. Public
  2. Private
  3. Protected
  4. Internal
  5. Protected Internal
Public:
Using Public a event or a variable can be accessed from outside of  the class, where it belongs. And also from the outside of the assembly. 

class ClassTest
{
    //Public method
    public void MethodPublic()
    {
        // defination of MethodPublic
    }
}

// to access the method
class Program
{
    static void Main(string[] args)
    {
        ClassTest objClassTest = new ClassTest();
           
        objClassTest.MethodPublic(); // valid code to access.  
    }
}

Private:
It restricts the use of methods and variables only within the the class itself. It cant be used from the outside of the class. As you declare a private constructor of a class that class can't be access from the outside that class, you can't create an object of that class,

Example 1: Private keyword
class ClassTest
{
    //Private method
    private void MethodPrivate()
    {
        // defination of MethodPrivate
    }
}
// to access the method
class Program
{
    static void Main(string[] args)
    {
        ClassTest objClassTest = new ClassTest();

        objClassTest.MethodPrivate(); // invalid code to access.  
    }
}


Example 2: Private Constructor 
class ClassTest
{
    private ClassTest() { } // private constructor
}
// to access the method
class Program
{
    static void Main(string[] args)
    {
        // invalid code. can't create an object of this class
        ClassTest objClassTest = new ClassTest();
    }
}

Protected:
This allows variables  and methods to access from that class and the sub class of the class. That means that methods can be access within that class and from the classes, which actually inheriting that class. 

class ClassTest
{
    //Protected variable
    protected int _a;
}

class ClassTest2 : ClassTest
{
    ClassTest2()
    {
        this._a = 10; // can access from this class
    }
}

class ClassTest3
{
    ClassTest3()
    {
        this._a = 10; // can't access from this class
    }
}

Internal:
Internal is introduces in C#. In JAVA we don't have this access modifier. This allows the access after Protected. As Protected it is also allow to access the methods and variables from that class and the sub classes of that class. It added the assembly into it. That means the variables and methods can be access within the assembly where the class belongs. Now make that sure that here we are talking about Namespace, because Namespace and assembly are slightly different. An assembly can hold more than one Namespace. Assemblies are actually the dll of the project.

class ClassTest
{
    internal void MethodInternal()
    {
        // do your code
    }
}
// to access the method
class Program
{
    static void Main(string[] args)
    {
        ClassTest objClassTest = new ClassTest();

        objClassTest.MethodInternal(); // valid code to access.  
    }
}

Protected Internal:
Protected Internal allows you to access the variables and methods to access from that class and sub classes of that class. Also allows to access within the same assembly. Means in protected if the class is inheriting the super class and the method or variable is protected then the assembly doesn't matter to access. But in the Internal the assembly matters if the class is inheriting the super class. That is why we use Protected Internal access modifier. 

class ClassTest
{
    protected internal string name; // protected internal
    public void print()
    {
        Console.WriteLine("\nMy name is " + name);
    }
}
// to access the method
class Program
{
    static void Main(string[] args)
    {
        ClassTest objClassTest = new ClassTest();
        // Accepting value in protected internal variable
        objClassTest.name = "Arka";
        objClassTest.print();
    }
}

In sort:

Public: Any where from the class
Private: Only within the class
Protected: Only within that class and the sub classes of that class
Internal: Within the assembly of the class
Protected Internal: Within that class, sub classes of that class and and assembly.

Hope it will clear your concept about the access modifiers. Don't forget to post your valuable comments. 

Friday, October 2, 2015

Difference between Encapsulation and Abstraction in OOPs (C#.NET)

Introduction:
There are 4 major properties of Object Oriented Programming (OOPs) as you know. These are

  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism
Among of these four properties or features we will discuss about the first two (Abstraction and Encapsulation) in this post. 

Description:

So what actually Abstraction and Encapsulation are? Lets us know with an example

Abstraction:
Abstraction is a process to abstract or hide the functionality and provide users or other programmers to use it only. Like for the method Console.WriteLine(), no one knows what actually happening behind the function calling. We  are just using it by calling and passing the arguments. This is the thing called Abstraction. 

Encapsulation:
Encapsulation means to encapsulate or put every thing into one thing and provide others to use it. Like in a shaving kit there are all the necessary kits are available. And also these kits are available as loose in market. But the shaving kit is encapsulate every other kits into a small bag and provide user to use it. 

Hope so now you have a basic idea about both of these properties, Lets see a real world example of encapsulation and abstraction.

Lets assume you have to create a method to insert an users data and pass it to other developers to use. So first create a class and add a method to insert the data into database with validation. 

There will be three fields 
  1. Name 
  2. Email
  3. Phone number
So these inputs have to validate first and then insert into db.

First create a class with all methods

class User
{
    public bool AddUser(string name, string email, string phone)
    {
        if (ValidateUser(name, email, phone))
        {
            if (AddtoDb(name, email, phone) > 0)
            {
                return true;
            }
        }
        return false;
    }

    private bool ValidateUser(string name, string email, string phone)
    {
        // do your validation
        return true;
    }

    private int AddtoDb(string name, string email, string phone)
    {
        // Write the Db code to insert the data
        return 1;
    }
}

As you can see there are three methods are written in this User class. 
  • AddUser: To call from outside the class. That is why the access modifier is public.
  • validateUser: To validate the user's details. Can't access from out side the class. Its private.
  • AddtoDb: To insert data into database table and again it is private, can't access from out side the class.
Now another user will just call AddUser method with parameters. And that user has no idea what is actually happening inside the method. I didn't write the code to validate and insert into db, as you can get it from others examples. We will discuss about it later. 

To call the AddUser method do like following. 

class Program
{
    static void Main(string[] args)
    {
        User objUser = new User();
        bool f = objUser.AddUser("Arka", "ark@g.com", "1234567890");
    }
}

Now come back to the main discussion.

Here we are hiding the procedure of adding data into database from other users, this is Abstraction. And putting all the three methods into one User class and provide other user to use it that is called Encapsulation

So procedure hiding is Abstraction and putting every necessary things into one is Encapsulation.   
Hope so you have cleared your doubt about the concept of  Encapsulation and Abstraction. 

Popular Posts

Pageviews