SQL interview Question Answer- Part -  2

Question 16. What is an Index?

Answer : Indexes are used to retrieval data more quickly from database. An index contains keys built from one or more columns in the table or view. These keys are stored in a structure (B-tree) that enables SQL Server to find the row or rows associated with the key values quickly and efficiently.

Question 17. What are the types of Indexes available in SQL Server?

Answer: There are two types of indexes available in SQL Server.

  1.     Clustered Index
  2.     Non-Clustered Index
Question 18. What is Clustered index and how many clustered indexes there can be in one table?
Answer: A clustered index is special type if index that reorder the way records in the table are physically stored. Only one clustered index is possible in one table.

Question 19. Why only one clustered index per table should be created in SQL Server? 
Answer. Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be stored in only one order.

Question 20. Can we create a clustered index on multiple columns in SQL Server?
Answer. Yes we can create clustered index on multiple columns in Sql Server but there is limitation only we can take max 16 column.

Question 21. Is it necessary to declare column primary or unique key for creating clustered index.
Answer. Answer is NOT. but it is recommended to declare the clustered index key column or combination of columns as unique to improve the queries performance. Otherwise, SQL Server will automatically add a uniqueifier (this four bite value is not visible to user) column to enforce the clustered index key uniqueness.

Indexes are automatically created when PRIMARY KEY and UNIQUE constraints are defined on table columns. For example, when you create a table with a UNIQUE constraint, Database Engine automatically creates a nonclustered index. If you configure a PRIMARY KEY, Database Engine automatically creates a clustered index, unless a clustered index already exists. When you try to enforce a PRIMARY KEY constraint on an existing table and a clustered index already exists on that table, SQL Server enforces the primary key using a nonclustered index. later we can drop indexes.

Question 22. What is ideal characteristics of clustered index key.
Answer.
  1. Short : as short as possible, in terms of the number of bytes it stores.
  2. Static : ideally, never updated.
  3. Unique: to avoid the need for SQL Server to add a 'uniqueifier' to duplicate key values.
  4. Accessed Frequently.
  5. Used in Order By Clause
Question 23. Why it is not recommended to use GUID and Character column as clustered index key.
Answer. There are two main reasons why we don’t do this. First is data size. The SQL Server UNIQUEIDENTIFIER data type is 16 bytes convertible to the char(36) data type while BIGINT is only 8 bytes and INT is only 4 bytes.
Second one the most damaging thing that GUIDs cause is severe index fragmentation.  To understand this, we need to review how clustered indexes work in SQL Server.  The clustered index for a table or view determines the physical order of the rows on a data page.  So we like to make sure we are clustering on a value that is continuously increasing, like an integer generated by the IDENTITY property or via a sequence.  By doing this we ensure that new data always gets added to the end of the table and pages are filled sequentially.  The very definition of a GUID is that it is not sequential.  So every time a new row is inserted, SQL Server has to move things around to make room for it in the correct place.  Not only is this an expensive operation, but a GUID will never be accessed in a range so we lose that benefit of a good clustering key as well.  If a page is full and we need to insert a row into it, we get a Page Split, meaning SQL Server has to allocate a new page, move the rows that spill off the original page to it, and then add our new row to the original page.

Question 24.  What is Non Clustered Index.
Answer. First of the non-clustered index does not sort the data rows physically as clustered index does.
It creates a separate key-value structure from the table data where the key contains the column values 
(on which a non-clustered index is declared) and each value contains a pointer to the data row that 
contains the actual value, similar to textbook indexing.

Question 25. How many Non Clustered index can be created?
Answer. For Sql Server  2005 it is 249 and Onwards Sql Server 2008  it is 999 Non Clustered index can be created in a single table.

Question 26. What is advantages and disadvantages of indexes?
Answer. Advantages.
  1. Quickly returns a large range of data.
  2. Physical ordering of the data of the column.
  3. A Index improve the performance of data retrieval.
Disadvantages
  1. Frequently updated data increases the overhead of rearranging the B-tree.
  2. Indexes have a poor consequence on the performance of the data modification statements like INSERT, UPDATE, or DELETE. Every time a query asks to modify the data in the table, the database updates itself with the new index where the data changes. 
  3.  Only one Clustered Index per table.
  4.  If the size of the table is small then it is not effective.
