Wednesday 11 May 2011

Encrypting and Decrypting connectionString in web.config file

HTML page code:
<form id="form1" runat="server">
    <div>
   
        <table class="style1">
            <tr>
                <td class="style3">
                    <asp:Button ID="Button1" runat="server" Height="36px" onclick="Button1_Click"
                        style="font-size: large" Text="Encrypt" Width="180px" />
                </td>
                <td class="style4">
                    <asp:Button ID="Button2" runat="server" Height="36px" onclick="Button2_Click"
                        style="font-size: large" Text="Decrypt" Width="180px" />
                </td>
                <td>
                    <asp:Button ID="Button3" runat="server" Height="36px" onclick="Button3_Click"
                        style="font-size: large" Text="Get All Connection Strings" Width="250px" />
                </td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style4">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style2" colspan="3">
                    <asp:Label ID="Label1" runat="server" style="font-size: large"></asp:Label>
                </td>
            </tr>
        </table>
   
    </div>
    </form>

Code for .cs page:

protected void Button1_Click(object sender, EventArgs e)
    {
        Configuration c = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        ConfigurationSection cs = c.Sections["appSettings"];

        if (!cs.SectionInformation.IsProtected)
        {
            cs.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
            c.Save();
            Label1.Text = "Encrypted";
        }
        else
        {
            Label1.Text = "Section is already encrypted";
        }
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        foreach (ConnectionStringSettings css in ConfigurationManager.ConnectionStrings)
        {
            Label1.Text = "Name: " + css.Name;
            Label1.Text += "<br>Connection String: " + css.ConnectionString;
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Configuration c = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        ConfigurationSection cs = c.Sections["connectionStrings"];

        if (cs.SectionInformation.IsProtected)
        {
            cs.SectionInformation.UnprotectSection();
            c.Save();
            Label1.Text = "Decrypted";
        }
        else
        {
            Label1.Text = "Section is already decrypted";
        }
    }

Sunday 17 April 2011

Joins In Sql

What is a Join in SQL Server?

Join is used  to put data from two or more tables into a single result set.

What are the types of Joins that we can have with Sql Server?

There are 4 types of joins: Inner Join, Outer Join, Cross Join , Self Join

INNER JOIN

Inner join shows matches only when they exist in both tables.Example in the below SQL there are two tables Customers and Orders and the inner join in made on Customers Customerid and Orders Customerid.So this SQL will only give you result with customers who have orders.

SELECT Customers.*, Orders.* FROM Customers INNER JOIN Orders ON Customers.CustomerID =Orders.CustomerID

LEFT OUTER JOIN:

Left join will display all records in left table of the SQL statement whether their is a matching record in right table  or not. In SQL below customers with or without orders will be displayed. Order data for customers without orders appears as NULL values.

SELECT Customers.*, Orders.* FROM Customers LEFT OUTER JOIN Orders ON Customers.CustomerID =Orders.CustomerID

RIGHT OUTER JOIN:

Right join will display all records in right table of the SQL statement whether their is matching record in left table or not. In SQL below all orders with or without matching customer records will be displayed. Customer data for orders without customers appears as NULL values.

SELECT Customers.*, Orders.* FROM Customers RIGHT OUTER JOIN Orders ON Customers.CustomerID =Orders.CustomerID

CROSS JOIN:

It will return the cartesian product of rows of both the tables. Suppose their is 3 rows in first table and 5 in second able then it will return total of 15 rows.

SELECT Customers.*, Orders.* FROM Customers CROSS JOIN Orders ON Customers.CustomerID =Orders.CustomerID

                                                                  1  3

Faq's Interview Questions

What is a view?

If we have several tables in a db and we want to view only specific columns from specific tables we can go for views. It is derived from a table but has no storage space of its own and often may be used in the same manner as a table.

What is an Index?

Index is used primarily to speed up execution and impose UNIQUENESS upon data. When queries are run against a db, an index on that db basically helps in the way the data is sorted to process the query for faster and data retrievals are much faster when we have an index.

What are the types of indexes available with SQL Server?

There are basically two types of indexes that we use with the SQL Server.

1. Clustered
2. Non-Clustered.

What is the basic difference between clustered and a non-clustered index?

Clustered index is unique for any given table and we can have only one clustered index on a table.  The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index.

Whereas in case of non-clustered index the leaf level is actually a pointer to the data in rows so we can  have as many non-clustered indexes as we can on the db.

we can have 1 clustered index and 249 non clustered index per table.

What are cursors?
Cursors help us to do an operation on a set of data that we retreive by commands such as Select columns from table.

Difference between DELETE & TRUNCATE commands?

Delete command removes particular rows from a table that we provide with a WHERE clause. Truncate will actually remove all the rows from a table.
Delete command can be rolled back whereas Truncate command cannot be rolled back.

What command do we use to rename a db?

sp_renamedb ‘oldname’ , ‘newname’

What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?

Having Clause is basically used only with the GROUP BY function in a query.
WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.

What is BCP? When do we use it?

BulkCopy is a tool used to copy huge amount of data from tables and views. But it won’t copy the structures of the same.

                                                                     1 2 3

Sunday 3 April 2011

Ado.Net FAQ's

can we connect two dataadapters to same data source using single connection at same time?

yes,we can connect two dataadapters to same datasource using single connection at same time.
There is a technology in ado.net 2.0 called MARS usinng Mars in connection string we can do it.
for eg:
cn.ConnectionString = "server=(local); database=employee; integrated security=sspi; MultipleActiveResultSets=True";

What are the two fundamental objects in ADO.NET ?

Datareader and Dataset are the two fundamental objects in ADO.NET.

What are major difference between classic ADO and ADO.NET ?

a. In classic ADO their is client and server side  cursors which is not available in ADO.NET.
b. Their is no concept of locking in Ado.net.
c. All data is persisted in XML as compared to classic ADO where data was persisted in Binary format also.

what is the difference between recordset and DataSet?


There two main basic differences between recordset and dataset :

a. In dataset we can retrive data from two databases but in recordset its not possible.
b. All representation of Dataset is using XML while recordset uses COM.
c. We cannot transmit Recordset on HTTP while Dataset can be.

What is the difference between connected and disconnected architecture?

1. In connected architecture state of connection constantly remains open but in disconnected data is fetched
   in client side.
2. Connected architecture has low scalability then disconnected architecture.
3. In connected current data is always available but in disconnected up to data data is not available.
4. Connected uses datareader whereas disconnected uses dataset.

Does disconnected architecture requires manual opening and closing of connection?

No, We dont have to do manula opening and closing in disconnected it is required in connected architecture.
In disconnected architecture datadapter does it internally.

Ado.Net basic questions

What is the namespace in which .NET has the  data functionality classes ?

Following are the namespaces provided by .NET for data management :-

System.Data: Has DataSet,DataTable, and DataRelation.

System.Data.OleDB: Has OleDbConnection, OleDbCommand, etc.

System.Data.SqlClient: SqlConnection, SqlCommand, SqlDataAdapter etc.

System.XML This Contains the basic objects required to create, read, store, write, and manipulate XML documents.


What is the use of connection object ?

They are used to connect a data to a Command object.

a. An OleDbConnection object is used with an OLE-DB provider
b. A SqlConnection object uses Tabular Data Services (TDS) with MS SQL Server

What is the use of command objects and what are the methods provided by the command object ?

Used to connect connection object with Datareader or dataset.Following are the methods provided by command object :-

a. ExecuteNonQuery :- Used for a query that does not return any rows (an UPDATE, DELETE or INSERT).Returns an Integer indicating the number of  rows affected by the query.
b. ExecuteReader :- Return a "reader" object that is connected to the resulting rowset within the database, allowing the rows to be retrieved.
c. ExecuteScalar :- Returns only a single value (effectively the first column of the first row of the resulting rowset). Any other returned column and rows are discarded.

If we are not returning any records from the database, which method is to be used?

There is a method called Execute Non Query. This method executes the Update, Delete etc. This does not return any rows but will give the number of rows affected.

Explain ExecuteNonQuery?

Executes a Transact-SQL statement against the connection and returns the number of rows affected.

What is the ExecuteScalar method?

Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

 

DataAdapter Interview questions

What is the use of dataadapter ?

These are objects that connect one or more Command objects to a Dataset object..They provide logic that gets the  data from the data store and populates the tables in the DataSet, or pushes the changes in the DataSet back into the data store.

What are basic methods of Dataadapter ?

There are three most commonly used methods of Dataadapter :

Fill :- Executes the SelectCommand to fill the DataSet object with data from the data source. Can also be used to update (refresh)
an existing table in a DataSet with changes made to the data in the original datasource if there is a primary key in the table in the DataSet.

FillSchema :- Uses the SelectCommand to extract just the schema for a table from the data source, and creates an empty table in the  DataSet object with all the corresponding constraints.

Update:- Calls the respective InsertCommand, UpdateCommand, or DeleteCommand for each inserted, updated,or deleted row in the DataSet so as to update the original data source with the changes made to the content of the DataSet. This is a little like the UpdateBatch method  provided by the ADO Recordset object, but in the DataSet it can be used to update more than one table.

DataAdapter is used in Connected or Disconnected architecture?
It is used in disconnected architecture.

Wednesday 30 March 2011

DataReader Interview Questions

Can dataReader hold data from multiple tables?

Yes, DataReader can hold data from multiple tables.

 SqlConnection con = new SqlConnection("server=sugandha;initial catalog = dotnet;uid=sa;pwd=sugandha");
        string query = "select * from Employee; select * from Employee1";
        con.Open();
        SqlCommand cmd = new SqlCommand(query, con);

       SqlDataReader dr = cmd.ExecuteReader();

        if (dr.HasRows)
        {

            dr.Read();

            GridView1.DataSource = dr;

            GridView1.DataBind();

            if (dr.NextResult())
            {

                GridView2.DataSource = dr;

                GridView2.DataBind();

            }

        }

        dr.Close();

        con.Close();
  
How can we retrieve two tables of data at a time by using DataReader?

If we pass two queries in the commandText then we get data from two tables.
It return 2 tables in DataReader.

like :
string str="Select * from a;select * from b";
cmd.CommandText=str;
dr=cmd.ExecuteReader();

What is difference between dataset and datareader ?

Following are some major differences between dataset and datareader :

1. DataReader provides forward-only and read-only access to data , while the DataSet object can hold more than one table   from the same data source as well as the relationships between them.
2. Dataset is a disconnected architecture while datareader is connected architecture.
3. Dataset can persists contents while datareader can not persist contents , they are forward only.

I want to force the DataReader to return only schema of the datastore rather than data ?

objDataReader = objCommand.ExecuteReader(CommandBehavior.SchemaOnly)

How can we force the connection object to close after my DataReader is closed ?

ExecuteReader takes a parameter called as CommandBehavior where in we can specify saying close connection automatically after the DataReader is close.
objDataReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection)

