Saturday, June 4, 2016

.NET Core 5 is the small optimized run time for ASP.NET 5. It currently runs on Windows, and will be extended to Linux and Mac. You will have more choice of which operating systems you use for ASP.NET 5 development and deployment, supported by Microsoft. Azure will support ASP.NET 5 in both Linux and Windows VMs. You choose.

Saturday, August 23, 2014

Important Interview Questions to know in Asp.net

1. What CLR Does?
2. Explain CTS (Common Type System)?
3. Explain CLS (Common Language Specification)
4. Explain Boxing and unboxing?
5. Explain Variables in C#.
6. Explain Jump statements in c#.
7. What is nullable Type?
8. Why does string in .net is immutable?
9. Explain string Comparison?
10. Explain String Interning?
11. Explain String Pooling?
12. Explain string builder functioning behind the scene?
13. Explain Indexers?
14. Explain Iterators?
15. Explain secure strings?
16. Explain Enumerated types.
17. Explain interface.
18. Should I design a base type or an interface?
19. Explain App domain?
20. Explain Threading in dot net?
21. What is diffgram?
22. How assignment of value is different in value type and reference type?
23. Difference between shallow copy and deep copy of object?
24. What is use of using keyword?
25. What is cloning?
26. What is Assembly? Difference between Private and Shared Assembly? How can we make shared assembly?
27. Why value type cannot be inherited?
28. What is the difference between an event and a delegate?
29. What size is .net object?
30. When and How to Use Dispose and Finalize in C#?
31. What is difference between equivalent of objects and identical of objects?
32. What's the difference between the System.Array.CopyTo() and System.Array.Clone()?
33. How ado.net maintain transaction of data?
34. What is delay signing?
35. Can you declare a C++ type destructor in C# like ~MyClass ()?
36. What is difference between == and .Equals?
37. What is the difference between structures and enumeration?
38. Should I make my destructor virtual?
39. How do I declare a pure virtual function in C#?
40. Where would you use an iHTTPModule, and what are the limitations of any approach you might take in implementing one?
41. What is difference between code base security and role base security? Which one is better?
42. Is it possible to prevent a browser from caching an aspx page?
43. What is the difference between Debug. Write and Trace. Write?
44. What is difference between repeater over datalist and datagrid?
45. Describe Main Characteristics of static functions?
46. What is DataReader? Difference between datareader and dataset?
47. What is DLL hell?
48. What is Temporary Table? How can we create it?
49. What is strong key and what is the use of it?
50. What is Impersonation?
51. What is Partitioned Tables?
52. What types of data validation events are commonly seen in the client-side form validation? Web service support?
54. What is PreProcessor in .NET and type , where it use?
55. Please brief not about XSD, XSLT & XML?
57. What is Polymorphism?
58. What is implicit operator overloading?
59. What is Operator Overloading?
60. What is difference between http handler and http module?
61. What is Caching? Where is it use? Why and when?
62. What is Cursor? Define Different type of cursor?
63. What is Views?
64. What is Triggers? What are the different types of triggers in Sql Server 2005?
65. What is use of extern keyword?
66. What is base assembly of Dot net?
67. What’s difference between Shadowing and Overriding?
68. What’s difference between Server.Transfer and response.Redirect?
69. Can you explain in brief how the ASP.NET authentication process works?
70. What are the various ways of authentication techniques in ASP.NET?
71. How does authorization work in ASP.NET?
72. What’s difference between Datagrid, Datalist and repeater?
73. What exactly happens when ASPX page is requested from Browser?
74. What is the result of ―select firstname, secondname from emp order by 2‖?
75. How can we create proxy class without VS?
76. How can we create overloaded methods in Web Service?
77. How can we maintain State in WebService?
78. ASP.Net Page Life Cycle ?
79. What are the different data types in dot net?
80. What is Static class?
81. How can you increase SQL performance?
82. What is ACID fundamental and what are transactions in SQL SERVER?
83. If we have multiple AFTER Triggers on table how can we define the sequence of the triggers?
84. Give the output of following code ?
85. Give the output of following code?
86. Give output of following code?
87. What is Performance tips and tricks in .net application?
88. How Garbage Collector Works?
89. How objects are allocated on heap?
90. What causes finalize methods to be called?
91. What is Sync Block Index and object pointer?
92. What is JIT compiler? What is its role?
93. How Types are stored in dot net?
94. Explain structure of GAC in windows?
95. What is Advantage and disadvantage of GC?
96. What is Reflection? Explain about reflection performance
97. What are members of a type?
98. Explain bridge between ISAPI and Application Domains?
99. How Securely Implement Request Processing, Filtering, and Content Redirection with HTTP Pipelines in ASP.NET?
100. Is there any difference in the way garbage collection works when it is called automatically by the Runtime
environment, and when it is invoked intentionally by the programmer?
101. What is probing?
102. What is compilation and execution procedure for asp.net page?
103. If need an array of objects then which option when better ArrayList Class or List Generic Class ? Array[] / ArrayList / List<T> Difference i.e. string[] arraylist.add(string) / List<string> ?
104. Custom Paging in ASP.NET 2.0 with SQL Server 2005
106. What is the difference between a Struct and a Class?
108. What is Web Gardening? How would using it affect a design?
109. What is view state? Where it stored? Can we disable it?
110. Can you debug a Windows Service? How?
111. What are the different ways a method can be overloaded?
112. How do you handle data concurrency in .NET?
114. What are jagged array?
115. Who host CLR? How windows identify where running assembly is managed or not?
116. Conceptual view of DotNet Framework
117. Explain Delegates?
118. Explaint about Events?
119. How to: Connect Event Handler Methods to Events ?
120. How to: Consume Events in a Web Forms Application ?
121. What’s the difference between localization and globalization?
122. Difference between primitive types, ref types and value types?
123. Difference between gettype() and typeof
124. What is Microsoft SharePoint Portal Server?
127. What is difference between static and singleton classes?
128. Explain Advantages of WCF.
129. What is dependency Injection?
130. What is difference between STA & MTA?
132. How does a database index work? 178
133. Give some threading best practices?
134. What is object pooling?
135. Static and Dynamic Assembly.
136. Why we have to consider object in lock statement as private?
137. How can we make class immutable? Give Example
138. How to override Equal, GetHashCode?
139. What is SSL and how can we implement it in our asp.net website?
140. What is difference between runtime polymorphism and compile time polymorphism?
141. What is difference between real proxy and transparent proxy?
142. What is prologue code?
143. Explain string class or what is behind the scene of string?
144. What is Encapsulation, polymorphism and abstraction? Give real time examples?
145. Why we use command object?
146. What is Satellite Assembly? How application knows which assembly should be loaded for particular culture?
147. Http request and response life cycle in ASP.Net?
148. If any body is editing data in webpage and at the time of editing row has been explicitly locked by user but if
any one stop website processing then how will handle locking?
149. Applied use of Inheritance ( i.e aggregation, specialization etc)
150. Explaing Connection pooling
151. Difference between dbnull and null?
152. What is snapshot in sql server?