Question 27. Why do we need Indexes in SQL Server?
Answer. In above answer we can consider all advantages.

Question 28. When should we create indexes on a table?
Answer. We can create an index in columns that are common in WHERE, ORDER BY and GROUP BY clauses. You may consider adding an index in columns that are used to relate other tables (through a JOIN, for example).

Question29. What is difference between cluster and Non-cluster index?.
Answer. 
  1. Clustered index is faster while Non-clustered index is slower.
  2. Clustered  index has the natural ability to store data on the disk while Non-clustered index does not have the natural strength to store data on the disk.
  3. Clustered index requires less memory for operations while Non-Clustered index requires more memory for operations.
  4. A table can have only one clustered index. while we can have have multiple non-clustered index in a table.
  5. In Clustered index leaf nodes are actual data itself while In Non-Clustered index leaf nodes are not the actual data itself rather they only contains included columns.
Question 30. Which Index is faster, Clustered or Non Clustered and why?
Answer. Clustered Index is slightly faster than the Non-Clustered Index. This is because when a Non Clustered Index is used there is an extra look up from the Non-Clustered Index to the table, to fetch the actual rows.

Question 31. What is difference between rebuild index and organize index?
Answer. 
Index Rebuild : This process drops the existing Index and Recreates the index.
Index Reorganize : This process physically reorganizes the leaf nodes of the index.
Recommendation: Index should be rebuild when index fragmentation is great than 40%.Index should be reorganized when index fragmentation is between 10% to 40%. Index rebuilding process uses more CPU and it locks the database resources. SQL Server development version and Enterprise version has option ONLINE, which can be turned on when Index is rebuilt. ONLINE option will keep index available during the rebuilding.
 
Question 32. How can we improve the performance of poor-performing SQL queries?
Answer. We can improve the performance of poor-performing SQL queries in the following ways:
  1. Using indexes properly
  2. Creating primary and foreign keys.
  3. Not making table scans.
  4. Avoiding using cursors.
  5. Using partitioned views.
Question 33.  How can you improve the performance of stored procedures in the SQL server?
Answer. 
  1. Using SET NOCOUNT ON messages, information messages can be prevented from the result set. It will reduce network traffic and increase operational performance.
  2. When fully qualified procedure name, the SQL server finds the compiled plan quickly, which in turn increases the performance
  3. Specifying stored procedures as 'sp_procedurename' must be avoided because the SQL server will search the master database first if it finds ‘sp’ in the procedure name. It would decrease the performance and yield error results at times.
  4. Transactions need to be shorter so that deadlocks and blocking can be prevented.

Pie Chart in Angular 13 with d3

    Creating Pie chart with in angular 13 with d3 libraries.

    Lets  get  started : 

    If you don't installed angular CLI please installed it  

    npm install -g @angular/cli 

    Create an angular application with name 'PieChartDemo'

    ng new PieChartDemo 

     Now navigate to Project where Project is resides like

     cd PieChartDemo 

    Now installed the d3 libraries with    

    npm install d3 &&  npm install @types/d3 --save-dev 

    Let generate commpnent with name 'PieChart'

    ng g c PieChart 

Below is pie-chart.component.ts


import { Component, OnInit } from '@angular/core';
import * as d3 from 'd3';
@Component({
    templateUrl : './pie-chart.component.html',
    styleUrls:['./pie-chart.component.css']
})
export class PieChartComponent implements OnInit
{     
    private data = [
      {"Students": "First Div", "NoOfStudents": "50"},
      {"Students": "Second Div","NoOfStudents": "30"},
      {"Students": "Thirs Div","NoOfStudents": "15"},
      {"Students": "Fail", "NoOfStudents": "5"}    
    ];
    private svg :any;
    private margin = 50;
    private width = 750;
    private height = 600;
    private radius = Math.min(this.width, this.height) / 2 - this.margin;
    private colors : any;  
    constructor(){}      
     
  ngOnInit(){
        this.createSvg();
        this.createColors();
        this.drawChart();
  }