DataSet Interview Questions

What is a DataSet ?

A DataSet is an in memory representation of data loaded from any data source.

How can we load multiple tables in to Dataset?

DataSet ds=new DataSet();
SqlDataAdapter dap=new SqlDataAdapter(Select * from <tablename>,<connection1>);
dap.Fill(ds,"TableOne");
SqlDataAdapter dap1=new SqlDataAdapter(Select * from <tablename>,<connection1>);
dap1.Fill(ds,"tableTwo");


How do we update a Dataset in ADO.Net and How do we update database through Dataset?

a. Update a DataSet:

DataSet ds = new DataSet();
SqlDataAdapter adp = new SqlDataAdapter(Query,connection);
adp.fill(ds);
Again we can add/update Dataset as below
SqlDataAdapter adp1 = new SqlDataAdapter(Query1,connection);
Adp1.fill(ds);

b. Update database through DataSet:

SqlCommandBuilder cmd = new SqlCommandBuilder(adp);
foreach(DataRow dr in ds.Table[0].Rows)
{
dr[“column Name”] = “value”;
adp.Update(ds);
}


What we do with the object of ado.net dataset after using it?Can we dispose it or can we set it nothing?Is it must or not?

we use dispose

If a table contains 20000 records . In a page at each time 100 records to be displayed.
What are the steps u will take to improve performance? will you use dataset or datareader?


