Saturday, 21 July 2012

asp.net

ASP.Net Interview Questions and answers for freshers pdf
0. What is .Net?
 It was a System which can be used in the developed as various  kinds of applications like Console, Windows, Web&Mobile.
It Magerly consist of three things
(i) Language (C#.Net, VB.Net, J#.Net, Vcpp.Net etc)
(ii) Technologies (ASP.Net, ADO.Net, WPF, WCF etc)
(iii) Servers (SQL Server, Web Server, Sharepoint Server, Biztalk Server etc)

1 . What is ASP.NET?
ASP.NET is a programming framework built on the common language run time that can be used on a server to build powerful Web applications.

2.What is a IL?
(IL)Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code is compiled to IL. This IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.

3.What is a CLR?
Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework. All Languages have runtime and its the responsibility of the runtime to take care of the code execution of the program. For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL, Java has Java Virtual Machine etc.

4.What is a CLS(Common Language Specification)?
This is a subset of the CTS which all .NET languages are expected to support. It was always a dream of Microsoft to unite all different languages in to one umbrella and CLS is one step towards that. Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.

5.What is a Managed Code?
Managed code runs inside the environment of CLR i.e. .NET runtime. In short all IL are managed code. But if you are using some third party software example VB6 or VC++ component they are unmanaged code as .NET runtime (CLR) does not have control over the source code execution of the language.

6.What is an Assembly?
Assembly is unit of deployment like EXE or a DLL. An assembly consists of one or more files (dlls, exe’s, html files etc.), and represents a group of resources, type definitions, and implementations of those types.An assembly may also contain references to other assembles.

7.What are the different types of Assembly?
There are two types of assembly Private and Public assembly (Shared Assembly).
  • A private assembly is normally used by a single application, and is stored in the application's directory, or a sub-directory beneath.
  • A shared assembly is normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime.
 8.What is a Manifest?
Assembly metadata is stored in Manifest. Manifest contains all the metadata needed to do the following things:
  • Version of assembly
  • Security identity
  • Scope of the assembly
  • Resolve references to resources and classes.
9. What is NameSpace?
Namespace has two basic functionalities:-
  • Namespace logically group types. Ex: - System.Web.UI logically groups our UI related features.
  • In Object Oriented world many times it’s possible that programmers will use the same class name. By qualifying NameSpace with class name this collision is able to be removed.
10.What is Difference between Namespace and Assembly?
Following are the differences between namespace and assembly:
  • Assembly is physical grouping of logical units. Namespace logically groups classes.
  • Namespace can span multiple assemblies.                                                           
11.What is GAC?
GAC (Global Assembly Cache) is used where shared .NET assembly reside. GAC is used in the following situations:-
  • If the application has to be shared among several application.
  • If the assembly has some special security requirements like only administrators can remove the assembly.
12.How to add and remove an assembly from GAC?
There are two ways to install .NET assembly in GAC:-
  • Using Microsoft Installer Package.
  • Using Gacutil. Goto “Visual Studio Command Prompt” and type “gacutil –i (assembly_name)”, where (assembly_name) is the DLL name of the project.
13.Can we force garbage collector to run?
System.GC.Collect () forces garbage collector to run. This is not recommended but can be used if situations arise.

14.What is reflection?
All .NET assemblies have metadata information stored about the types defined in modules. This metadata information can be accessed by mechanism called as “Reflection”.
System. Reflection can be used to browse through the metadata information.

15.What are Value types and Reference types?
Value types directly contain their data which 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. Reference types can be self-describing types, pointer types, or interface types.

16.What is concept of Boxing and UnBoxing?
Boxing is converting a value type to a reference type (Object Type).
Unboxing is vice versa of boxing operation where the value is copied from the instance in to appropriate storage location.

17.What is concept of Casting?
Casting is converting a reference type to a reference type or a value type as another value type

18.What is Exception? What is the difference between System exceptions and Application exceptions?
An exception is what happens when something goes wrong with the code at runtime. All exception derives from Exception Base class. Exceptions can be generated programmatically or can be generated by system.
Application exception is used when we want to define user defined exception.
System exception is all which is defined by .NET.

19.What is the difference between Convert.toString and .toString () method?
The basic difference between them is “Convert” function handles NULLS while “i.ToString ()” does not, it will throw a NULL reference exception error.

20.What is the difference between Convert.toString and .toString () method?
The basic difference between them is “Convert” function handles NULLS while “i.ToString ()” does not, it will throw a NULL reference exception error.

21.What is Native Image Generator (Ngen.exe)?
The Native Image Generator utility (Ngen.exe) allows you to run the JIT compiler on your assembly's MSIL and generate native machine code which is cached to disk. After the image is created .NET runtime will use the image to run the code rather than from the hard disk.

22.What is CodeDom?
“CodeDom” is an object model which represents actually a source code. It is designed to be language independent - once you create a “CodeDom” hierarchy for a program we can then generate the source code in any .NET compliant language.
The Native Image Generator utility (Ngen.exe) allows you to run the JIT compiler on your assembly's MSIL and generate native machine code which is cached to disk. After the image is created .NET runtime will use the image to run the code rather than from the hard disk.

23.What is CodeDom?
“CodeDom” is an object model which represents actually a source code. It is designed to be language independent - once you create a “CodeDom” hierarchy for a program we can then generate the source code in any .NET compliant language.

24.How can we use COM Components in .NET?
.NET components communicate with COM using RCW (Runtime Callable Wrapper). Following are the ways with which you can generate RCW :-
 Adding reference in Visual Studio.net. See figure below (Adding reference using VS.NET 2005). Wrapper class is generated and placed in the “BIN” directory.
                                Fig: Adding Reference using VS.NET 2005
  • Using Type library import tool. Tlbimp.exe yourname.dll.
  • Using interopservices.System.runtime.Interopservices namespace contains class TypeLib Converter which provides methods to convert COM classes and interface into assembly metadata.
  •  Make your custom wrappe rs.If your COM component does not have type library then the only way to communicate is writing custom wrappers. That means communicating directly with COM components.
25.When we use windows API in .NET is it managed or unmanaged code?
Windows API in .NET is unmanaged code.

26.What is COM ?
Microsoft’s COM is a technology for component software development. It is a binary standard which is language independent. DCOM is a distributed extension of COM.

27. What is Multi-tasking ?
It’s a feature of modern operating systems with which we can run multiple programs at same time example Word, Excel etc.

28. What is Multi-threading ?
Multi-threading forms subset of Multi-tasking. Instead of having to switch between programs this feature switches between different parts of the same program. Example you are writing in word and at the same time word is doing a spell check in background.

29.What is a Thread ?
A thread is the basic unit to which the operating system allocates processor time.

29. Did VB6 support multi-threading ?
While VB6 supports multiple single-threaded apartments, it does not support a freethreading model, which allows multiple threads to run against the same set of data.

30. Can we have multiple threads in one App domain ?
One or more threads run in an AppDomain. An AppDomain is a runtime representation of a logical process within a physical process. Each AppDomain is started with a single thread, but can create additional threads from any of its threads.

31. Which namespace has threading ?
Systems.Threading has all the classes related to implement threading. Any .NET application who wants to implement threading has to import this namespace.

32. Can you explain in brief how can we implement threading ?
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim pthread1 As New Thread(AddressOf Thread1)
Dim pthread2 As New Thread(AddressOf Thread2)
pthread1.Start()
pthread2.Start()
End Sub
Public Sub Thread1()
Dim pintcount As Integer
Dim pstr As String
pstr = “This is first thread”
Do Until pintcount > 5
lstThreadDisplay.Items.Add(pstr)
pintcount = pintcount + 1
Loop
End Sub
Public Sub Thread2()
Dim pintcount As Integer
Dim pstr As String
pstr = “This is second thread”
Do Until pintcount > 5
lstThreadDisplay.Items.Add(pstr)
pintcount = pintcount + 1
Loop
End Sub
Above is a sample code which shows simple sample code for threading. Above sample code can be found in “Threading” folder in CD provided. Above sample has two methods “Thread1()” and “Thread2()” which are started in multi-threaded mode in Form load event of the sample.

33. How can we change priority and what the levels of priority are provided by .NET ?
Thread Priority can be changed by using Threadname.Priority = ThreadPriority.Highest.
In the sample provided look out for code where the second thread is ran with a high priority.
Following are different levels of Priority provided by .NET :-
  • ThreadPriority.Highest
  • ThreadPriority.AboveNormal
  •  ThreadPriority.Normal
  •  ThreadPriority.BelowNormal
  • ThreadPriority.Lowest
34. What does AddressOf operator do in background ?
The AddressOf operator creates a delegate object to the BackgroundProcess method. A delegate within VB.NET is a type-safe, object-oriented function pointer. After the thread has been instantiated, you begin the execution of the code by calling the Start() method of the thread.

35. How can you reference current thread of the method ?
"Thread.CurrentThread" refers to the current thread running in the method."CurrentThread" is a public static property.

36.  What's Thread.Sleep() in threading ?
Thread's execution can be paused by calling the Thread.Sleep method. This method takes an integer value that determines how long the thread should sleep. Example Thread.CurrentThread.Sleep(2000).

37. How can we make a thread sleep for infinite period ?
You can also place a thread into the sleep state for an indeterminate amount of time by calling Thread.Sleep (System.Threading.Timeout.Infinite). To interrupt this sleep you can call the Thread.Interrupt method.

38.  What is Suspend and Resume in Threading ?
It is Similar to Sleep and Interrupt. Suspend allows you to block a thread until another thread calls Thread.Resume. The difference between Sleep and Suspend is that the latter does not immediately place a thread in the wait state. The thread does not suspend until the .NET runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state.

39. What the way to stop a long running thread ?
Thread.Abort() stops the thread execution at that moment itself.

40. How do I debug thread ?
                               Fig: Debug thread window
This window is only seen when the program is running in debug mode. In windows one of the window is “Threads”.

41. What is Thread.Join() in threading ?
 There are two versions of Thread.Join :-
  •  Thread.join().
  • Thread.join(Integer) this returns a Boolean value.
The Thread.Join method is useful for determining if a thread has completed before starting another task. The Join method waits a specified amount of time for a thread to end. If the thread ends before the time-out, Join returns true; otherwise it returns False. Once you call Join, the calling procedure stops and waits for the thread to signal that it is done.
Example you have "Thread1" and "Thread2" and while executing 'Thread1" you call
"Thread2.Join()".So "Thread1" will wait until "Thread2" has completed its execution and the again invoke "Thread1".
Thread.Join(Integer) ensures that threads do not wait for a long time. If it exceeds a specific time which is provided in integer the waiting thread will start.

42. What are Daemon threads and how can a thread be created as Daemon?
Daemon thread's run in background and stop automatically when nothing is running program. Example of a Daemon thread is "Garbage collector". Garbage collector runs until some .NET code is running or else its idle.
You can make a thread Daemon by Thread.Isbackground=true

43. When working with shared data in threading how do you implement synchronization ?
There are certain somethings that you need to be careful with when using threads. If two threads (e.g. the main and any worker threads) try to access the same variable at the same time, you'll have a problem. This can be very difficult to debug because they may not always do it at exactly the same time. To avoid the problem, you can lock a variable before accessing it. However, if the two threads lock the same variable at the same time, you'll have a deadlock problem.
SyncLock x
'Do something with x
End SyncLock

44. Can we use events with threading ?
Yes, you can use events with thread; this is one of the techniques to synchronize one thread with other.


45. How can we know a state of a thread?
"ThreadState" property can be used to get detail of a thread. Thread can have one or a combination of status.System.Threading. Threadstate enumeration has all the values to detect a state of thread. Some sample states are Isrunning, IsAlive, suspended etc.

 46. What is use of Interlocked class ?
Interlocked class provides methods by which you can achieve following functionalities :
  •  Increment Values.
  •  Decrement values.
  •  Exchange values between variables.
  •  Compare values from any thread.
47. What is a monitor object?
Monitor objects are used to ensure that a block of code runs without being interrupted by code running on other threads. In other words, code in other threads cannot run until code in the synchronized code block has finished. SyncLock and End SyncLock statements are provided in order to simplify access to monitor object.

48. What is the sequence in which ASP.NET events are processed ?
Following is the sequence in which the events occur :
  •  Page_Init.
  • Page_Load.
  • Control events
  •  Page_Unload event.
Page_init event only occurs when first time the page is started, but Page_Load occurs in subsequent request of the page.

49. Explain the differences between Server-side and Clientside code?
Server side code is executed at the server side on IIS in ASP.NET framework, while client side code is executed on the browser.


50. How can you avoid deadlock in threading?
A good and careful planning can avoid deadlocks.There are so many ways Microsoft has provided by which you can reduce deadlocks example Monitor, Interlocked classes, Wait handles, Event raising from one thread to other thread, ThreadState property which you can poll and act accordingly etc.

51What is the difference between thread and process?
A thread is a path of execution that run on CPU, a process is a collection of threads that share the same virtual memory. A process has at least one thread of execution, and a thread always run in a process context.
A good and careful planning can avoid deadlocks.There are so many ways Microsoft has provided by which you can reduce deadlocks example Monitor, Interlocked classes, Wait handles, Event raising from one thread to other thread, ThreadState property which you can poll and act accordingly etc.

52. What is the difference between thread and process?
A thread is a path of execution that run on CPU, a process is a collection of threads that share the same virtual memory. A process has at least one thread of execution, and a thread always run in a process context.

53. What is an application domain?
Previously “PROCESS” where used as security boundaries. One process has its own virtual memory and does not over lap the other process virtual memory; due to this one process can not crash the other process. So any problem or error in one process does not affect the other process. In .NET they went one step ahead introducing application domains. In application domains multiple applications can run in same process with out influencing each other. If one of the application domains throws error it does not affect the other application domains. To invoke method in a object running in different application domain .NET remoting is used.
                Fig:: One process can have multiple Application domains

54. What is .NET Remoting ?
.NET remoting is replacement of DCOM. Using .NET remoting you can make remote object calls which lie in different Application Domains. As the remote objects run in different process client calling the remote object can not call it directly. So the client uses a proxy which looks like a real object. When client wants to make method call on the remote object it uses proxy for it. These method calls are called as “Messages”. Messages are serialized using “formatter” class and sent to client “channel”. Client Channel communicates with Server Channel. Server Channel uses as formatter to deserialize the message and sends to the remote object.
                           Fig:: Channels, Formatters and Proxy in action.

55. Which class does the remote object has to inherit ?
All remote objects should inherit from System.MarshalbyRefObject.

56. What are two different types of remote object creation mode in .NET ?
There are two different ways in which object can be created using Remoting :
  •  SAO (Server Activated Objects) also called as Well-Known call mode.
  •  CAO (Client Activated Objects)
SAO has two modes “Single Call” and “Singleton”. With Single Call object the object is created with every method call thus making the object stateless. With Singleton the object is created only once and the object is shared with all clients.
CAO are stateful as compared to SAO. In CAO the creation request is sent from client side. Client holds a proxy to the server object created on server.

 57.What is an application object ?
Application object ca be n used in situation where we want data to be shared across users globally.

58.What’s the difference between Cache object and application object ?
The main difference between the Cache and Application objects is that the Cache object provides cache-specific features, such as dependencies and expiration policies.

59.How can get access to cache object ?
The Cache object is defined in the System.Web.Caching namespace. You can get a reference to the Cache object by using the Cache property of the HttpContext class in the System.Web namespace or by using the Cache property of the Page object.

60.What are dependencies in cache and types of dependencies ?
When you add an item to the cache, you can define dependency relationships that can force that item to be removed from the cache under specific activities of dependenci es.Example if the cache object is dependent on file and when the file data changes you want the cache object to be update. Following are the supported dependency :-
  •  File dependency :- Allows you to invalidate a specific cache item when a diskbased file or files change.
  •  Time-based expiration :- Allows you to invalidate a specific cache item depending on predefined time.
  • Key dependency :-Allows you to invalidate a specific cache item depending when another cached item changes.
61. What is view state and use of it? 
The current property settings of an ASP.NET page and those of any ASP. NET server controls contained within the page. ASP.NET can detect when a form is requested for the first time versus when the form is posted (sent to the server), which allows you to program accordingly.

62. What are user controls and custom controls? 
Custom controls:
A control authored by a user or a third-party software vendor that does not belong to the NET Framework class library. This is a genenc tel-rn that includes user controls. A custom server control is used in Web Forms (ASP. NET pages). A custom client control is used in Windows Forms applications.
User Controls:
In ASP.NET: A user-authored server control that enables an ASP.NET page to be re-used as a server control. An ASP.NET user control is authored declaiatively and persisted as a text file with an .ascx extension. The ASP.NET page framework compiles a user control on the fly to a class that derives from the System.Web.UlUserControl class.

63. What are the validation controls? 
A set of server controls included with ASP.NET that test user input in HTML and Web server controls for programmer-defined requirements. Validation controls perform input checking in server code. If the user is working with a browser that supports DHTML. the validation controls can also petform validation using client script.

64. What is the difference between Response.Write() and 
Response.Output.WriteO?
The latter one allows you to write formatted output.

65. What methods are fired during the page load? Init() 
When the page is instantiated, Load() - when the page is loaded into server memory,PreRender () - the brief moment before the page is displayed to the user as HTML, Unload() - when page finishes loading.

66. Where does the Web page belong in the .NET Framework class hierarchy? 
System.Web.U1.Page

67. How do you read an XML file into a DataSet?
Using the DataSet object’s ReadXML method.

68. When do you use ExecuteReader, ExecuteNonQuery, ExecuteScalar methods?
  • If the command or stored procedure that is being executed returns a set of rows, then we use ExecuteReader method.
  • If the command or stored procedure that is being executed returns a single value then we use ExecuteScalar method.
  • If the command or stored procedure performs INSERT, DELETE or UPDATE operations, then we use ExecuteNonQuery method. ExecuteNonQuery method returns an integer specifying the number of rows inserted, deleted or updated.
69. What is Microsoft ADO.NET?
Visual Studio .NET provides access to databases through the set of tools and namespaces collectively referred to as Microsoft ADO.NET

70. What are the 3 major types of connection objects in ADO.NET? 
OleDbConnection object : Use an OleDbConnection object to connect to a Microsoft Access or third-party database, such as MySQL. OLE database connections use the OleDbDataAdapter object to perform commands and return data.
SqlConnection object : Use a SqlConnection object to connect to a Microsoft SQL Server database. SQL database connections use the SqlDataAdapter object to perform commands and return data.
OracleConnection object : Use an OracleConnection object to connect to Oracle databases. Oracle database connections use the OracleDataAdapter object to perform commands and return data. This connection object was introduced in Microsoft .NET Framework version 1.1.

71. List the 4 common ADO.NET Namespaces?
System.Data : Contains Classes, types, and services for creating and accessing data sets and their subordinate objects
System.Data.SqlClient : Contains Classes and types for accessing Microsoft SQL Server databases
System.Data.OracleClient : Contains Classes and types for accessing Oracle databases (Microsoft .NET Framework version 1.1 and later)
System.Data.OleDb : Contains Classes and types for accessing other databases

72. List all the steps in order, to access a database through ADO.NET?
  •  Create a connection to the database using a connection object.
  •  Invoke a command to create a DataSet object using an adapter object.
  •  Use the DataSet object in code to display data or to change items in the database.
  •  Invoke a command to update the database from the DataSet object using an adapter object.
  •  Close the database connection if you explicitly opened it in step 2 using the Open method. Invoking commands without first invoking the Open method implicitly opens and closes the connection with each request.
73. Why will you usually create an ASPNET user account in the Database for an ASP.NET web application?
Web applications run using the ASPNET user account. The SQL database administrator will have to set up this account and grant it permissions before your Web application will have access to a SQL database. For file-based databases, such as Microsoft Access, you must grant permissions on the database file to the ASPNET user account using Windows file security settings.

74. What is the difference between DataReader and DataAdapter? 
  •  Data Reader is read only forward only and much faster than DataAdapter.
  •  If you use DataReader you have to open and close connection explicitly where as if you use DataAdapter the connection is automatically opened and closed.
  •  DataReader is connection oriented where as Data Adapter is disconnected
75. Can you inherit from SqlConnection Class?
No, you cannot inheirt from SqlConnection Class. SqlConnection Class is a sealed class. It is a compile time error.

76. Will the connection be closed, if the SqlConnection object goes out of scope? 
No, If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose.


77. What happens if connection pooling is enabled?
If connection pooling is enabled and when you call Close or Dispose methods, then the connection is returned to the connection pool. This connection can then be resused.If connection pooling is disabled and when you call Close or Dispose methods, the underlying connection to the server is actually closed.


78. How do you ensure that the database connections are always closed? 
To ensure that the database connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.
using (SqlConnection ConnectionObject = new SqlConnection())
{
ConnectionObject.Open();
//The database connection will be closed when the control exits the using code block
}

79. Can your class inherit from SqlCommand Class?
No, you cannot inheirt from SqlCommand Class. SqlCommand Class is a sealed class. It is a compile time error.

80. Give an example that shows how to execute a stored procedure in ADO.NET?
using (SqlConnection ConnectionObject = new SqlConnection())
{
//Specify the name of the stored procedure to execute and the Connection Object to use
SqlCommand CommandObject = new SqlCommand("StoredProcedureName", ConnectionObject);
//Specify the SQL Command type is a stored procedure
CommandObject.CommandType = CommandType.StoredProcedure;
//Open the connection
ConnectionObject.Open();
//Execute the Stored Procedure
int RecordsAffected = CommandObject.ExecuteNonQuery();
}

81. Can you reuse a SqlCommand object?
Yes, you can reset the CommandText property and reuse the SqlCommand object.

82. What are the methods that can ensure asynchronous execution of the Transact-SQL statement or stored procedure?
BeginExecuteNonQuery
BeginExecuteReader

83. What is SqlCommand.CommandTimeout Property used for?
CommandTimeout Property is used to Get or set the wait time before terminating the attempt to execute a command and generating an error.
//Specify the CommandTimeout property value
SqlCommand CommandObject = new SqlCommand("StoredProcedureName",ConnectionObject);
//Wait for 10 seconds to execute the Stored procedure
CommandObject.CommandTimeout = 10;
The time is in seconds. The default is 30 seconds.

84. How do you create an instance of SqlDataReader class?
To create an instance of SqlDataReader class, you must call the ExecuteReader method of the SqlCommand object, instead of directly using a constructor.
//Error! Cannot use SqlDataReader() constructor
//to create an instance of SqlDataReader class
SqlDataReader ReaderObject = new SqlDataReader();
//Call the ExecuteReader method of the SqlCommand object
SqlCommand CommandObject = new SqlCommand();
SqlDataReader ReaderObject = CommandObject.ExecuteReader();
Creating an instance of SqlDataReader class using SqlDataReader() constructor generates a compile time error - The type 'System.Data.SqlClient.SqlDataReader' has no constructors defined.

85. How do you programatically check if a specified SqlDataReader instance has been closed?
Use the IsClosed property of SqlDataReader to check if a specified SqlDataReader instance has been closed. If IsClosed property returns true, the SqlDataReader instance has been closed else not closed.

86. How do you get the total number of columns in the current row of a SqlDataReader instance?
FieldCount property can be used to get the total number of columns in the current row of a SqlDataReader instance.

87. What is the use of SqlParameter.Direction Property?
SqlParameter.Direction Property is used to specify the Sql Parameter type - input-only, output-only, bidirectional, or a stored procedure return value parameter. The default is Input.

88. How do you retrieve two tables of data at the same time by using data reader?
Include 2 select statements either in a stored procedure or in a select command and call the ExecuteReader() method on the command object. This will automatically fill the DataReader with 2 Tables of data.
 The datareader will always return the data from first table only. If you want to get the second table then you need to use ReaderObject.NextResult() method. The NextResult() method will return true if there is another table. The following code shows you how do it.
//Create the SQL Query with 2 Select statements
string SQLQuery = "Select * from Customers;Select * from Employees;";
//Create the Connection Object
SqlConnection ConnectionObject = new SqlConnection(ConnectionString);
//Create the Command Object
SqlCommand CommandObject = new SqlCommand(SQLQuery, ConnectionObject);
//Open the connection
ConnectionObject.Open();
//Execute the command. Now reader object will have 2 tables of data.
SqlDataReader ReaderObject = CommandObject.ExecuteReader();
//Loop thru the tables in the DataReader object
while (ReaderObject.NextResult())
{
while (ReaderObject.Read())
{
//Do Something
}
}
//Close the Reader
ReaderObject.Close();
//Close the Connection
ConnectionObject.Close();

89. What are the advantages of using SQL stored procedures instead of adhoc SQL queries in an ASP.NET web application?
Better Performance : As stored procedures are precompiled objects they execute faster than SQL queries. Every time we run a SQL query, the query has to be first compiled and then executed where as a stored procedure is already compiled. Hence executing stored procedures is much faster than executing SQL queries.
Better  Security: For a given stored procedure you can specify who has the rights to execute. You cannot do the same for an SQL query. Writing the SQL statements inside our code is usually not a good idea. In this way you expose your database schema (design) in the code which may be changed. Hence most of the time programmers use stored procedures instead of plain SQL statements.
Reduced Network Traffic : Stored Procedures reside on the database server. If you have to execute a Stored Procedure from your ASP.NET web application you just specify the name of the Stored Procedure. So over the network you just send the name of the Stored Procedure. With an SQL query you have to send all the SQL statements over the network to the database server which could lead to increased network traffic.

90. Can you update the database using DataReader object?
No, You cannot update the database using DataReader object. DataReader is read-only, foward only. It reads one record at atime. After DataReader finishes reading the current record, it moves to the next record. There is no way you can go back to the previous record.

91. What is the difference between a DataReader and a DataSet?
DataReader
  •  DatReader works on a Connection oriented architecture.
  •  DataReader is read only, forward only. It reads one record at atime. After DataReader finishes reading the current record, it moves to the next record. There is no way you can go back to the previous record. So using a DataReader you read in forward direction only.
  •  Updations are not possible with DataReader.
  •  As DataReader is read only, forward only it is much faster than a DataSet.
DataSet
  •  DataSet works on disconnected architecture.
  •  Using a DataSet you can move in both directions. DataSet is bi directional.
  •  Database can be updated from a DataSet.
  •  DataSet is slower than DataReader.
92. Give an example scenario of using a DataSet and a DataReader?
If you want to just read and display the data(No updates, deletes, or inserts) then use a DataReader.
If you want to do a batch inserts, updates and deletes then use a DataSet.

93. What is AppSetting Section in “Web.Config” file ?
 Web.config file defines configuration for a webproject. Using “AppSetting” section we can define user defined values. Example below defined is “ConnectionString” section which will be used through out the project for database connection.
<configuration>
<appSettings>
<add key="ConnectionString" value="server=xyz;pwd=www;database=testing" />
</appSettings>

94. How can we create custom controls in ASP.NET ?
User controls are created using .ASCX in ASP.NET. After .ASCX file is created you need to two things in order that the ASCX can be used in project:.
  •  Register the ASCX control in page using the <%@ Register directive. Example: <%@ Register tagprefix="Accounting" Tagname="footer" Src="Footer.ascx" %>
  •  Now to use the above accounting footer in page you can use the below directive.            <Accounting:footer runat="server" />
95. How can you enable automatic paging in DataGrid ?
Following are the points to be done in order to enable paging in Datagrid :-
  •  Set the “AllowPaging” to true.
  •  In PageIndexChanged event set the current pageindex clicked.
96. What is the difference between Server.Transfer and response.Redirect ?
Following are the major differences between them:-
 Response.Redirect sends message to the browser saying it to move to some different page, while server.transfer does not send any message to the browser but rather redirects the user directly from the server itself. So in server.transfer there is no round trip while response.redirect has a round trip and hence puts a load on server.
 Using Server.Transfer you can not redirect to a different from the server itself.
Example if your server is www.yahoo.com you can use server.transfer to move to www.microsoft.com but yes you can move to www.yahoo.com/travels, i.e. within websites. This cross server redirect is possible only using Response.redirect.
 With server.transfer you can preserve your information. It has a parameter called as “preserveForm”. So the existing query string etc. will be able in the calling page. In response.redirect you can maintain the state, but has lot of drawbacks.

97. What is the Difference between ASP and ASP.NET?
ASP.NET new feature supports are as follows :-
Better Language Support:
  • New ADO.NET Concepts have been implemented.
  • ASP.NET supports full language (C#, VB.NET, C++) and not simple scripting like VBSCRIPT..
Better controls than ASP:
  •  ASP.NET covers large set’s of HTML controls..
  • Better Display grid like Datagrid, Repeater and datalist.Many of the display grids have paging support.  Controls have events support 
  • All ASP.NET controls support events. 
  • Load, Click and Change events handled by code makes coding much simpler and much better organized.
Compiled Code:
The first request for an ASP.NET page on the server will compile the ASP.NET code and keep a cached copy in memory. The result of this is greatly increased performance.
Better Authentication Support:
ASP.NET supports forms-based user authentication, including cookie management and automatic redirecting of unauthorized logins. (You can still do your custom login page and custom user checking).
User Accounts and Roles:
ASP.NET allows for user accounts and roles, to give each user (with a given role) access to different server code and executables.
High Scalability:
  •  Much has been done with ASP.NET to provide greater scalability.
  •  Server to server communication has been greatly enhanced, making it possible to scale an application over several servers. One example of this is the ability to run XML parsers, XSL transformations and even resource hungry session objects on other servers.
Easy Configuration:
  •  Configuration of ASP.NET is done with plain text files.
  •  Configuration files can be uploaded or changed while the application is running.
  • No need to restart the server. No more metabase or registry puzzle.
Easy Deployment:
No more server restart to deploy or replace compiled code. ASP.NET simply redirects all new requests to the new code.

98. How do you upload a file in ASP.NET ?
I will leave this to the readers … Just a hint we have to use System.Web.HttpPostedFile
class.

99. How do I send email message from ASP.NET ?
ASP.NET provides two namespaces System.WEB.mailmessage class and System.Web.Mail.Smtpmail class. Just a small homework create a Asp.NET project and send a email at shiv_koirala@yahoo.com. Do not Spam.

100. What are different IIS isolation levels?
IIS has three level of isolation:-
LOW (IIS process):: In this main IIS process and ASP.NET application run in same process. So if any one crashes the other is also affected. Example let’s say (well this is not possible) I have hosted yahoo, hotmail .amazon and google on a single PC. So all application and the IIS process runs on the same process. In case any website crashes it affects every one.
                              Fig:  LOW IIS process scenario
Medium (Pooled):: In Medium pooled scenario the IIS and web application run in different
process. So in this case there are two processes process1 and process2. In process1 the IIS
process is running and in process2 we have all Web application running.
                             Fig: Medium pooled scenario
High (Isolated):: In high isolated scenario every process is running is there own process. In below figure there are five processes and every one handling individual application. This consumes heavy memory but has highest reliability.
                                      Fig: High isolation scenario
101. What is the Differences between ASP and ASP.NET?
1. ASP: Code is Interpreted
   ASP.NET: Code is Compiled
2. ASP: Business Logic and Presentation Logic are in a single file
   ASP.NET: Business Logic and Presentation Logic are in separate files (.cs or .vb) and (.aspx) respectively.
3. ASP: No Web Server Controls
   ASP.NET: Web Server Controls supported by strong .NET Framework
4. ASP: No RAD in Classic ASP
   ASP.NET: Supports RAD

No comments:

Post a Comment

Popular posts