  private createSvg(): void {
    this.svg = d3.select("figure#pieChart")
      .append("svg")
      .attr("width", this.width)
      .attr("height", this.height)
      .append("g")
      .attr(
        "transform",
        "translate(" + this.width / 2 + "," + this.height / 2 + ")"
      );
  }
  private createColors(): void {
    this.colors = d3.scaleOrdinal()
      .domain(this.data.map(d => d.NoOfStudents.toString()))
      .range(["#28a745", "#6f42c1", "#e83e8c", "#dc3545"]);
  }
  private drawChart(): void {
    // Compute the position of each group on the pie:
    const pie = d3.pie<any>().value((d: any) => Number(d.NoOfStudents));
    // Build the pie chart
    this.svg
      .selectAll('pieces')
      .data(pie(this.data))
      .enter()
      .append('path')
      .attr('d', d3.arc()
        .innerRadius(0)
        .outerRadius(this.radius)
      )
      .attr('fill', (d: any, i: any) => (this.colors(i)))
      .attr("stroke", "#121926")
      .style("stroke-width", "1px");
    // Add labels
    const labelLocation = d3.arc()
      .innerRadius(100)
      .outerRadius(this.radius);
    this.svg
      .selectAll('pieces')
      .data(pie(this.data))
      .enter()
      .append('text')
      .text((d: any) => d.data.Students +
     ' ' + d.data.NoOfStudents.toString() + '%')
      .attr("transform", (d: any) => "translate(" +
                    labelLocation.centroid(d) + ")")
      .style("text-anchor", "middle")
      .style("font-size", 15);
  }
}

and pie-chart.component.html


<h3>Pie Chart</h3>
<figure id="pieChart"></figure>


Now run application and naviagte to pieChart component 

ng s -o 








SQL Interview Question Answer

                                    SQL interview Question Answer Part - 1 

Question 1.  What are the differences between Stored procedures and functions?

  1.  A function has a return type and must return a value while procedure does not have a return type but it may or not return values.
  2. You cannot use a function with data manipulation queries. Only Select queries are allowed in functions while in procedure you can use DML queries such as insert, delete, update, select etc.
  3.  A function does not allow output parameters while procedure allows  output parameters.
  4. You cannot manage transactions inside a function while you can manage transactions inside a procedure.
  5. You cannot call stored procedures from a function while you can call a function from a stored procedure.
  6. You can call a function using a select statement while you cannot call a procedure using select statements.
  7. Function does not have execution plan while procedure use execution plan.
  8. Function does not use default parameter while procedure use default parameter.
  9. Function can call through SQL query while procedure does not.
  10. Function doesn’t support try-catch blocks while procedure supports try-catch blocks.
  11. Function can not run dynamic SQL which are dynamically build in.
  12. Temporary Tables can not be used in function where as we can use in store Procedure.
  13. function does not support error handling, RAISEERROR or @@ERROR are not allowed.

Question 2. Why use functions instead of stored procedure in Sql or What is advantages of function.

Answer.  Lot of advantages of procedure over function, we are generally used procedure since it has all functionality like transaction, try-catch, out parameter, execution plan but only by using store procedure you are not able to use select operation, hence when you required to reusability of code and cross apply you need function. 

Question 2. Any disadvantages of store Procedure?

Answer. Above answer also we can consider disadvantages of store procedure and also Version control is not supported by the stored procedure. debugging stored procedures will either be very difficult or not possible.

Question3. What is disadvantages of function?

Answer. Take reference answer one, you can consider what  function not allowed.

Question 3. What is nesting Stored Procedures and what level it can be nested.

Answer. Stored procedures are nested when one stored procedure calls another 

You can nest stored procedures and managed code references up to 32 levels.

https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms190607(v=sql.105)?redirectedfrom=MSDN

Although the nesting limit is 32 levels, SQL Server has no limit on the number of stored procedures that can be invoked from a given stored procedure, provided that the subordinate stored procedures do not invoke other subordinate stored procedures and the maximum nesting level is never exceeded.

Question 4. What is view in SQL and why you use view?

Answer. A view is a virtual table whose contents are defined by a query.

a view does not exist as a stored set of data values in a database. The rows and columns of data come from tables referenced in the query defining the view and are produced dynamically when the view is referenced

The main purpose of a view in SQL is, to combine data from multiple sources in a useful way without having to create yet another database table to store that data. The multiple sources can include tables and view from other database servers.

Limiting the visibility of columns(not allow all column due to security reason), rows to just those pertinent to a task