We should go for DataSet as DataReader doesnot allow navigation between data. Suppoose we are seeing 1500 data and we want to see previous data in DataReader it is not possible but with DataSet we can do this.

what is typed and untyped dataset?
Typed DataSet has a schema and an Untyped DataSet does not have one.
It should be noted that the Typed Datasets have more support in Visual studio.

What is a DataTable?

A DataTable is a class in .NET Framework and in simple words a DataTable object represents a table from a database.

How do you merge two datasets into the third dataset in a simple manner?

Use DataSet1.Merge (DataSet2) method to merge two datasets and copy DataSet1 to DataSet3.

How to generate XML from a dataset and vice versa?

We can use WriteXml() and ReadXml() methods of DataSet Object.

What is Dataset object?

The DataSet provides the basis for disconnected storage and manipulation of relational data. We fill it from a data store, work with it while disconnected from that data store, then reconnect and flush changes back to the data store if required.

How can we save all data from dataset ?

Dataset has “AcceptChanges” method which commits all the changes since last time “Acceptchanges” has been executed.

How can we check that some changes have been made to dataset since it was loaded ?
Twist :- How can we cancel all changes done in dataset ? , How do we get values which are changed in a dataset ?


For tracking down changes Dataset has two methods which comes as rescue “GetChanges “and “HasChanges”.

