Exception Handling-
What are Exceptions?
Exceptions are unusual occurrences that happen within the logic of an
application.
What are the 3 approaches to handle
exceptions in a Web application?
1. Use exception-handling structures to
deal with exceptions within the scope of a procedure. This technique is called
structured exception handling (SEH) in the Visual Studio .NET documentation.
try
catch
finally
2. Use error events to deal with
exceptions within the scope of an object.
Page_Error
Global_Error
Application_Error
3. Use custom error pages to display
informational messages for unhandled exceptions within the scope of a Web
application.
Where will the control flow if an exception
occurs inside a try block?
If a statement in a try block causes an exception, control flow passes
immediately to the next catch statement. When control flow passes to a catch
block, the statements contained in the catch block are processed to correct the
error or otherwise handle the exception.
Will the finally block gets executed, if an
exception occurs?
Yes, a finally block will always be executed irrespective of whether an
exception has occured or not.
What is the main use of a finally block in
exception handling?
Finally block is mainly used to free resources used within the try block.
How do you raise an exception?
Use the throw keyword to raise an exception. Use this keyword within your
exception-handling structure to immediately pass control flow to the catch
statement.
Will the following code block compile?
try
{
throw new System.IO.FileNotFoundException();
}
catch (Exception E)
{
Response.Write(E.Message);
}
catch (System.IO.FileNotFoundException FNFE)
{
Response.Write(FNFE.Message);
}
No, a compile time error A previous catch clause already
catches all exceptions of this or of a super type ('System.Exception').
Catch blocks are evaluated in the order in which they appear in code. The
exception declaration of each catch block determines which type of exception
the catch block handles. Always order catch blocks from most specific to most
general. So, in the preceding sample, FileNotFoundException should be placed
before the general Exception catch block.
What is ApplicationException class used for?
If you are creating a large application or creating components that are
used by other applications, you might want to define your own exception classes
based on the ApplicationException class. For example, the following code
defines a class for the UserLoggedOnException:
public class
UserLoggedOnException : System.ApplicationException
{
// Exception constructor (overloaded).
public UserLoggedOnException()
: this("The user is already logged on to the server", null)
{
}
public UserLoggedOnException(string message)
: this(message, null)
{
}
public UserLoggedOnException(string message, Exception inner)
: base(message, inner)
{
}
}
The preceding UserLoggedOnException class inherits its properties and methods
from the ApplicationException base class. The new exception class provides only
its own constructor to set the default message to display. This is a standard
practice.
What are Error Events?
Another way to handle exceptions is through the Web objects’ built-in error
events. When an unhandled exception occurs in a Web application, ASP.NET fires
the error events shown below.
Page_Error : Occurs when an unhandled exception
occurs on the page. This event procedure resides in the Web form.
Global_Error : Occurs when an unhandled exception
occurs in the application. This event procedure resides in the Global.asax
file.
Application_Error : Occurs when an unhandled exception
occurs in the application. This event procedure resides in the Global.asax
file.
Error events let you handle exceptions for an entire object in a single,
centralized location—the error event procedure. This is different from using
exception-handling structures, in which exceptions are handled within the
procedure where they occurred. You can use error events in the following ways:
As a substitute for exception-handling
structures :
Because error events occur outside the scope of the procedure in which the
error occurred, you have less information about the steps leading up to the
exception and therefore less ability to correct the exception condition for the
user. However, using exception-handling events is fine for tasks where you
might not be able to correct the exception in code.
As an adjunct to exception-handling
structures :
Error events can provide a centralized “backstop” against exceptions that were
not foreseen or handled elsewhere. Using the two exception-handling techniques
together lets you catch all exceptions before the user sees them, display a
reasonable message, and even record the exception in a log as part of an
ongoing effort to improve your application.
Give an example to show how error events can
be used to handle exceptions?
To handle an exception using error events, follow these steps:
1. In the Page_Error event procedure, get
the exception that occurred using the GetLastError method.
2. Do something with the exception, such
as display a message to the user, take steps to correct the problem, or write
to an error log.
3. Clear the exception using the
ClearError method.
4. Redisplay the page. Web form
processing stops immediately when an exception occurs, so server controls and
other items on the page might not be displayed after the exception is cleared.
5. Add the following code to Page_Error
event procedure on the web page.
private void Page_Error(object
sender, System.EventArgs e)
{
// Get the error.
Exception ex = Server.GetLastError();
// Store the message in a session object.
Session["Error"] = ex.Message;
// Clear the error message.
Server.ClearError();
// Redisplay this page.
Server.Transfer("ErrorEvents.aspx");
}
The preceding code stores the
exception message as a Session state variable before clearing the exception so
that the message can be displayed when the page is reloaded by the Transfer
method. The following code displays the saved exception message when the page
is redisplayed:
Add the following code to Page_Load event procedure on the web page.
private void Page_Load(object
sender, System.EventArgs e)
{
// Display error. if any.
if (Session["Error"] != null)
{
litError.Text = "The following error occurred:
" +
Session["Error"].ToString();
// Clear the Session state variable.
Session["Error"] = null;
}
}
Can you have a try block without a catch or a
finally block?
No, you cannot have a try block without a catch or a finally block. A try block
cannot exist in isolation. A try block should be followed by either a catch
block or a finally block or both.
Is the following code legal?
try
{
Response.Write("Try block executed");
}
finally
{
Response.Write("Finally block executed");
}
Yes, it's legal. A try statement does not have to have a catch statement if it
has a finally statement.
What is wrong with using the following type
of exception handler?
catch(Exception E)
{
//Some Code
}
This handler catches exceptions
of type Exception, therefore, it catches any exception. This can be a poor
implementation because you are losing valuable information about the type of
exception being thrown and making your code less efficient. As a result, your
program may be forced to determine the type of exception before it can decide
on the best recovery strategy.
Will the second catch block handle the
exception thrown by the first catch block?
try
{
throw new System.IO.FileNotFoundException();
}
catch (System.IO.FileNotFoundException FNFE)
{
Response.Write(FNFE.Message);
throw new Exception();
}
catch(Exception E)
{
Response.Write(E.Message);
}
No. For a catch block to handle the exception, the statement that raised the
exception must be inside a try block.
What will happen to the exception raised by
the code in the following Button1_Click event procedure?
protected void
Button1_Click(object sender, EventArgs e)
{
throw new Exception();
try
{
Response.Write("Hello");
}
catch (Exception E)
{
Response.Write(E.Message);
}
}
The exception will not be handled by the catch block because the statement that
raised the exception must be inside a try block.
Managed and Unmanaged Code-
What is Managed Code and
Unmanaged Code?
Microsoft ASP.NET Web applications run under the control of the common language
runtime (CLR). The CLR controls how the application’s assembly executes,
allocates, and recovers memory; therefore, ASP.NET applications are said to use
managed code. In contrast, most other Windows executables use unmanaged code
because the executable itself determines how memory is used.
Examples of unmanaged code include the Microsoft Win32 API, legacy DLLs and
EXEs created for Windows applications prior to the Microsoft .NET Framework,
and COM objects.
What is Platform Invoke or pinvoke?
The process of executing native code from within a .NET assembly is called
platform invoke, or pinvoke for short. You use platform invoke to call the
Win32 API directly, to access existing (legacy) DLLs your company uses, or to
access procedures compiled to native code for performance reasons.
What are the steps to follow to use Platform
Invoke?
To use platform invoke, follow the following steps:
1. Import the
System.Runtime.InteropServices namespace.
2. Declare the unmanaged procedure using
the DllImport attribute or the Declare statement.
3. Map the data types of the procedures
parameters to the equivalent .NET types.
4. Call the unmanaged procedure and test
its return value for success.
5. If the procedure did not succeed,
retrieve and handle the exception code using the Marshal object’s
GetLastWin32Error method.
What are the limitations of using Unmanaged
Code from within a .NET assembly?
Performance : Although native-code DLLs can perform
some operations more quickly than equivalent code managed by the CLR, these
benefits might be offset by the time it takes to marshal the data to pass
between the unmanaged procedure and the .NET assembly.
Type safety : Unlike .NET assemblies, unmanaged
procedures might not be type-safe. This can affect the reliability of your .NET
application. In general, reliability is a paramount concern with ASP.NET Web
applications.
Code security : Unmanaged procedures do not use the
.NET Framework’s model for code security.
Versioning:Unmanaged code does not support .NET versioning; therefore,
assemblies that call unmanaged procedures might lose the benefit of being able
to coexist with other versions of the same assembly.
What are COM objects?
COM objects are another type of unmanaged code that you can use from .NET
assemblies. Because COM is widely used, Visual Studio includes built-in tools
for importing and using COM objects within .NET assemblies. Visual Studio also
includes the option of automatically registering .NET class library assemblies
for use from COM.
What happens when you add a
reference to a COM object from with in a dot net application?
When you add a
reference to a COM object, Visual Studio automatically generates an interop
assembly for the object and places it in the project’s /bin folder. The interop
assembly is created from the COM object’s type information and contains the
metadata that the CLR uses to call the unmanaged code in the COM object. You
can then use COM objects from within .NET code the same way that you use .NET
classes.
You can view this interop assembly using the Microsoft Intermediate Language
Disassembler (Ildasm.exe) included in the .NET Framework.
Can we create a .NET object for use from COM?
Yes, Visual Studio can automatically generate type library information and
register a .NET class library assembly for use from COM. These automatic tools
do not work for ASP.NET Web applications, so you must isolate the code you want
to use from COM in its own Class Library project.
How do you hide Public .NET Classes and other
public members from COM?
In some cases, you might want to hide selected .NET classes from COM but
keep them public for use from other .NET assemblies. The ComVisible attribute
allows you to select which public .NET classes and members are included in the
generated type library. This attribute applies hierarchically for the assembly,
class, and member levels.
How do you handle exceptions between .NET and
COM?
.NET handles errors through exception classes. COM handles errors through
32-bit data types called HRESULTs. All of the .NET exception classes include
HResult properties that map to COM HRESULT codes.
If an exception occurs in a .NET object, the exception is automatically mapped
to the appropriate HRESULT and returned to COM. Similarly, if an exception
occurs in a COM object, the COM HRESULT is mapped to the appropriate exception
class, which is returned to .NET, where it can be handled just like any other
exception.
If you are creating your own .NET exception classes for use with COM, be sure
to set the class’s HResult property so that the exception can be handled within
COM.
What are the technical limitations of COM
Interop?
The .NET Framework was developed to address the limitations of COM. Because
of this evolution, there are limits to the .NET features that you can use from
COM. The following list describes these limits:
Static members : COM requires objects to be
created before use, so it does not support .NET Static members.
New members : COM flattens the inheritance tree of
.NET objects, so members in a derived class that hides members inherited from a
base class are not callable.
Constructors with parameters : COM can’t pass parameters to an
object’s constructor.
What are the practical limitations of using
COM objects?
The following are the practical limitations of using COM objects from .NET:
Shared solutions might not allow COM objects
: ASP.NET host
service providers that use nondedicated servers can limit or prohibit the
installation of COM objects on their servers.
COM objects are prone to memory leaks : COM uses reference counting to
determine when to destroy objects and free memory. It is possible for this
reference count to become incorrect, leaving objects in memory indefinitely.
Type libraries might be inaccurate : Because COM separates the object’s
description from its implementation, it’s possible for this description to not
accurately reflect the object. In this case, the generated interop assembly
will also include those inaccuracies.
COM is unmanaged code : All the limitations of unmanaged code
apply to COM objects as well.
Tracing-
What is an exception log?
An exception log is a list of handled exceptions that occur while your
application is running. Reviewing the exception log periodically helps you
verify that exceptions are being handled correctly, are not occurring too
frequently, and are not preventing users from accomplishing tasks with your
application.
What is Tracing and what are the adavantages
of using tracing to log exceptions?
Tracing is a technique for recording events, such as exceptions, in an
application. There have always been ways to record errors in an application -
usually by opening a file and writing error messages to it. But tracing offers
the following significant advantages:
Standardization:Building
tracing into the .NET Framework ensures that programming techniques are the
same across all the applications you develop with the .NET Framework.
Built-in Web support:ASP.NET
extends the .NET Framework tools by including information related to the
performance and behavior of Web requests.
Configuration:You can turn
tracing on and off using settings in your application’s configuration file. You
don’t have to recompile your application to enable or disable tracing.
Performance:While disabled,
tracing statements do not affect application performance.
How do you turn tracing on and off for an ASP.NET
web application?
Tracing can be turned on or off for an entire Web application or for an
individual page in the application:
1. To turn tracing on for an entire
application, in the application’s Web.config file, set the trace element’s
Enabled attribute to True.
Or
2. To turn tracing on for a single
page, set the DOCUMENT object’s Trace property to True in the Visual Studio
.NET Properties window. This sets the @ Page directive’s Trace attribute to
True in the Web form’s HTML.
Where is the trace output displayed by
default?
By default, trace output is displayed at the end of each Web page.
While this is fine for debugging purposes, you’ll generally want to write trace
output to a log file when you start testing your completed application. To
write trace messages to a log file for an entire application, in the
application’s Web.config file, set the trace element’s PageOutput attribute to
False. ASP.NET then writes trace output to the Trace.axd file in your
application’s root folder.
How do you specify, how many page requets
should be written to the trace log?
The element's RequestLimit attribute can be used to specify how many page
requests to write to the trace log. For example, the following line from a
Web.config file turns on tracing for the application and writes the first 10
requests to the Trace.axd file:
How do you write trace messages to a log file
for only selected pages in an application?
To write trace messages to a log file for only selected pages in an
application, follow these steps:
In the application’s Web.config file, set the trace element’s Enabled attribute
to True and PageOutput attribute to False.
For each Web page you want to exclude from tracing, set the @ Page directive’s
Trace attribute to False.
What is the difference between Trace.Write()
and Trace.Warn() methods of a trace object?
The Trace object provides the Write and Warn methods to allow you to write
messages to a request’s trace information. The two methods are identical with
one difference: messages written with Trace.Write are displayed in black,
whereas messages written with Trace.Warn are displayed in red.
How do you programatically check if tracing
is enabled?
The Trace object’s IsEnabled property can be used to programatically check
if tracing is enabled.
How do you prevent from trace output being
written at the bottom of the web page?
You can prevent from trace output being written at the bottom of the web page
by setting the trace element’s PageOutput attribute to False in the Web.config
file.
What is the name of the file to which trace
log is written?
Trace.axd
Can you view Trace.axd from a remote machine?
No, by default, you can view Trace.axd only from the local server running
the application. If you want to view the trace log from a remote machine, set the
trace element’s LocalOnly attribute to False in the Web.config file
Session State and Application State-
What is a Session?
A Session is a
unique instance of the browser. A single user can have multiple instances of
the browser running on his or her machine. If each instance visits your Web
application, each instance has a unique session.A session starts when a user
accesses a page on a Web site for the first time, at which time they are
assigned a unique session ID. The server stores the user's session ID in the
Session.SessionID property.
What is the default session timeout period?
20 minutes.
Where do you generally specify the Session
Timeout?
You specify the Session Timeout setting in the web.config file.
Can you specify Session Timeout in a code
behind file?
Yes, can specify the Session.Timeout property as shown below in a code behind
file.
Session.Timeout = 10;
How do you end a user session?
You can call the Session.Abandon() method to end a user session. If a user
then tries to access a page the server will assign them a new session ID and it
will clear all the previous session variables. You'll typically use
Session.Abandon() on log-out pages.
What type of data can you store in
Application State and Session State variables?
Application State and Session State variables are used to store data that you
want to keep for the lifetime of an application or for the lifetime of a
session. You can store any type of data in the Application or Session state,
including objects.
Are Application State or Session State
variables type safe?
No, Application and Session state variables are created on the fly, without
variable name or type checking.
Do maintaining Session state affects
performance?
Yes
Can you turn of Session state?
Yes, Session state can be turned off at the application and page levels.
Are Application state variables available
throughout the current process?
Yes, Application state variables are available throughout the current process,
but not across processes. If an application is scaled to run on multiple
servers or on multiple processors within a server, each process has its own
Application state.
How do you disable Session state for a Web
form?
To turn Session state off for a Web form set EnableSessionState property of
the Page to False.
How do you turn Session state off for an
entire web application?
In the Web.config file, set the sessionstate tag to False.
What are Application State variables?
Application State variables are global variables that are available from
anywhere in the application. All Sessions can access Application State
variables.
How to add and remove data to Application
State Variables?
//Code to add data to Application State
Application.Add("AppName",
"Sample");
//Code to remove data from Application State
Application.Remove("AppName");
How do you remove all Application State
Variables data?
//Code to remove all Application State Variables data
Application.RemoveAll();
Transaction-
What is a transaction?
A transaction is a group of commands that change the data stored in a database.
The transaction, which is treated as a single unit, assures that the commands
are handled in an all-or-nothing fashion. if one of the commands fails, all of
the commands fail, and any data that was written to the database by the
commands is backed out. In this way, transactions maintain the integrity of
data in a database. ADO.NET lets you group database operations into
transactions.
What is the main purpose of database
transactions?
The main purpose of database transactions is to maintain the integrity of
data in a database.
How do you determine which SQL commands are
part of a transaction?
You can determine what database commands belong in a transaction by using the
ACID test. Commands must be atomic, consistent, isolated, and durable.
Commands belong in a transaction if they are:
Atomic:In other words, they
make up a single unit of work. For example, if a customer moves, you want your
data entry operator to change all of the customer’s address fields as a single
unit, rather than changing street, then city, then state, and so on.
Consistent:All the
relationships between data in a database are maintained correctly. For example,
if customer information uses a tax rate from a state tax table, the state
entered for the customer must exist in the state tax table. Isolated:Changes
made by other clients can’t affect the current changes. For example, if two
data entry operators try to make a change to the same customer at the same
time, one of two things occurs: either one operator’s changes are accepted and
the other is notified that the changes weren’t made, or both operators are
notified that their changes were not made. In either case, the customer data is
not left in an indeterminate state.
Durable:Once a change is
made, it is permanent. If a system error or power failure occurs before a set
of commands is complete, those commands are undone and the data is restored to
its original state once the system begins running again.
Why is transaction processing very important
for web applications?
Transaction processing is very important for Web applications that use data
access, because Web applications are distributed among many different clients.
In a Web application, databases are a shared resource, and having many
different clients distributed over a wide area can present the below key
problems.
Contention for resources:Several
clients might try to change the same record at the same time. This problem gets
worse the more clients you have.
Unexpected failures:The
Internet is not the most reliable network around, even if your Web application
and Web server are 100 percent reliable. Clients can be unexpectedly
disconnected by their service providers, by their modems, or by power failures.
Web application life cycle:Web
applications don’t follow the same life cycle as Windows applications—Web forms
live for only an instant, and a client can leave your application at any point
by simply typing a new address in his or her browser.
List the steps in order to process a
transaction?
1.Begin a transaction.
2.Process database commands.
3.Check for errors.
4.If errors occurred, restore the database to its state at the beginning of the
transaction. If no errors occurred, commit the transaction to the database.
Explain how a DataSet provides transaction
processing?
DataSet provide transaction processing through the RejectChanges and Update
methods. DataSet also provide an AcceptChanges method that resets the state of
records in a data set to Unchanged. Data sets provide implicit transaction
processing, because changes to a data set are not made in the database until
you invoke the Update method on the data adapter object. This lets you perform
a set of commands on the data and then choose a point at which to make the
changes permanent in the database.
If an error occurs during the Update method, none of the changes from the data
set is made in the database. At that point, you can either attempt to correct
the error and try the Update method again or undo the changes pending in the
data set using the data set’s RejectChanges method.
Give an example to show how DataSets provide
transaction processing?
Let us assume we have a DataGrid that displays employee information. Every row
also has a delete button, which when you click will delete that row. On this
page we also have a Restore and Commit buttons. When you click the Restore
button you should be able to restore the data to its previous state. When you
click the Commit button you should be able to update the database with the
deletions made in the DataSet.
The code for Commit and Restore buttons is shown below.
private void
butRestore_Click(object sender, System.EventArgs e)
{
// Restore the data set to its original state.
dsContacts.RejectChanges();
// Refresh the data grid.
grdContacts.DataBind();
}
private void butCommit_Click(object sender, System.EventArgs e)
{
int intRows;
// Update the database from the data set.
intRows = adptContacts.Update(dsContacts);
// Save changes to state variable.
Session["dsContacts"] = dsContacts;
// Refresh the data grid.
grdContacts.DataBind();
}
The RejectChanges method in the
preceding butRestore_Click event procedure returns the data set to its state
before the row was deleted. The data set’s AcceptChanges method is the inverse
of RejectChanges—it resets the DataRowState property for all the changed rows
in a data set to Unchanged and removes any deleted rows.
The AcceptChanges method prevents the Update method from making those changes
in the database, however, because Update uses the rows’ DataRowState property
to determine which rows to modify in the database. For this reason, the
AcceptChanges method is useful only when you do not intend to update a database
from the data set.
What are the 3 types of transaction objects
available in ADO.NET?
As we have 3 types of database connections in ADO.NET, there are also 3
types of transaction objects:
SqlTransaction
OracleTransaction
OleDbTransaction
What are the steps involved in using a
transaction object in ADO.NET?
1.Open a database connection.
2.Create the transaction object using the database connection object’s
BeginTransaction method.
3.Create command objects to track with this transaction, assigning the
Transaction property of each command object to the name of the transaction
object created in step 2.
4.Execute the commands. Because the purpose of transaction processing is to
detect and correct errors before data is written to the database, this is
usually done as part of an error-handling structure.
5.Commit the changes to the database or restore the database state, depending
on the success of the commands.
Close the database connection.
What property of a transaction object
determines how concurrent changes to a database are handled?
IsolationLevel property of the transaction object is used to determine how
concurrent changes to a database are handled.
What are different isolation levels of a
transaction object in ADO.NET?
ReadUncommitted:Does not
lock the records being read. This means that an uncommitted change can be read
and then rolled back by another client, resulting in a local copy of a record
that is not consistent with what is stored in the database. This is called a
dirty read because the data is inconsistent.
Chaos:Behaves the same way as
ReadUncommitted, but checks the isolation level of other pending transactions
during a write operation so that transactions with more restrictive isolation
levels are not overwritten.
ReadCommitted:Locks the
records being read and immediately frees the lock as soon as the records have
been read. This prevents any changes from being read before they are committed,
but it does not prevent records from being added, deleted, or changed by other
clients during the transaction. This is the default isolation level.
RepeatableRead:Locks the
records being read and keeps the lock until the transaction completes. This
ensures that the data being read does not change during the transaction.
Serializable:Locks the entire
data set being read and keeps the lock until the transaction completes. This
ensures that the data and its order within the database do not change during
the transaction.
What is the default isolation level in a
transaction?
ReadCommitted
What is a Save Point in a transaction in
ADO.NET?
SqlConnection object provide one transaction capability that is unavailable for
OLE database connections: the ability to create save points within a
transaction. Save points let you restore the database state to a specific
position within the current transaction. To set a save point within a SQL
transaction, use the Save method as shown below.
TransactionObject.Save("FirstStep");
How do you restore a SQL transaction to a
specific save point?
To restore a SQL transaction to a save point, specify the name of the save
point in the Rollback method as shown below.
TransactionObject.Rollback("FirstStep");
User Controls-
What are ASP.NET Custom
controls?
Custom controls extend the tools available to Web developers. Using custom
controls, you can encapsulate key aspects of the visual interface and program
logic that you want to reuse throughout your application, or throughout your
organization.
What are the 3 types of custom controls in
ASP.NET?
Microsoft Visual Studio .NET provides three types of custom control for use on
Web forms.
1. Web user controls
These combine existing server and HTML controls by using the Visual Studio .NET
Designer to create functional units that encapsulate some aspect of the user
interface. User controls reside in content files, which must be included in the
project in which the controls are used.
2. Composite custom controls
These create new controls from existing server and HTML controls. Although
similar to user controls, composite controls are created in code rather than
visually, and therefore they can be compiled into an assembly (.dll), which can
be shared between multiple applications and used from the Toolbox in Visual
Studio .NET.
3. Rendered custom controls
These create entirely new controls by rendering HTML directly rather than using
composition. These controls are compiled and can be used from the Toolbox, just
like composite controls, but you must write extra code to handle tasks that are
performed automatically in composite controls.
What are the limitations of user controls in
ASP.NET?
As the user controls are not compiled into assemblies, they have the following
limitations:
1. A copy of the control must exist in
each Web application project in which the control is used.
2. User controls can’t be loaded in the
Visual Studio .NET Toolbox; instead, you must create them by dragging the
control from Solution Explorer to the Web form.
3. User control code is initialized after
the Web form loads, which means that user control property values are not
updated until after the Web form’s Load event.
What are the steps to follow for creating and
using a user control in a Web application?
1. Add a Web user control page (.ascx) to
your project.
2. Draw the visual interface of the
control in the designer.
3. Write code to create the control’s
properties, methods, and events.
4. Use the control on a Web form by
dragging it from Solution Explorer to the Web form on which you want to include
it.
5. Use the control from a Web form’s code
by declaring the control at the module level and then using the control’s
methods, properties, and events as needed within the Web form.
How do you identify user controls?
User controls are identified by their .ascx file extensions.
What is the base class from which user
controls derive?
User controls derive from System.Web.UI.UserControl base class. This base class
provides the base set of properties and methods you use to create the control.
What are the steps to follow to create
properties and methods for the user control that you can use from a Web form?
To create properties and methods for the user control that you can use from a
Web form, follow these steps:
1. Create the public property or method
that you want to make available on the containing Web form.
2. Write code to respond to events that
occur for the controls contained within the user control. These event
procedures do the bulk of the work for the user control.
3. If the property or method needs to
retain a setting between page displays, write code to save and restore settings
from the control’s ViewState.
What happens when you drag a user control
from solution explorer and drop it on a web form?
When you drag a user control from solution explorer and drop it on a web form,
Visual Studio .NET generates a @Register directive and HTML tags to create the
control on the Web form.
Custom Controls-
What are composite custom
controls?
Composite custom controls combine one or more server or HTML controls within a
single control class, which can be compiled along with other control classes to
create an assembly (.dll) that contains a custom control library. Once created,
the custom control library can be loaded into Visual Studio .NET and used in
the same way as the standard server and HTML controls.
Composite custom controls are functionally similar to user controls, but they
reside in their own assemblies, so you can share the same control among
multiple projects without having to copy the control to each project, as you
must do with user controls. However, composite controls are somewhat more
difficult to create because you can’t draw them visually using the Visual
Studio .NET Designer.
What are the steps to follow create and use a
custom control in a Web application?
1. Create a solution containing a custom
control project.
2. Add a Web application project to the
solution, and set it as the startup project. You will use the Web application
project to test the custom control during development.
3. Add a project reference from the Web
application to the custom control project, and add an HTML @Register directive
and control element to use the custom control on a Web form.
4. Create the custom control’s visual
interface by adding existing controls to it through the custom control’s
CreateChildControls method.
5. Add the properties, methods, and
events that the custom control provides.
6. Build and test the custom control.
In general what is the base class for every
composite custom control?
System.Web.UI.WebControls.WebControl
Which directive is used to add a custom
control to a Web form?
Register directive.
What are the 3 Register directive's
attributes?
TagPrefix
This name identifies the group that the user control belongs to. For example,
the tag prefix for ASP.NET server controls is “asp”. You use this prefix to
create a naming convention to organize your custom controls.
Namespace
This is the project name and namespace within the custom control assembly that
contains the controls to register. Microsoft Visual Basic .NET uses the project
name as an implicit namespace, so for controls written in Visual Basic .NET,
use the project name.
Assembly
This is the name of the assembly (.dll) containing the custom controls. The
control assembly must be referenced by the Web application. Referencing the
assembly maintains a copy of it in the Web application’s /bin directory.
What are the differences between User
Controls and Custom Controls?
1. User Controls are easy to create where
as Custom Controls are difficult to create.
2. User Controls cannot be compiled into
an assembly, where as Custom Controls can be compiled into an assembly.
3. User Controls cannot be added to tool
box, where as Custom controls can be added to the toolbox.
4. You need to have a copy of user
control in every project where you want to use it, where as this is not the
case with custom controls. You can install a single copy of the Web custom
control in the global assembly cache and share it between applications, which
makes maintenance easier.
5. User controls are used for reusing
existing user interface elements and code, but are not useful for developing
reusable components for multiple web applications.