Summary:

Do you want answers? you can send a  request mail to dotnetcircle@gmail.com for Answers, if you need to know.

WPF Architecture - An overview of Windows Presentation

In this article we are going to see an overview of Windows Presentation Foundation. In previous WPF tutorial i have explained a basic introduction to WPF. I would suggest to read that article because it explains why Microsoft introduced WPF and how it is better than Windows Forms applications.

To know more about the Windows Presentation Foundation(WPF), one must have a clear idea about the architecture of WPF. So lets get some overview of wpf architecture.


Overview of Windows Presentation Foundation

----------------------------------------------------------------------------------------


Windows Presentation Framework is a next generation UI framework to create applications with a rich user experience. It is part of the .NET framework 3.0 and higher. WPF architecture is a layered architecture which have Managed, Unmanaged and Core API layers as shown in below fig.



The position of WPF within the .NET Framework.


01. Managed Layer

Managed layer has two main components – Presentation Framework and Presentation Core.

- Presentation Framework provides the required functionalities that we need to build the WPF applications such as controls, data bindings, styling, shapes, media, documents, annotations, animation and more. PresentationFamework.dll is responsible for this purpose.

- Presentation Core acts as a managed wrapper around MILCore and provides public interface for MIL. Presentation Core is the home for WPF Visual System and provides classes for creating application visual tree. The Visual System creates visual tree which contains applications Visual Elements and rendering instructions. PresentationCore.dll is responsible for this purpose.



                  The public API exposed is only via this layer. Major portion of the WPF is in managed code.