GetChanges Return’s dataset which are changed since it was loaded or since Acceptchanges was executed.
HasChanges This property indicate’s has any change’s been made since the dataset was loaded or
acceptchanges method was executed.

 If  we want to revert or abandon all change’s since the dataset was loaded use “RejectChanges”.

How can we add/remove row’s in “DataTable” object of “DataSet” ?

”DataTable” has “DataRowCollection” object which has all rows in a “DataTable” object.
Following are the methods provided by “DataRowCollection” object :-

Add: Add’s a new row in DataTable
Remove: Remove’s a “DataRow” object from “DataTable”
RemoveAt: Remove’s a “DataRow” object from “DataTable” depending on index position of  the “DataTable”.

What’s difference between DataSet.Clone and DataSet.Copy ?

Clone: - It only copies structure, does not copy data. Copy: - Copies both structure and data.

Saturday 26 March 2011

Delegates and events Interview Questions

What’s a delegate?

A delegate object encapsulates a reference to a method.

What are the different types of delegates?

Two types:

1. Unicast delegate: Delegate which is used to call a single method is called unicast delegate.
2. Multicast delegate: Delegate which is used to call a more than one method is called multicast delegate.


Do events have return type ?

No events do not have return type.

Can event’s have access modifiers ?

Event’s are always public as they are meant to serve every one registering to it.But we can use access modifiers in events. we can have events with protected keyword which will be accessible only to inherited classes. We can have private events only for object in that class.

Can we have shared events ?

Yes we can have shared event’s note only shared methods can raise shared events.

What’s difference between delegate and events?

1. Actually events use delegates in bottom. But they add an extra layer on the delegates, thus forming the publisher and subscriber model.
2. As delegates are function to pointers they can move across any clients. So any of  the clients can add or remove events ,  which can be pretty confusing. But events give the extra protection by adding the layer and making it a publisher and subscriber model.

What is an Asynchronous delegate?

Delegates used to invoke method that takes long time to execute.

How to create events for a control? What are custom events?


Declare a public delegate and set of events to listen from.
public delegate void CarEventHandler(string msg);
public event CarEventHandler AboutToBlow;
public event CarEventHandler BlewUp

Steps to use delegate?

1. Create delegate: delegate returntype nameofdelegate(parameter passed to method);
2. Create instance of delegate: delname objname = new delname(classobj.nameofmethod);
3. Invoke delegate: datatype parameter of method = objname("value to pass ");

What is invocationlist?

Multicast delegate contains internal lis tof delegate. This list is called invocationlist.

** += and -= operators are use dto add and remove delegates from invocationlist.

Reflection Interview Questions

What is reflection?

All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection.

Which namespace is used in Reflection?
System.Reflection

Which namespace is used to built new types at runtime?


System.Reflection.Emit

Advantages of Reflection?

1. Used to access attribute sin programs metadata.
2. Examine and instantiate types in an assembly.
3. To perform late binding, accessing methods on the types created at runtime.

What is attributes? Types of attributes?

Attributes are the declarative tags that convey information at runtime.
Some predefind attributes are Serializable, Deserializable

Types:

1. Standard: Predefined attributes in .Net framework

eg.

 class attributeparamsdemo
    {
        [DllImport("user32.DLL", EntryPoint = "MessageBox")]
        static extern int MessageDialog(int hwnd, string msg, string caption, int msgtype);
        static void Main(string[] args)
        {
            MessageDialog(0, "MessageDialog called !", "DllImport demo", 0);

        }
    }
This will display the messagebox as output with the message "MessageDialog called ! " , caption  "DllImport demo" and
Ok button as msgtype 0 contains ok button.

2. Custom: Attributes defined by user

eg.

namespace demo_customattribute
{
    [AttributeUsage(AttributeTargets.All,Inherited = false,AllowMultiple = true)]
    public class bookattribute : System.Attribute
    {
        private string name;

        public string version;

        public bookattribute(string str)
        {
            name = str;
            version = "1.5";
        }
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }

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

           book b = new book();
           Type t = b.GetType();
           Attribute[] ats = Attribute.GetCustomAttributes(t);
           foreach (Attribute a in ats)
           {
               if (a is bookattribute)
               {
                   bookattribute author = (bookattribute)a;
                   Console.WriteLine("AuthorName = " + author.Name);
                   Console.WriteLine("Version = " + author.version.ToString());
               }
           }
           Console.ReadLine();
        }
    }
        [bookattribute("balaguruswamy", version = "1.1")]
        [bookattribute("ABC", version = "1.2"), bookattribute("yashwant")]
        public class book
        {
            private string bkname;

            public string Bkname
            {
                get { return bkname; }
                set { bkname = value; }
            }
        }
               
    }