For security purposes to prevent direct access to database tables.

Grant permission to user for specific role like only View , delete , edit etc.

Question 5. What are the differences between a table and a view?

When compared with a table we have the following differences between a table and view.

  • The table is physical and the view is logical.
  • A table is an independent object while view is a dependent object that is a view depends on a table or tables from which it is dynamically loading the data.
  • When a new table is created from an existing table the new and old tables are independent themselves that is the changes of one table will not be reflected into the other table whereas if a view is created based on a table any changes that are performed on the table reflects into the view and any changes performed on the view reflected in the table also. 
Question 6. What are the limitations of a View?
  • In view you cannot pass parameters.
  • Rules and Defaults cannot be associated with views.
  • The ORDER BY clause is invalid in views unless TOP or FOR XML is specified.
  • Views cannot be based on temporary tables 

Question 7. How many types of views are there in SQL Server?

Answer. There are two type of view in SQL server.

  1. Simple view and Updatable views
  2. Complex view and non-updatable views.
Question 8. What are the differences between Simple and Complex View in SQL?

  1. Simple view is created from only one table while complex view is created from more than one tables.
  2. In Simple view we cannot use group functions like MAX(), COUNT(), etc. while in complex view we can use group functions.
  3. DML(data manipulation language like delete, update, insert) operations could be performed through a simple view. while DML operations could not always be performed through a complex view.
  4. INSERT, DELETE and UPDATE are directly possible on a simple view. We cannot apply INSERT, DELETE and UPDATE on complex view directly.
  5. In simple view does not include NOT NULL columns from base tables. while NOT NULL columns that are not selected by simple view can be included in complex view.

Question 9. Can we drop a table that views dependent on it?

Answer. Yes, we can drop a table even if any dependent views are associated with it. but the views that are associated with it will not be dropped. They will still execute in the database only with the status as inactive object and all those views become active and start functioning provided the table is recreated.

Question 10. Can we create a view based on other views?

Answer. Yes, we can create a view based on other views. Usually, we create views based on tables, but it is also possible to create views based on views.

Question 11. Can we update the views?

Answer. Yes, views can be updated. However, updating a view that is based on multiple tables, may not update the underlying tables correctly. To correctly update a view that is based on multiple tables we can make use “Instead OF triggers” in SQL Server.

Question 12. How can view be used to provide security layer for your app?  

Row Level Security: For example, I want an end-user, to have access only to IT Department employees. If I grant him access to the underlying tblEmployees and tblDepartments tables, he will be able to see, every department employee. To achieve this, I can create a view, which returns only IT Department employees, and grants the user access to the view and not to the underlying table.

Column Level Security: Salary is confidential information and I want to prevent access to that column. To achieve this, we can create a view, which excludes the Salary column, and then grant the end-user access to these views rather than the base tables.

Question 13. What’s the difference between CHAR and VARCHAR?

Answer. CHAR is a fixed length string data type, so any remaining space in the field is padded with blanks. CHAR takes up 1 byte per character. So, a CHAR(100) field (or variable) takes up 100 bytes on disk, regardless of the string data it holds.

VARCHAR is a variable length string data type, so it holds only the characters you assign to it. VARCHAR takes up 1 byte per character, + 2 bytes to hold length information.  For example, if you set a VARCHAR(100) data type = ‘Jen’, then it would take up 3 bytes (for J, E, and N) plus 2 bytes, or 5 bytes in all.

Question 14. When should we use CHAR instead of VARCHAR?

Answer. VARCHAR only costs two “extra” bytes, when compared to CHAR.  It’s only in rare cases where using CHAR will actually save you space and effort. Examples of those cases:

  1. CHAR(2) for state abbreviation.  If your business rules say that the State column will ALWAYS be two characters long, then use CHAR(2).
  2. Fixed length product codes (e.g., CHAR(8) for product codes like ‘004-3228’). Just like the state; if you have a field, like product code, that is ALWAYS (now and forevermore) a set length, then CHAR is preferred.
  3. A single letter string. For example, we should use CHAR(1) for a middle initial column.

Question 15. What is difference between VARCHAR and NVARCHAR?