PresentationFramework.dll :- It holds the top level WPF elements, including those that represents Windows, panels, controls, styles etc. It also implements the end-user presentation features including time-dependent, story-based animations and data binding.

PresentationCore.dll :- Presentation Core provides a managed wrapper for MIL and implements the core services for WPF such as UI Element and visual from which all shapes and controls derived in PresentationFramework.dll.

WindowsBase.dll :- Holds more basic elements which are capable to be reused outside the WPF environment like Dispatcher objects and Dependency objects.

02. Unmanaged Layer

This layer is also called milcore or Media Integration Library Core. MilCore is written in unmanaged code in order to enable tight integration with DirectX. DirectX engine is underlying technology used in WPF to display all graphics, allowing for efficient hardware and software rendering. MIL has Composition System that receives rendering instructions from Visual System and translates into data that can be understood by DirectX to render user interface.

03. Core API Layer

This layer has OS core components like Kernel, User32, GDI, Device Drivers, Graphic cards etc. These components are used by the application to access low level APIs. User32 manages memory and process separation.


Summary :

Do you like this Article? want to know more Interesting things on .Net, then you can subscribe and follow to this blog.



Connecting with Different Database Servers in .Net

Today, we will see how to connect with Different Databases in Ado.Net Framework.

1. For  SQL Server

Using ODBC
-------------

 // ODBC -- Standard Connection
using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={SQL Server}; Server=ServerName; DataBase=DataBaseName; Uid=UserName; Pwd=Secret";
conn.Open();

 // ODBC -- Trusted Connection
using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={SQL Server}; Server=ServerName; DataBase=DataBaseName; Uid=admin; Pwd=password";
conn.Open();
// or

OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={SQL Server}; Server=ServerName; DataBase=DataBaseName; Trusted_Connection=Yes;";
conn.Open();

Using OLEDB
---------------------

 // OleDb -- Standard Connection
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Driver=SQLOLEDB; Data Source=ServerName; Initial Catalog=DataBaseName; User id=UserName; Password=Secret;";
conn.Open();
 // OleDb -- Trusted Connection
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Driver=SQLOLEDB; Data Source=ServerName; Initial Catalog=DataBaseName; Integrated Security=SSPI;";
conn.Open();

Using .Net DataProvider
------------------------------

 // .NET DataProvider -- Standard Connection
using System.Data.SqlClient;
SqlConnection conn = new SqlDbConnection();
conn.ConnectionString ="Data Source=ServerName; Initial Catalog=DataBaseName; User id=UserName; Password=Secret;";
conn.Open();
 // .NET DataProvider -- Trusted Connection
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=ServerName; Initial Catalog=DataBaseName; Integrated Security=SSPI;";
conn.Open();

2. For Oracle

Using ODBC
---------------------

 // ODBC -- New Microsoft Driver

using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={Microsoft ODBC for Oracle};Server=OracleServer.world;Uid=UserName;Pwd=Secret;";
conn.Open();

 // ODBC -- Oracle Driver