[AttributeUsage(AttributeTargets.All,Inherited = false,AllowMultiple = true)]
<b> AttributeTargets </b>indicates that this attribute can be applied to all program elements.
<b>Inherited</b> indicates whether the attribute can be inherited by classes that are derived from the classes to which attribute is applied.
<b>AllowMultiple</b>indicates whether multiple instances of attribute can exists on an element.




Serialization Interview Questions

What is serialization and Deserialization?
Serialization is the process of converting an object into a stream of bytes.
Deserialization is the opposite process i.e. it creats an object from a stream of bytes.

Serialization /Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).

What are the types of Serialization?

There are 4 types of srailization.

1. Binary Serialization: It writes the contents of an object into binary form to a file.
2. SOAP Serialization: It writes the contents of an object into platform-agnostic format.
3. XML Serialization: It writes the contents of an object into a XML file.
4. Custom Serialization: In some cases, the default serialization techniques provided by .NET may not be sufficient in real life.  This is when we require implementing  custom serialization.   It is possible to implement custom serialization in .NET by implementing the ISerializable interface.  This interface allows an object to take control of its own serialization and de-serialization process.

Does the .NET Framework have in-built support for serialization?

There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.

Why is XmlSerializer so slow?
There is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize an object of a given type in an application, there is a significant delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a poor choice for loading configuration settings during startup of a GUI application.

Why do we get errors when we try to serialize a Hashtable?

XmlSerializer will refuse to serialize instances of any class that implements IDictionary,
e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.

what are the namespaces we use to implement serialization?

using System.Xml.Serialization; -> for xml
using System.Runtime.Serialization.Formatters.Binary; -> for binary
using System.Runtime.Serialization.Formatters.Soap; -> for soap



Wednesday 23 March 2011

Static Keyword related Questions

What is a Static class? What are its features?

Static class is a class which can be accessed without creating an instance of the class.
Important Features:
a. Static class only contains static members.
b. Static class need not to be instantiated.
c. Static classes are sealed by default and therefore cannot be inherited.

What is sealed class? What are its features?

Sealed classes are those classes which can not be inherited and thus any sealed class member can not be derived in any other class.
A sealed class cannot also be an abstract class.
In C# structs are implicitly sealed; therefore, they cannot be inherited.

What is a life span of a static variable?

A static variable’s life span is till the class is in memory.

Why main function is static?
To ensure there is only one entry point to the application.

What is static member?

static members are the members that can be called directly from the class name, it doesnt require the object of the class.

What is static constructor?

When constructors are used to set the value of a type’s data at the time of construction, if we want the value of such static
data is to be preserved regardless of how many objects of the type are created, we have to define the constructor with static keyword.


Can you declare the override method static while the original method is non-static?

No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

Polymorphism Interview questions

What is Polymorphism?

Ability to provide different implementation based on different number/type of parameters that
are called by the same name.


public class DrawingShape
{
public virtual void Draw()
{
Console.WriteLine("Drawing shapes.");
}
}
public class Square : DrawingShape
{
public override void Draw()
{
Console.WriteLine("Drawing square.");
}
}
public class rectangle : DrawingShape
{
public override void Draw()
{
Console.WriteLine("Drawing rectangle.");
}
}

public class baseclass
{
public static void Main()
{
DrawingShape[] ds = new Drawingshape[2];

ds[0] = new Square();
ds[1] = new rectangle();


foreach (DrawingShape s in ds)
{
ds.Draw();
}
}
}

In this we have drawingshape class having virtual method Draw() whic his overriden in the Square and rectangle class.


In which cases you use override?

If the base class member is declared as virtual or abstract then to override these members in derived class
we use override leyword in derived class.

Can you override private virtual methods?

No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access

What does the keyword virtual mean in the method definition?

It means the method can be over-ridden in derived class.

Can you declare the override method static while the original method is non-static?

No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

How a base class method is hidden?

We can Hide a base class method by declaring a method in derived class with keyword new.

What is the difference between virtual and abstract method?

Abstract methods doesnot provide implementation of method whereas virtual method provides the implementation.

Interface Interview Questions

What is an Interface?

An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body.

Important point:

a. By default it is public. We cannot specify any access specifier in interface.
b. It doesnot contain implementation of method.
[code]
using System;
namespace Interfaces
{
interface Icustdetails
{
void GetName();
void GetID();
}
public class Demo : Icustdetails
{
public void GetName()
{
Console.WriteLine("Gives the name");
}

public void GetID()
{
Console.WriteLine("gives the ID");
}

public static void Main()
{
Demo obj_demo = new Demo();
demo_obj.GetName();
demo_obj.GetID();
}
}
}

[/code]
In this example we have declared an interface ICustdetails with the abstract methods GetName and GetID. Now their is a class demo
which is inherited from Icustdetails so,it has to provide the implementation of these methods. If it doesn't provide the implementation
then compile time error is thrown.

What do you mean by "Explicitly Implemeting an Interface"?

If a class is implementing the inherited interface member by prefixing the name of the interface, then the class is "Explicitly Implemeting an Interface member". 

Can we declare private methods inside an Interface?

No, they all must be public, you are not allowed to specify any accessibility, its public by default.

Can you create an instance of an interface?
No, you cannot create an instance of an interface.

A class inherits from 2 interfaces and both the interfaces have the same method name as shown below.
How should the class implement the GetName method for both IOrderdetails and ICustdetails interface?

[code]
  interface ICustdetails
    {
         void GetName(int n);
    }
    interface IOrderdetails
    {
        void GetName(int n);
    }
    class Orders : ICustdetails, IOrderdetails
    {
       //how we implement method of both interface
    }
[/code]

To implement the GetName() method we use the fully qualified name as shown below.
To call the respective interface GetMethod method type cast the Orders object to the respective interface and then call the  method.
[code]
 interface ICustdetails
    {
         void GetName(int n);
    }
    interface IOrderdetails
    {
        void GetName(int n);
    }
    class Orders : ICustdetails, IOrderdetails
    {
        void ICustdetails.GetName(int n)
        {
           
        Console.WriteLine("These are customer details");
          
        }
        void IOrderdetails.GetName(int n)
        {           
            Console.WriteLine("These are order details");
          
        }
    }
 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter customer number");
            int n = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter order number");
            int o = int.Parse(Console.ReadLine());
            Orders obj = new Orders();
            ICustdetails cd = obj;
            IOrderdetails od = obj;
            cd.GetName(n);
            od.GetName(o);
            Console.ReadLine();

        }
    }

[/code]

If a class inherits an interface, what are the options available for that class?
Their are 2 options available in this case:

a. A class has to implement all the members of that interface.

namespace demo_interface
{
interface Bank
{
void savingaccount();
Void currentaccount();
}

class bankdetail : Bank
{
public void savingaccount()
{
Console.WriteLine("savingaccount Method");
}
public void currentaccount()
{
Console.WriteLine("currentaccount Method");
}
}
}

Option 2: class must use the abstract keyword

namespace demo_interface
{
interface Bank
{
void savingaccount();
Void currentaccount();
}


abstract class bankdetail : Bank
{
abstract public void savingaccount();
abstract public void savingaccount();
public void bankdetailmethod()
{
Console.WriteLine("Bankdetail Method");
}
}
}



Inheritance Interview Questions

What is Inheritance?

Inheritanc eprovides reusability and extensibility features.
Reusability:  Allow us to use a a component,class and even methods in different applications.
Extensability: Means to extend a module as a new need arises.

Does C# support multiple class inheritance?
No, C# supports doesn't support multiple class inheritance.We can use interface in place of that.

Do structs support inheritance?
No, structs do not support inheritance, but they can implement interface.

Is the following code legal?
class Employee
{
//code for Employee class
}
class Department
{
//code for Department claSS
}
class Clerk : Employee, Department
{
}


NO, Because c# doesnot support multiple inheritance so one class cannot inherit more then one class. Though if Employee and Department are interfaces rather than class then it is possible.

What will be the output of the following code? (very important question asked in almost every interviews)
public class Bank
{
public Bank()
{
Console.WriteLine("I am a bank class");
}
}
public class account : Bank
{
public account()
{
Console.WriteLine("I am a account class");
}
static void Main()
{
account a = new account();
}

}
Output:
I am a bank class
I am a account class

Base class constructor is always called before the child class.


Array Interview questions

What is an Array?
An array is a type of data structure that is used to store variables of same data type.

What are the different types of arrays?
1. Single-Dimensional

int[] arrayname = new int[size of array];

2. Multidimensional: int[ , ] arrayname = new int[2,3];

3. Jagged : It is array of array.
int[][] arrayname = new int[2][];


Arrays are value types?yes or no

no,Arrays are reference types.

What is the base class for Array types?
System.Array



Tuesday 22 March 2011

Collection Interview questions

what is Collection?