Answer. Unicode is used to extend beyond the English and Western Europe code pages, like if u want to store Hindi, Chinese, Japanese Kanji or Korean Hangul language. (Unicode is sometimes referred to as "double-wide")

  1. Varchar is Non-Unicode variable length while Nvarchar is Unicode variable length.
  2. Varchar can store max 8000 char while Nvarchar can store max 4000 Char.
  3. Varchar takes 1 byte per char while Nvarchar takes 2 bytes per char.
https://www.mssqltips.com/sqlservertip/4322/sql-server-differences-of-char-nchar-varchar-and-nvarchar-data-types.



Extension Method in C#

Extension Method in C#
Qst 1. What is Extension method.
Ans. An extension method is a static method of a static class that can be invoked like as an instance method syntax. Extension methods are used to add new behaviors to an existing type without altering it.
What does it mean it means extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
In extension method "this" keyword is used with the first parameter and the first parameter will be of type that is extended by extension method.
The most common extension methods are the LINQ standard query operators that add query functionality to the existing on  IEnumerable  and IQeryable type, for an example.


using System;
using ExtensionMethod; //  to access extension method
namespace MainProgramm
{
    class MainProgram
    {
        static void Main(string[] args)
        {
            DateTime CurrentDate = DateTime.Now;
            Console.WriteLine("Current Date : " + CurrentDate);
            string  FormatedDate  = CurrentDate.DMYhmsString();
            Console.WriteLine("Formated Date : " + FormatedDate);
            Console.ReadLine();
        }     
    }
}.
using System;
namespace ExtensionMethod
{
    public static class ExtensionMethod
    {
        public static string  DMYhmsString(this DateTime AttendDate)
        {
            return AttendDate.ToString("dd MMM yyyy hh:mm:ss");
        }
    }
}

Output.






Qst 2. What is advantages of using Extension method.
Ans.  There is no need to creating a new derived type, recompiling, or otherwise modifying the original type.

Qst 3Extension method is a static method of static class but it call as extension method can you explain why encapsulation rule not violated.
Ans. The intermediate language (IL) generated by the compiler translates your code into a call on the static method. The principle of encapsulation is not really being violated.\
here is the MSIL code of above example.



Qst 4. Can extension methods access private variables in the type they are extending?.
Ans. No, Cause inaccessible due to protection level.









Qst 5. Will  an extension method  be call if it has the same signature as a method defined in the type?.
Ans. An extension method will never be called if it has the same signature as a method defined in the type. At compile time, extension methods always have lower priority than instance methods defined in the type itself. Hence you can use extension methods to extend a class or interface, but not to override them.
Let see an example for better understanding.





















Output. you can see in extension method we have printed some label but not come in output since ToLower() method already exists in string type .








Qst 5. Can I add extension methods to an existing static class?.
Ans. No. Cause Instance with this keyword is going to extend and we know static class does not allow this or instance.
Qst 5. Can I add ref and out keyword with first parameter extension methods?.
Ans. No.  
 






Exception & Exception Handling in C#



 Exception & Exception Handling in C#

This topic is prepared to keep in mind  at the point of  interview  as how an interviewer can ask one by one question in deep to know how deep knowledge you have. let start from rudimentary.

Qst 1. What is an Exception and its types.
Exception is a type of error(s) that occurs during the execution of an application, Errors are typically problem that are not expected.
There are two types of exception in .Net
a). System exception  : Occurred by  the CLR.
b). Application Exception Occurred by the custom code written by user(programmer).
Some system exception list given below with description.

 Exception Class  Description (Cause)
 SystemException  A failed run-time check;used as a base class for other.
 AccessException  Failure to access a type member, such as a method or field.
 ArgumentException  An argument to a method was invalid.
 ArgumentNullException  A null argument was passed to a method that doesn't   accept  it.
 ArgumentOutOfRangeException  Argument value is out of range.
 ArithmeticException  Arithmetic over - or underflow has occurred.
 ArrayTypeMismatchException  Attempt to store the wrong type of object in an array.
 BadImageFormatException  Image is in the wrong format.
 DivideByZeroException  An attempt was made to divide by zero.
 FormatException  The format of an argument is wrong.
 IndexOutOfRangeException   An array index is out of bounds.
 InvalidCastExpression    An attempt was made to cast to an invalid class.
 InvalidOperationException  A method was called at an invalid time.
 MissingMemberException  An invalid version of a DLL was accessed.
 NotFiniteNumberException   A number is not valid.
 NotSupportedException  Indicates sthat a method is not implemented by a class.
 NullReferenceException  Attempt to use an unassigned reference.
 OutOfMemoryException  Not enough memory to continue execution.
 StackOverflowException  A stack has overflown.