using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={Oracle ODBC Driver};Dbq=myDataBase;Uid=UserName;Pwd=Secret;";
conn.Open();

Using OLEDB

 // OleDb -- Oracle Driver -- Standard Connection
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Driver=OraOLEDB.Oracle;Data Source=ServerName;User id=UserName;Password=Secret;";
conn.Open();

 // OleDb -- Oracle Driver -- Trusted Connection
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Driver=OraOLEDB.Oracle;Data Source=ServerName;OSAuthent=1;";
conn.Open();
// or
using System.Data.OleDb;

OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Driver=OraOLEDB.Oracle;Data Source=ServerName;User id=admin;Password=pwd";
conn.Open();

3. For DB2

Using ODBC
-------------
 // ODBC without DSN
using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={IBM DB2 ODBC DRIVER};DataBase=DataBaseName; HostName=ServerName; Protocol=TCPIP;Port=PortNumber;Uid=UserName;Pwd=Secret";
conn.Open();

Using OLEDB
--------------

 // OleDb -- Microsoft Driver
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Driver=DB2OLEDB; Network Transport Library=TCPIP; Network Address=xxx.xxx.xxx.xxx; Package Collection=CollectionName; Initial Catalog=DataBaseName; User id=UserName; Password=Secret;";
conn.Open();

// OleDb -- IBM Driver
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Driver=IBMDADB2; DataBase=DataBaseName; HostName=ServerName; Protocol=TCPIP; Port=PortNumber; Uid=UserName; Pwd=Secret;";
conn.Open();

Using .Net DataProvider
-----------------------
 // .NET DataProvider from IBM
using IBM.Data.DB2;
Db2Connection conn = new Db2Connection();
conn.ConnectionString = "DataBase=DataBaseName;Uid=UserName;Pwd=Secret";

conn.Open();

4. For MySQL

Using ODBC
------------
 // ODBC -- MyODBC Driver -- remote database
using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={MySql}; Server=db.domain.com; Option=131072; Port=3306; Stmt=; DataBase=DataBaseName; Uid=UserName; Pwd=Secret;" ;
conn.Open();

Using OLEDB
------------
 // OleDb
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=MySqlProv; Data Source=ServerName; User id=UserName; Password=Secret";
conn.Open();

Using .Net DataProvider
------------------------

 // .NET DataProvider from CoreLab
using CoreLab.MySql;
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString ="Host=ServerName; DataBase=DataBaseName; Protocol=TCP; Port=3306; Direct=true; Compress=false; Pooling=true; Min Pool Size=0; Max Pool Size=100; Connection Lifetime=0; User id=UserName;Password=Secret";

conn.Open();

5. For Microsoft Access

Using ODBC
--------------
 // ODBC -- Standard Security
using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)}; Dbq=c:\myPath\myDb.mdb; Uid=Admin; Pwd=;password";
conn.Open();

 // ODBC -- Workgroup (System Database)
using System.Data.Odbc;
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)}; Dbq=c:\myPath\myDb.mdb; SystemDb=c:\myPath\myDb.mdw;";
conn.Open();

Using OLEDB
-------------

 // OleDb with MS Jet -- Standard Security
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\mypath\myDb.mdb; User id=admin;Password=password";
conn.Open();
 // OleDb with MS Jet -- Workgroup (System Database)
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\mypath\myDb.mdb; System Database=c:\mypath\myDb.mdw";
conn.Open();


Summary :

Do you like this Article? Want to know more Interesting Concepts in .Net, then Subscribe and Follow to this blog.

Tuesday, August 12, 2014

SQL Server Basics of Cursors

CURSOR :

Cursor is a pointer to the temporary memory where data is retrieved from a table is stored. Main purpose of cursor is to provide access to one by one row in sequence from a table.

To work with cursor you have to perform the following five steps:

1. Cursor Declaration :