It is the set of of similar typed objects grouped together.

 Give examples of Generic and non-generic collections?

Non-Generic collection comes under System.Collections namespace.
eg: Arraylist, queue, stack, Sorted list, Hashtable etc

Generic collection comes under System.Collections.Generic namespace.
eg:generic list, generic queue, generic stack etc

What is an ArrayList?

The ArrayList object is a collection of items containing a single data type values.

What is a HashTable?

The Hashtable object contains items in key/value pairs. The keys are used as indexes, and very quick
searches can be made for values by searching through their keys.

What is SortedList?

The SortedList object contains items in key/value pairs. A SortedList object automatically sorts items in alphabetic or numeric order.

What’s the .NET collection class that allows an element to be accessed using a unique key?

HashTable.

What class is underneath the SortedList class?

A sorted HashTable.

Where are all .NET  Collection classes located ?

System.Collection namespace has all the collection classes available in .NET.

What’s difference between HashTable and ArrayList ?

You can access array using  INDEX value of  array , but  how many times you know the
real value of index.Hashtable provides way of accessing the index using a user identified KEY value , thus removing the INDEX problem.

What are queues and stacks ?
Queue is for  first-in, first-out (FIFO) structures. Stack  is for last-in, first-out (LIFO) structures.

What is the difference between array and arraylist?

1. Size of array is always fixed and should be defined at the time of instantiation of array whereas arraylist size grows dynamically.
2. In array we can store elements of single type of data type whereas in arraylist we can store elements of data types.

Boxing and unboxing interview questions

What do you mean by boxing and un-boxing?
C# provides us with Value types and Reference Types. Value Types are stored on the stack and Reference types
are stored on the heap. The conversion of value type to reference type is known as boxing and converting
reference type back to the value type is known as un-boxing.
e.g.
int x = 100;

object o = x ;  //  Implicit boxing
object o = (object) x; // Explicit Boxing

x = o; // Implicit Un-Boxing
x = (int)o; // Explicit Un-Boxing


What happens during the process of boxing?
Boxing is used to store value types data types in the garbage-collected heap.
Boxing is an implicit conversion of a value type to the type object or to any interface
type implemented by this value type.During this an object is created on the heap and
value is copied over their.



Access specifiers interview questions

What are the access-specifiers available in c#?
There are 5 access specifiers.
Private, Protected, Public, Internal, Protected Internal.


Are private class-level variables inherited?
Yes, but they are not accessible.

Explain about Protected and protected internal, “internal” access-specifier?
protected - Access is limited to the containing class or types derived from the containing class.

internal - Access is limited to the current assembly.

protected internal - Access is limited to the current assembly or types derived from the containing class.

When you inherit a protected class-level variable, who is it available to?
Classes in the same namespace.

Explain public and private access specifier?
public: can be accessed anywhere

private: can be accessed in the class in which it is declared.

Abstract and sealed keyword interview questions

What is an Abstract class?

An abstract class is a special kind of class that cannot be instantiated. It normally contains one or more abstract methods
or abstract properties. It provides body to a class.


What is an Sealed class?

Sealed class is a class which cannot be inherited.

<b>Can a sealed class be used as a base class?</b>
No, sealed class cannot be used as a base class. A compile time error will be generated.


When do you absolutely have to declare a class as abstract?

a. If a class contains one or more abstract method.
b. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.

 Can we declare a class as sealed as well as abstract?

No, as it is against definition.A sealed class cannot be inherited but to use abstract class its necessary to inherit that class.

Can we declare a method as sealed?

In C# a method can't be declared as sealed. However when we override a method in a derived class,
we can declare the overridden method as sealed. By declaring it as sealed, we can avoid further overriding of this method.
E.g.

using System;
class MyClass1
{
   public int x;
   public int y;
   public virtual void Method()
   {
    Console.WriteLine("virtual method"); 
   }
}
class MyClass : MyClass1
{
   public override sealed void Method() 
  {
    Console.WriteLine("sealed method");  
  }   
}
class MainClass
{   public static void Main() 
    {
      MyClass1 mC = new MyClass();
      mC.x = 110;
      mC.y = 150;
      Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
      mC.Method();  
    }
}

Wednesday 16 March 2011

Data-types in C#

Data types in c# is divided into how many parts?

There are 2 types of Data types in c#:
a. Value type
b. Reference type

Examples of Value type data type?

Integer
Enumeration
Structure
characters

Example of Reference type data types?

Object
Strings
Classes
Arrays
Interfaces

What are Value types and Reference types ?

Value types directly contain their data are either allocated on the stack or allocated in-line in a structure.
Reference types store  a reference to the value's memory address, and are allocated on the heap.