Qst 2. Why we need exception handling how to handle exception. Give an real time example?
Ans. To stop the abnormal termination of the program, and also provide user understandable messages when an exception is raised. So that users can make the decision without the help of developers.
C# provides built-in support to handle the exception using try, catch & finally block.
try
{
    // code that may raise exceptions
}
catch(Exception ex)
{
    // handle exception
}
finally
{
    // final cleanup code.
}
There is lot of example one of them is in case of excel import of attendance data of employees where empid , attenddate field is there suppose those employee  is present there's  attenddate and time are filled and those employees absent there's data is empty.
Now when you are importing data if all employees are preset then  data imported successfully, but in case of at least one employee absent, then system gives exception because datetime conversion exception not handled.
Once you have handle exception it is import fine to give default date value.

using System;
using System.Data;
class ExceptionThrowNThrowex
{
    public static void Main()
    {
        DataTable dtExcelData = GetData();
        DataTable dtProcessed = new DataTable();
        dtProcessed.Columns.AddRange(new DataColumn[]
        {
            new DataColumn("EmpID",typeof(short)),
            new DataColumn("AttendDate", typeof(DateTime)),

        });
        foreach (DataRow row in dtExcelData.Rows)
        {
            DataRow dr = dtProcessed.NewRow();
            dr["EmpID"] = row["EmpID"];
            dr["AttendDate"] = row["AttendDate"];
            dtProcessed.Rows.Add(dr);
        }
        Console.ReadLine();
    }
    /// <summary>
    /// Make data manullay, in real time scenario these data will come from excel.
    /// </summary>
    /// <returns>DataTable</returns>
    static DataTable GetData()
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[]
        {
            new DataColumn("EmpID",typeof(string)),
            new DataColumn("AttendDate", typeof(string))           
        });
        DataRow dr = dt.NewRow();
        dr["EmpID"] = "1";
        dr["AttendDate"] = "2020-03-29 09:34:22.193";   
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr["EmpID"] = "2";
        dr["AttendDate"] = "2020-03-29 09:35:22.193";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr["EmpID"] = "3";
        dr["AttendDate"] = "";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr["EmpID"] = "4";
        dr["AttendDate"] = "2020-03-29 09:35:22.193"; ;
        dt.Rows.Add(dr);
        return dt;
    }
}
Output is Crashes application.
Once you handle Exception like .
using System;
using System.Data;
class ExceptionThrowNThrowex
{
    public static void Main()
    {
        DataTable dtExcelData = GetData();
        DataTable dtProcessed = new DataTable();
        dtProcessed.Columns.AddRange(new DataColumn[]
        {
            new DataColumn("EmpID",typeof(short)),
            new DataColumn("AttendDate", typeof(DateTime)),
        });
        foreach (DataRow row in dtExcelData.Rows)
        {
            try
            {
                DataRow dr = dtProcessed.NewRow();
                dr["EmpID"] = row["EmpID"];
                dr["AttendDate"] = row["AttendDate"];
                dtProcessed.Rows.Add(dr);
            }
            catch
            {
                DataRow dr = dtProcessed.NewRow();
                dr["EmpID"] = row["EmpID"];
                dr["AttendDate"] = "1 jan 1900";
                dtProcessed.Rows.Add(dr);
            }
        }
        foreach (DataRow dr in dtProcessed.Rows)
        {
            string AttendDate = Convert.ToDateTime(dr["AttendDate"]).ToString("dd MMM yyyy");
            Console.WriteLine("EmpID : " + dr["EmpID"] + ",  IsPresent : " + ( Convert.ToDateTime(dr["AttendDate"]).ToString("dd MMM yyyy") == "01 Jan 1900" ? "No" : "Yes" ) + " ,AttendTime" + dr["AttendDate"]);
        }
        Console.ReadLine();
    }
Output




Qst 3. Explain the difference between Error and Exception in C#?
Exceptions are those which can be handled at the runtime whereas errors cannot be handled.

The exception is thrown by the CLR (Common Language Runtime) when errors occur that are nonfatal and recoverable by user programs. It is meant to give you an opportunity to do something with a throw statement to transfer control to a catch clause in a try block.

Qst 4 . What is order of Try - Catch - Finally Blocks?.
Ans.  Order of exception handling  , try block comes first after that catch block and at last finally block get executed.

Qst 5. Can a try block exists without catch or Finally block ?.
Ans . No.  At least one of them is required to run code and we can also have both block at a time. let see an example

using System;
class MainProgram
{
    static void Main(string[] args)
    {
        Devision();
        Console.ReadLine();
    }
   static void Devision()
    {
        try
        {
            int InputNo;
            InputNo = Convert.ToInt32(Console.ReadLine().ToString());
            int module = 100 / InputNo;
        }     
    }
}
If you are trying to run code it will give Compile time error.
Error CS1524  Expected catch or finally. 
A try block have at least one catch block or finally block, hence combination of try-catch-finally or try catch or try-finally blocks is valid.

Qst 6. Can a try block have multiple catch block ?.
Ans . Yes.  let see an example

using System;
class MainProgram
{
    static void Main(string[] args)
    {
        Devision();
        Console.ReadLine();
    }
   static void Devision()
    {
        try
        {
            int InputNo;
            InputNo = Convert.ToInt32(Console.ReadLine().ToString());
            int module = 100 / InputNo;
        }
        catch (DivideByZeroException ex)
        {
             Console.WriteLine("Exception :" + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception :" + ex.Message);
        }
    }
}
It is running perfect.
Qst 7. Can a try block has catch and finally block  both?.
Ans . Yes.  
Qst 8. might possibility an  interviewer can ask to given bellow scenario.
  .........
  ........ in continuation 
  catch (Exception Ex)
 {
    Console.WriteLine("Exception :" + ex.Message);
 }
 catch (DivideByZeroException ex)
 {
   Console.WriteLine(ex.Message);
 }

as we explained more than one catch block is possible. Is this  code is running perfect or give any error?.
Ans. It will give error at compile time
Error CS0160  A previous catch clause already catches all exceptions of this or of a super type ('Exception')
Because 'Exception' is parent class of all exception handling class and it will never go to next catch block. hence more specialized catch block should come before a generalized one. other wise specialized catch block will never be executed ( dot net frame not allowed the same.)

Qst 9. Next question arises that will finally block execute if try or catch block has return statement or gives exception in try or catch block.
Ans. finally block will always execute whether try and catch block have return statement.
since generally finally block used to memory management to destroy object which was created earlier.

Qst 10. What happened if error occurred in finally block?. 
Ans. If error occurred in finally block cursor leave finally block nothing will executed further.

Qst 11. Can finally return value?.
 Ans.   No .
           finally
           {
               return 1; // Gives compile time error  'control can not leave the body of finally clause'
           }
because finally block is used for cleanup resources so that the control can not be exit without its completion.

Qst 12. What is inner or nested exception?.
Ans. An exception will be caught in the catch block that follows the try block where an exception occurred.

using System;
public class NestedClass
{
    public static void Main()
    {
        try
        {
            try
            {

                int[] arr = { 2, 4, 5, 6, 7 };
                var intdata = arr[6];
            }
            catch (IndexOutOfRangeException innerEx)
            {
                Console.WriteLine("Inner Exception " + innerEx.Message.ToString());
                int z = 0;
                z = Convert.ToInt32(Console.ReadLine());
                if (z != 0)
                {
                    var i = 100 / z;
                }
                else
                {
                    throw new DivideByZeroException("Invalid OPeration Divide by Zero ", innerEx);
                }
            }
        }
        catch (DivideByZeroException OuterEx)
        {
            Console.WriteLine("Outer Exception : " + OuterEx.Message + ", Inner Exception : " +OuterEx.InnerException);
        }
        Console.ReadLine();
    }
}.
Enter Zero hit enter it will give following result.



Qst 13. What is Application or Custom exception.
Ans. Custom exception is application level exception that is created by developer  to raise an exception when the business rule of your application gets violated or not full fill you criteria what you expected.

using System;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
public class CustomApplicationException
{
    public static void Main()
    {
        string Name = "Ram@123";
        try
        {
            ValidateName(Name);
        }
        catch (InvalidNameException Ex)
        {
            Console.WriteLine(Ex.Message.ToString());
        }
        Console.ReadLine();
    }
    private static void ValidateName(string Name)
    {
        Regex regex = new Regex(@"^[a-zA-Z\s]+$");
        if (!regex.IsMatch(Name))
        {
            throw new InvalidNameException(Name);
        }
    }
}

[Serializable]
internal class InvalidNameException : ApplicationException
{
    public InvalidNameException()
    {

    }
    public InvalidNameException(string Name) : base(string.Format("Invalid Name : {0}", Name))
    {

    }
    public InvalidNameException(string message, Exception innerException) : base(message, innerException)
    {
    }
    protected InvalidNameException(SerializationInfo info, StreamingContext context) : base(info, context)
    {
    }
}
 here exception interface has following overload methods.

// Out put



Qst 14 . What is  throw keyword  and why use?.
 Ans. throw keyword  can be used to raised manually exception. throw keyword  can raised any type of exception which is derived from exception class like throw new DivideByZeroException , NullreferenceException , FileNotFoundException , Object null Reference Exception.
throw creates an object of any valid exception type using the new keyword. it has three overload method, without parameter , with message , and with messgae and innerexception parameter which was explain in Ans 11.
Example:

using System;
class ExceptionThrowANDex
{
    public static void Main()
    {
        try
        {
            DevidebyZero(10);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.StackTrace);
        }
        Console.ReadLine();
    }
    public static void DevidebyZero(int i)
    {
        try
        {
            int j = 0;
            int k = i / j;
            Console.WriteLine(k);
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            throw;// check first comment and uncomment see what happen
        }
    }
}

for a moment lets comment throw keyword in above code what you think will main method catch blog executed. No its not executed because in DevidebyZero method exception handled but not throw
hence in cal lee method catch not executed.
Once you uncomment and run application throw keyword help to raised exception manually in Main  method and out put is.




If you  want to show some customization message then you can do
      int j = 0;
      if (j != 0)
       {
           int k = i / j;
           Console.WriteLine(k);
           Console.ReadLine();
        }
        else
        {
            throw new DivideByZeroException("You are try to devide by Zero Which is not meaning         full");
        }
Output :







Qst 15. What is Stack Tarce?.
Ans. The execution stack keeps track of all the methods that are in execution at a given instant. A trace of the method calls is called a stack trace. The stack trace listing provides a way to follow the call stack to the line number in the method where the exception occurs.

The StackTrace property returns the frames of the call stack that originate at the location where the exception was thrown. You can obtain information about additional frames in the call stack by creating a new instance of the System.Diagnostics.StackTrace class and using its StackTrace.ToString method. Example in Ans 12.

Qst 16. What is difference between throw and throw ex ?.
Ans. throw ex  will reset your stack trace so error will appear from the line where throw ex written while throw does not reset stack trace and you will get information about original exception.
In MSIL code when you use throw ex it will generate code as throw , and if you use throw it will create rethrow.

 using System;
class ExceptionThrowNThrowex
{
    public static void Main()
    {
        try
        {
            Console.WriteLine("Please enter number.:");
            int i = Convert.ToInt32(Console.ReadLine());
            Division(i);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.StackTrace);
        }
        Console.ReadLine();
    }
    public static void Division(int i)
    {
        try
        {
            Division_Concrete(i);
        }
        catch (Exception ex)
        {
            throw ex;// it will reset stack trace of method Division_Concrete exception
        }
    }
    public static void Division_Concrete(int i)
    {
        try {
            if (i == 0)
            {
                throw new DivideByZeroException("you are trying to divide by zero which is not meaning full");
            }
            else
            {
                int k = 100 / i;
                Console.WriteLine(k);
            }
        }
        catch(Exception ex)
        {
            throw;
        }
    }
}
Output  it is working properly.


Now use only throw in place of   throw ex in Division(int i) method. and out put






   
Qst 17. What is Web Exception?.
Ans. The web exception class is thrown by class decedent from WebRequest and WebResponse
when the web exception is thrown by a decedent of the web request class the response property provides the internet response to the application



  SQL interview Question Answer- Part -  2 Question 16. What is an Index? Answer :  Indexes are used to retrieval data more quickly from dat...