The first step to work with cursor is declaring the cursor. In cursor declaration you have to provide a name to the cursor, type of cursor and associate a 'select' statement to the cursor.

syntax: 

declare <cursor name> Cursor
[local/global]
[forwared-only/scroll]
[static/dynamic/keyset]
for [select statement]

2. Opening Cursor:

When we open the cursor then the select statement associated with cursor will be executed, rows retrieved by SELECT will be stored in temporary memory & CURSOR will point to that memory.

syntax:

OPEN <cursor name>

3. Fetching Data from Cursor :

When you have to make any changes to the data available in Cursor, you must copy the data from Cursor into variables in the program & this process of copying data from cursor into variables in the program is called Fetching Data.

Syntax: 

fetch  nexy/prior/first/last/relative/
absolute<n> from <cursor name> into
<local variable list>

After fetching a row to verify whether or not the fetch statement successfully fetches a row, use system variable "@@FETCH_STATUS". This variable will contain the value zero when 'fetch' was Success.

0 - fetch was success
1 - if the row try to fetch was beyond cursor.
2 - if the row try to fetch was missing in cursor.

4. Closing Cursor

After accessing data from cursor is completed you can close the cursor, when you close then link to temporary memory from your program will be closed, but the memory allocated for the cursor will not de-allocated. Hence, you can reopen the cursor.

syntax: Close <cursor name>

5. De-allocating Cursor

You can de-allocate the complete memory allocated for the cursor & once the cursor is de-allocated you can reopen the cursor without executing declaration statement again.

Syntax:

Deallocate <cursor name>

Simple Example for Cursor :

 CREATE TABLE Employee
(
 EmpID int PRIMARY KEY,
 EmpName varchar (50) NOT NULL,
 Salary int NOT NULL,
 Address varchar (200) NOT NULL,
)
GO
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(1,'Mohan',12000,'Noida')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(2,'Pavan',25000,'Delhi')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(3,'Amit',22000,'Dehradun')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(4,'Sonu',22000,'Noida')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(5,'Deepak',28000,'Gurgaon')
GO
SELECT * FROM Employee 




 SET NOCOUNT ON
DECLARE @Id int
DECLARE @name varchar(50)
DECLARE @salary int
 DECLARE cur_emp CURSOR
STATIC FOR 
SELECT EmpID,EmpName,Salary from Employee
OPEN cur_emp
IF @@CURSOR_ROWS > 0
 BEGIN 
 FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
 WHILE @@Fetch_status = 0
 BEGIN
 PRINT 'ID : '+ convert(varchar(20),@Id)+', Name : '+@name+ ', Salary : '+convert(varchar(20),@salary)
 FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
 END
END
CLOSE cur_emp
DEALLOCATE cur_emp
SET NOCOUNT OFF 




Saturday, August 9, 2014

New Learners: Understanding Normalization in SQL Server


What is Normalization?

When we want to store the some piece of information, we store it in database. Now storing a data in database mean, it should be stored properly so that while retrieving it, it should be easy. So we say store it in Normalized way. In short, Normalization can be defined as the process of organizing the data in database efficiently. The result of normalization is a logical database design and is called as Normal Form.

Why Normalization?
Goals of Normalization process are:

 -  It helps you to eliminate the redundant data from same table.
 -  It ensures the data dependencies between the tables are proper.
 -  A Normalized database design makes it easy to change in modification is required.

Advantages of Normalization

 - Data redundancy is removed
 - Faster update as redundant columns from a tables are removed.
 - Easy understanding of structure
 - Improvement in Index as be achieved
 - Long term maintainability of database get easier

Disadvantages of Normalization

 - Query to some extent get complicated
 - Performance may degrade due to multiple joins
 - Suppose I have some data with me, say


As you can see above, table is not properly managed

Normalization process is mainly divided in to stages which we call as Normal Form. Let’s talk about each Normal Form one by one with an example. Basically a database can be normalized into various normal forms such as-