Value and Reference type datatypes are further classified into?

a. User Defined
b. Pre Defined

Eg of user defined data types are:
Enum
Struct
Classes
Arrays
Interface

Eg of Pre defined data types are:
Integer
Characters
Object
Strings

Explain the difference between value types and reference types?

Value Type:
a.    Stores the data.
b.    The value of value types is stored on the managed stack.
c.    One variable can have just one value.
d.    They are lighter objects.
Reference Type:
a.    Stores the reference to the data.
b.    A reference type is allocated on the heap.
c.    several variables can reference the same data
d.    They are heavier objects.

Using ref and out keywords in c#

what is the use of ref and out keyword in C#?

When we pass value of value type or implicit data type to a method we actually pass
a copy of data. so any changes or modification done in the method in data is not reflected
back.

Consider an example:

class refoutsample
{
    public static void Main(string args[])
    {
        int a =3;
        add(a);
        Console.WriteLine("Value of a is" + a);
    }
    public static void add(int i)
    {
        i++;
    }
}

Output of this program is "value of a is 3" though the value is incremented by 1 in the method.
so to avoid this ref or out keyword is used.

P{rogram using ref keyword:

class refoutsample
{
    public static void Main(string args[])
    {
        int a =3;
        add(ref a);
        Console.WriteLine("Value of a is" + a);
    }
    public static void add(ref int i)
    {
        i++;
    }
}

now the output is 4.

Diffrence between ref and out keyword?

In case of ref, value must be initialized before passing it to method whereas in case of out keyword its not necessary.


    

Tuesday 15 March 2011

Exception Interview Questions

What’s difference between System exceptions and Application exceptions?

a. All exception derives from Exception Base class i.e. System.Exception class. Exceptions can be generated
programmatically or can be generated by system.
Application Exception serves as the base class for all application-specific exception classes. It derives from
Exception but does not provide any extended functionality. You should derive your custom application exceptions
from Application Exception.

b. Application exception are used when we want to define user defined exception. While system exception are all
which are defined by .NET.

Will the finally block get executed if an exception has not occurred?
Yes.

What’s the C# syntax to catch any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

Can multiple catch blocks be executed for a single try statement?

No. Once the proper catch block processed, control is transferred to the finally block .

If we write a goto  or a return statement in try and catch block will the finally block execute ?

The code in the finally always runs even if  there are statements like goto or a return statements.


Assembly interview Questions

What is Assembly?
Assembly is the building blocks of the .NET framework. They are the logical grouping of the functionality in a physical file.

What are the different components of Assembly?

Following are the main components of assembly:

1. Manifest : It contains assembly information like Assembly version, security, reference to other assemblies.
2. Type Metadata : Provides information about types defined in assembly like classes, interface, methods, properties.
3. MSIL Code : It is CPU independent set of instruction that can be efficiently converted into native code.
4. Resources  : Resources like .jpg and .bmp files are stored.

Which tool is used to deploy an assembly, so as the assembly is available to all the application?

The GacUtil.exe is the tool, which allows us to add any assembly to the windows GAC (Global Assembly Catche).

What is Namespace?

It is logical grouping of all the classes and methods inside it.

What is Difference between NameSpace and Assembly?

a. Assembly is physical grouping of  logical units whereas Namespace is the logically grouping of classes.
b. Namespace can span multiple assembly.


Where the version information of assembly is stored?

Version information is stored in assembly in manifest.

Is versioning applicable to private assemblies?

No, Versioning concept is only applicable to global assembly cache (GAC) as private assembly lie in there individual folders.

What is concept of strong names ? Twist :- How do we generate strong names  or what is the process of generating strong names?

Strong Name is only needed when  we need to deploy assembly in GAC.Strong Names helps GAC to differentiate between two versions.Strong names use public key cryptography (PKC) to ensure that no one can spoof it.PKC use public key and private key concept.

Following are the step to generate a strong name and sign a assembly :-
a. Go to “Visual Studio Command Prompt”.
b. After you are in command prompt type sn.exe -k “c:\test.snk”.
c. Add the strong name in AssemblyInfo.cs page of the project.
  [assembly: AssemblyKeyFile(@"e:\mykey.snk")]
d. Add the assembly to Cache: in command prompt  type:
gacutil/i- path of assembly

path of assembly = path of the dll file from the bin/debug folder of the project
What is the satellite assemblies?

In a multilingual or multi-cultural application, the localized assemblies, which contain language specific instructions that modify the core application, are kept separately and they are called satellite assemblies.