1. First Normal Form (1NF)
2. Second Normal Form (2NF)
3. Third Normal Form (3NF)
4. Boyce Codd Normal Form (BCNF)
and Fourth Normal Form (4NF) and so on.

But today I would like to talk about only up to Boyce Codd Normal Form because Fourth Normal Form and others is rarely used in the database design.

First Normal Form (1NF)

It says,
 - Eliminate all repeating groups in individual table
 - One cell should contain only one data
 - Create a separate table for each set of related data
 - Identify each set of related data with a primary key


As you can see above,

 -  Our UnNormalized table does not have repeating group. So this is not applicable over here.
 - We have eliminated the comma separated values and shifted to another table Skill. Each employee in Employee table is related to Skill table through EmployeeId column (Note: It is not a foreign key relationship.  -  We are just replacing the comma separated values in each cell in to rows and creating separate table for it).
 -  Each cell is containing single value.
 -  Skills of table is identified with primary key.

Second Normal Form (2NF)

It says,

 - Tables should be in First Normal Form (1NF)
 - Eliminate partial primary key dependencies
 - Non key column must depend on the entire composite primary key and create separate tables for sets of       values that apply to multiple records.
 - Relate these tables with a foreign key


As you can see above,
 - We have eliminated the partial primary key dependency of EmployeeId and created a new table which will contain the relation of EmployeeId and SkillId. This both columns will be the respective foreign key for Employee and Skill table.

Third Normal Form (3NF)

- Table should be in Second Normal Form
- Eliminate fields that are not dependent on key i.e. - Eliminate Transitive Dependencies. Create a separate table for it.
- Let’s suppose I want to add new columns in Employee Table Manager and Project.


Now, adding this 2 column violates the third Normal Form because the non key column Project is dependent on another not key column i.e. - Manager.
So we will normalize the table by separating nondependent column to another table. This way we can achieve third Normal Form.



Boyce Codd Normal Form (BCNF)
It says,

 - BCNF is based on the concept of a determinant.
 - A determinant is any attribute (simple or composite) on which some other attribute is fully functionally dependent.
 - A relation is in BCNF is, and only if, every determinant is a candidate key.
 - The same as 3NF except in 3NF we only worry about non-key attributes

Note: If there is only one candidate key then 3NF and BCNF are the same.

Consider another column in below table say ProjectTechnology



- As shown above, each manager will be handling unique project, so we can say particular project is determined by particular manger where Manager and Project depicts a candidate key.

- If we delete the entry of Manager Ronnie from the table we lose not only information of Project BCF but also the fact that project was developed in Asp.Net technology. We cannot make the entry of the fact that BCF project was developed using Asp.Net.

So let’s break this into separate tables


Fourth Normal Form (4NF)

It says,

 - Database design should follow the 1NF, 2NF, 3NF and BCNF if possible
 - There must not be more than one multivalued dependencies other than a candidate key.
 - I hope you got it what actually is the process of Normalization.

Conclusion

Thus concluding it, Normalization is a process which is a must to design any database. Hope you like this article. Please share your comments whether it’s good or bad. Your comments are valuable to me to get better. 

Friday, August 8, 2014

Learners: Exceptions Handling in C#.Net

Exceptions:
--------------


An Exception is an object delivered by the Exception class. This Exception class is exposed by the System.Exception namespace. Exceptions are used to avoid system failure in an unexpected manner. Exception handles the failure situation that may arise. All the exceptions in the .NET Framework are derived from the System.Exception class.

To understand exception, we need to know two basic things:

1. Somebody sees a failure situation that happened and throws an exception by packing the valid information.

2. Somebody who knows that a failure may happen catches the exception thrown. We call it Exception Handler.

In other words, Exception objects that describe an error are created and then thrown with the throw keyword. The runtime then searches for the most compatible exception handler.

Programmers should throw exceptions when:

- The method cannot complete its defined functionality. For example, if a parameter to a method has an invalid value:

static void CopyObject(SampleClass original)
{
if (original == null)
{
throw new System.ArgumentException("Parameter cannot be null", "original");
}

}


This type of Exception is thrown as ArgumentNullException.

- An inappropriate call to an object is made, based on the object state. For example, trying to write to a read-only file. In cases where an object state does not allow an operation, throw an instance of InvalidOperationException or an object based on a derivation of this class. This is an example of a method that throws an InvalidOperationException object:

class ProgramLog
{
    System.IO.FileStream logFile = null;
    void OpenLog(System.IO.FileInfo fileName, System.IO.FileMode mode) {}

    void WriteLog()
    {
        if (!this.logFile.CanWrite)
        {
            throw new System.InvalidOperationException("Logfile cannot be read-only");
        }
        // Else write data to the log and return.
    }
}

- When an argument to a methord causes an exception. In this case, the original exception should be caught and an ArgumentException instance should be created. The original exception should be passed to the constructor of the ArgumentException as the InnerException parameter:

static int GetValueFromArray(int[] array, int index)
{
    try
    {
        return array[index];
    }
    catch (System.IndexOutOfRangeException ex)
    {
        System.ArgumentException argEx = new System.ArgumentException("Index is out of range", "index", ex);
        throw argEx;
    }
}

try and catch blocks

- When exceptions are thrown, you need to be able to handle them. This is done by implementing a try/catch block. Code that could throw an exception is put in the try block and exception handling code goes in the catch block. Below Example shows how to implement a try/catch block. Since an OpenRead() method could throw one of several exceptions, it is placed in the try block. If an exception is thrown, it will be caught in the catch block. The code in  below will print message and stack trace information out to the console if an exception is raised.

using System;
using System.IO;

class tryCatchDemo
{
    static void Main(string[] args)
    {
        try
        {
            File.OpenRead("NonExistentFile");
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

finally block

The purpose of a finally statement is to ensure that the necessary cleanup of objects, usually objects that are holding external resources, happens immediately, even if an exception is thrown. One example of such cleanup is calling Close on a FileStream immediately after use instead of waiting for the object to be garbage collected by the common language runtime, as follows:

static void CodeWithoutCleanup()
{
    System.IO.FileStream file = null;
    System.IO.FileInfo fileInfo = new System.IO.FileInfo("C:\\file.txt");

    file = fileInfo.OpenWrite();
    file.WriteByte(0xF);

    file.Close();
}

To turn the previous code into a try-catch-finally statement, the cleanup code is separated from the working code, as follows.

static void CodeWithCleanup()
{
    System.IO.FileStream file = null;
    System.IO.FileInfo fileInfo = null;

    try
    {
        fileInfo = new System.IO.FileInfo("C:\\file.txt");

        file = fileInfo.OpenWrite();
        file.WriteByte(0xF);
    }
    catch(System.Exception e)
    {
        System.Console.WriteLine(e.Message);
    }
    finally
    {
        if (file != null)
        {
            file.Close();
        }
    }
}

Because an exception can happen at any time within the try block before the OpenWrite() call, or the OpenWrite() call itself could fail, we are not guaranteed that the file is open when we try to close it. The finally block adds a check to make sure the FileStream object is not null before calling the Close method. Without the null check, the finally block could throw its own NullReferenceException, but throwing exceptions in finally blocks should be avoided if possible.


Summary

This has been an introduction to handling exceptions. By now, you should have a good understanding of what an exception is. You can implement algorithms within try/catch blocks that handle exceptions. Additionally, you know how to clean up resources by implementing a finally block whose code is always executed before leaving a method.

Note:
 - Do you like this post, do you want to know more interesting concepts in .net, then subscribe to this blog.
 - You can also mail to dotnetcircle@gmail.com for any queries or issues in .net, we will try to solve and will post in this blog.