0% found this document useful (0 votes)
52 views18 pages

AWP Unit 3 and 4

The document provides a comprehensive overview of exception handling in C# with 13 sections. It discusses what exceptions are, how to use try, catch, and finally blocks to handle exceptions, different exception types, throwing custom exceptions, best practices for exception handling, and more.

Uploaded by

harshit sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views18 pages

AWP Unit 3 and 4

The document provides a comprehensive overview of exception handling in C# with 13 sections. It discusses what exceptions are, how to use try, catch, and finally blocks to handle exceptions, different exception types, throwing custom exceptions, best practices for exception handling, and more.

Uploaded by

harshit sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

AWP

Unit 3:
1) Exception Handling
->
**Exception Handling in C#**

Exception handling is a critical aspect of C# programming, as it allows


developers to manage and recover from unexpected errors or issues that can
occur during program execution. Here are comprehensive notes on exception
handling in C#, along with examples:

**1. What Are Exceptions:**


- Exceptions are unexpected or abnormal events that can occur during program
execution, such as division by zero, accessing an out-of-bounds array element,
or a file not found error.
- C# provides a mechanism to catch and handle these exceptions, preventing
them from crashing the application.

**2. The `try`, `catch`, and `finally` Blocks:**


- Exception handling in C# is achieved using `try`, `catch`, and `finally` blocks.
- The `try` block encloses the code where exceptions might occur.
- The `catch` block is used to catch and handle exceptions.
- The `finally` block contains code that always executes, regardless of whether
an exception is thrown or not.

**3. Throwing Exceptions:**


- You can explicitly throw exceptions using the `throw` statement. For example:

```csharp
try
{
int result = 10 / 0; // Division by zero
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Exception caught: " + ex.Message);
}
```
**4. Exception Types:**
- C# provides a hierarchy of exception classes, with the base class being
`Exception`. Derived classes include `SystemException`, `ApplicationException`,
and more specialized exceptions like `DivideByZeroException`,
`FileNotFoundException`, and `ArgumentNullException`.

**5. Catching Specific Exceptions:**


- You can catch specific exceptions to handle them differently. For example:

```csharp
try
{
int[] numbers = { 1, 2, 3 };
int value = numbers[5]; // Accessing an out-of-bounds element
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Index out of bounds: " + ex.Message);
}
```

**6. The `Finally` Block:**


- The `finally` block is executed whether an exception is thrown or not. It's
typically used for cleanup code, like closing files or releasing resources.

**7. Custom Exceptions:**


- You can create custom exception classes by deriving from `Exception` to
handle application-specific errors. For example:

```csharp
public class MyCustomException: Exception
{
public MyCustomException(string message) : base(message) { }
}
```

**8. Rethrowing Exceptions:**


- You can rethrow exceptions to propagate them up the call stack. For example:

```csharp
try
{
// Code that might throw an exception
}
catch (Exception ex)
{
Console.WriteLine("Exception caught: " + ex.Message);
throw; // Rethrow the same exception
}
```

**9. Exception Filters (C# 6.0 and later):**


- Exception filters allow you to specify conditions under which a `catch` block
should execute. This helps you catch specific exceptions in different situations.

```csharp
try
{
// Code that might throw an exception
}
catch (Exception ex) when (ex.Message.Contains("specific"))
{
Console.WriteLine("Caught a specific exception: " + ex.Message);
}
```

**10. Using `try-catch` for Resource Cleanup:**


- You can use `try-catch` blocks for resource management, ensuring that
resources are properly disposed of even if an exception is thrown.

```csharp
FileStream file = null;
try
{
file = new FileStream("example.txt", FileMode.Open);
// Read or write data here
}
catch (IOException ex)
{
Console.WriteLine("IO Exception: " + ex.Message);
}
finally
{
file?.Close(); // Close the file in the finally block
}
```

**11. Multiple `catch` Blocks:**


- You can have multiple `catch` blocks to handle different exception types. They
are evaluated from top to bottom, and the first matching block is executed.

```csharp
try
{
// Code that might throw exceptions
}
catch (FileNotFoundException ex)
{
Console.WriteLine("File not found: " + ex.Message);
}
catch (IOException ex)
{
Console.WriteLine("IO Exception: " + ex.Message);
}
```

**12. Using `finally` for Cleanup:**


- The `finally` block is useful for releasing resources, closing files, or performing
other cleanup tasks, ensuring they occur regardless of exceptions.

**13. Best Practices:**


- Handle exceptions where you can provide meaningful error recovery or
display useful information to users.
- Log exceptions to track issues in production.
- Avoid catching and swallowing exceptions without any action or logging.

2) Session State
->
https://www.youtube.com/watch?v=WBYcSMwnC3Y&list=PLf2Wj8X3RbBTsxK3t
ahVBBHX8yvgPi_em&index=34
3) Application State
->
Using Application State
Application state allows you to store global objects that can be accessed by any
client. Application state is
based on the System.Web.HttpApplicationState class, which is provided on all
web pages through the built-in
Application object.
Application state is similar to session state. It supports the same type of objects,
retains information
on the server, and uses the same dictionary-based syntax. A common example
of using an application state is
a global counter that tracks the number of times an operation has been
performed by all the web application’s
clients.
For example, you could create a global.sax event handler that tracks the number
of sessions that have been
created or the number of requests that have been received into the application.
Or you can use similar logic in the
Page.Load event handler to track the number of times a given page has been
requested by various clients. Here’s
an example of the latter:
protected void Page_Load(Object sender, EventArgs e)
{
// Retrieve the current counter value.
int count = 0;
if (Application["HitCounterForOrderPage"] != null)
{
count = (int)Application["HitCounterForOrderPage"];
}
// Increment the counter.
count++;
// Store the current counter value.
Application["HitCounterForOrderPage"] = count;
lblCounter.Text = count.ToString();
}
Once again, application-state items are stored as objects, so you need to cast
them when you retrieve them
from the collection. Items in the application state never time out. They last until
the application or server is restarted
or the application domain refreshes itself (because of automatic process
recycling settings or an update to one of
the pages or components in the application).
Application state isn’t often used, because it’s generally inefficient. In the
previous example, the counter
would probably not keep an accurate count, particularly in times of heavy traffic.
For example, if two clients
requested the page at the same time, you could have a sequence of events like
this:
1. User A retrieves the current count (432).
2. User B retrieves the current count (432).
3. User A sets the current count to 433.
4. User B sets the current count to 433.
In other words, one request isn’t counted because two clients access the counter
at the same time. To
prevent this problem, you need to use the Lock() and Unlock() methods, which
explicitly allow only one client to
access the Application state collection at a time.
protected void Page_Load(Object sender, EventArgs e)
Unfortunately, all other clients requesting the page will be stalled until the
Application collection is
released. This can drastically reduce performance. Generally, frequently modified
values are poor candidates for
application state. Application state is rarely used in the .NET world because its
two most common uses
have been replaced by easier, more efficient methods:
• In the past, the application state was used to store application-wide constants,
such as a
database connection string. As you saw in Chapter 5, this type of constant can
be stored
on the web. config file, which is generally more flexible because you can change
it easily
without needing to hunt through web page code or recompile your application.

• Application state can also be used to store frequently used information that is
time--
consuming to create, such as a full product catalog that requires a database
lookup.
However, using an application state to store this kind of information raises all
sorts of
problems about how to check whether the data is valid and how to replace it
when
needed. It can also hamper performance if the product catalog is too large.

4) View State
->
The ViewState Collection
The ViewState property of the page provides the current view-state information.
This property provides an
instance of the StateBag collection class. The StateBag is a dictionary collection,
which means every item is stored
in a separate “slot” using a unique string name, which is also called the key
name.
For example, consider this code:
//this keyword refers to the current Page object. It's optional.
this.ViewState["Counter"] = 1;
This places the value 1 (or rather, an integer that contains the value 1) into the
ViewState collection and
gives it the descriptive name Counter. If currently no item has the name Counter,
a new item will be added
automatically. If an item is already stored under the name Counter, it will be
replaced.
When retrieving a value, you use the key name. You also need to cast the
retrieved value to the appropriate
data type by using the casting syntax you saw in Chapter 2 and Chapter 3. This
extra step is required because the
ViewState collection stores all items as basic objects, which allows it to handle
many different data types.
Here’s the code that retrieves the counter from the view state and converts it to
an integer:
int counter;
counter = (int)this.ViewState["Counter"];
■ Note ASP.NET provides many collections that use the same dictionary syntax.
These include the collections
you’ll use for session and application state, as well as those used for caching and
cookies. You’ll see several of these
collections in this chapter.
A View-State Example
The following example is a simple counter program that records the number of
times a button is clicked. Without
any kind of state management, the counter will be locked perpetually at 1. With
careful use of the view state, the
counter works as expected.
public partial class SimpleCounter: System.Web. UI.Page
{
protected void cmdIncrement_Click(object sender, EventArgs e)
{
int counter;
if (ViewState["Counter"] == null)
{
counter = 1;
}
else
{
counter = (int)ViewState["Counter"] + 1;
}
ViewState["Counter"] = counter;
lblCount.Text = "Counter: " + counter.ToString();
}
}

5) Cookies
->
Cookies provide another way to store information for later use. Cookies are small
files that are created in the web
browser’s memory (if they’re temporary) or on the client’s hard drive (if they’re
permanent). One advantage of
cookies is that they work transparently, without the user being aware that
information needs to be stored. They
also can be easily used by any page in your application and even be retained
between visits, which allows for
truly long-term storage. They suffer from some of the same drawbacks that affect
query strings—namely, they’re
limited to simple string information, and they’re easily accessible and readable if
the user finds and opens the
corresponding file. These factors make them a poor choice for complex or private
information or large amounts
of data.
Some users disable cookies on their browsers, which will cause problems for
web applications that require
them. Also, users might manually delete the cookie files stored on their hard
drives. But for the most part, cookies
are widely adopted and used extensively on many websites.
Before you can use cookies, you should import the System.Net namespace so
you can easily work with the
appropriate types:
using System.Net;
Cookies are fairly easy to use. Both the Request and Response objects (which
are provided through Page
properties) provide a Cookies collection. The important trick to remember is that
you retrieve cookies from the
Request object, and you set cookies by using the Response object.
To set a cookie, just create a new HttpCookie object. You can then fill it with
string information (using the
familiar dictionary pattern) and attach it to the current web response:
// Create the cookie object.
HttpCookie cookie = new HttpCookie("Preferences");
// Set a value in it.
cookie["LanguagePref"] = "English";
// Add another value.
cookie["Country"] = "US";
// Add it to the current web response.
Response.Cookies.Add(cookie);
A cookie added in this way will persist until the user closes the browser and will
be sent with every request.
To create a longer-lived cookie, you can set an expiration date:
// This cookie lives for one year.
cookie.Expires = DateTime.Now.AddYears(1);
You retrieve cookies by cookie name, using the Request.Cookies collection.
Here’s how you retrieve the
preceding cookie, which is named Preferences:
HttpCookie cookie = Request.Cookies["Preferences"];
This code won’t cause an exception if the cookie doesn’t exist. Instead, you’ll
simply get a null reference.
Before you attempt to retrieve any data from the cookie, you should test the
reference to make sure you actually
have the cookie:
string language;
if (cookie != null)
{
language = cookie["LanguagePref"];
}
The only way to remove a cookie is by replacing it with a cookie that has an
expiration date that has already
passed. This code demonstrates the technique:
HttpCookie cookie = new HttpCookie("Preferences");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
A Cookie Example
The next example shows a typical use of cookies to store a customer name
(Figure 8-8). To try this example, begin
by running the page, entering a name, and clicking the Create Cookie button.
Then close the browser, and request
the page again. The second time, the page will find the cookie, read the name,
and display a welcome message.
Here’s the code for this page:
public partial class CookieExample: System.Web.UI.Page
{
protected void Page_Load(Object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["Preferences"];
if (cookie == null)
{
lblWelcome.Text = "<b>Unknown Customer</b>";
}
else
{
lblWelcome.Text = "<b>Cookie Found.</b><br /><br />";
lblWelcome.Text += "Welcome, " + cookie["Name"];
}
}
protected void cmdStore_Click(Object sender, EventArgs e)
{
// Check for a cookie, and create a new one only if
// one doesn’t already exist.
HttpCookie cookie = Request.Cookies["Preferences"];
if (cookie == null)
{
cookie = new HttpCookie("Preferences");
}
cookie["Name"] = txtName.Text;
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
lblWelcome.Text = "<b>Cookie Created.</b><br /><br />";
lblWelcome.Text += "New Customer: " + cookie["Name"];
}
}

Unit 4:

1) ADO.NET
->
- ADO.NET is the technology that .NET applications use to interact with a
database.
- ADO.NET provides a set of objects that allow developers to connect to a
database, execute queries, and retrieve data.
- ADO.NET is a powerful tool for building data-driven applications, and it is widely
used in web development, desktop applications, and other types of software.
- ADO.NET is an essential part of the .NET framework, and it is an important skill
for any .NET developer to learn.
- ADO.NET supports a variety of databases, including SQL Server, Oracle,
MySQL, and more.
- ADO.NET includes several key objects, such as the Connection object,
Command object, DataReader object, and DataSet object.
- ADO.NET also includes support for working with XML data, and it provides tools
for building web services and other types of distributed applications.
- To use ADO.NET, you need to configure your database connection string and
create an instance of the Connection object.
- You can then use the Command object to execute queries and retrieve data,
and you can work with the DataReader object or the DataSet object to process
the results.
- ADO.NET provides a flexible and powerful way to work with data in .NET
applications, and it is an essential tool for building modern software.

2) ADO.NET Architecture
->
ADO.NET architecture consists of the following components:

1. Data Providers: ADO.NET provides a set of data providers that are used to
connect to different types of databases. These data providers include SQL
Server, Oracle, MySQL, and more.

2. Connection: The Connection object is used to establish a connection to the


database. It provides methods for opening and closing the connection, as well as
for managing transactions.

3. Command: The Command object is used to execute SQL statements or stored


procedures against the database. It provides methods for executing queries,
updating data, and retrieving data.

4. DataReader: The DataReader object is used to read data from the database. It
provides a fast, forward-only, read-only stream of data that is retrieved from the
database.

5. DataSet: The DataSet object is used to store data in memory. It provides a


disconnected, in-memory representation of the data that is retrieved from the
database.

6. DataAdapter: The DataAdapter object is used to fill a DataSet with data from
the database, and to update the database with changes made to the DataSet.

7. CommandBuilder: The CommandBuilder object is used to automatically


generate SQL statements for updating the database based on changes made to
a DataSet.

8. Transactions: ADO.NET provides support for transactions, which allow you to


group multiple database operations into a single atomic unit of work.

These components work together to provide a flexible and powerful way to work
with data in .NET applications.
3) Data Binding
->
https://www.youtube.com/watch?v=NXEIO_dmGL0&list=PLf2Wj8X3RbBTsxK3ta
hVBBHX8yvgPi_em&index=35

- Retrieving data using DataSet or DataReader for display in an HTML table is


traditionally repetitive and error-prone.
- ASP.NET offers a more efficient solution through data binding, simplifying the
process of formatting and displaying data.
- Data binding instructs a control where to find data and how to display it, letting
the control handle the presentation details.
- ASP.NET's data binding differs significantly from traditional data binding in
client/server applications.
- Traditional data binding creates a direct connection between data and
on-screen controls, but this isn't practical for web applications.
- Direct data binding limits scalability and flexibility and is not suitable for
maintaining a database connection over the Internet.
- ASP.NET data binding operates in one direction, moving data from a source
into a control on the web page.
- Changes in data within data-bound controls are not automatically reflected in
the database; updates must be managed explicitly.
- ASP.NET data binding is more flexible and allows precise control over data
presentation and formatting.
- Databinding controls like GridView and DetailsView offer extensive
customization options for data display.
- ASP.NET data binding enhances the flexibility and control developers have over
their web applications, making it a powerful tool for data presentation and
formatting.

4) Single Value Data Binding


->
- **Single-Value Data Binding:**
- Single-value data binding allows inserting variables, properties, or expressions
into a web page dynamically.
- It can be used to place information into a control property or as plain text
inside an HTML tag.
- It is not specific to ADO.NET and is often used for creating templates for rich
data controls.
**Example:**
```csharp
protected int TransactionCount;
protected void Page_Load(object sender, EventArgs e)
{
TransactionCount = 10;
this.DataBind();
}

<asp:Label id="lblDynamic" runat="server" Font-Size="X-Large">


There were <%# TransactionCount %> transactions today.
I see that you are using <%# Request.Browser.Browser %>.
</asp:Label>

5) Repeated-Value Data Binding


->
Using Repeated-Value Data Binding
Although using simple data binding is optional, repeated-value binding is so
useful that
almost every ASP.NET application will want to use it somewhere.
Repeated-value data binding works with the ASP.NET list controls and the rich
data
controls. To use repeated-value binding, you link one of these controls to a data
source
(such as a field in a data table). When you call DataBind(), the control
automatically
creates a full list by using all the corresponding values. This saves you from
writing code
that loops through the array or data table and manually adds elements to a
control.
ListBox, DropDownList, CheckBoxList, and RadioButtonList: These web controls
provide a list for a single field of information.
GridView, DetailsView, FormView, and ListView: These rich web controls allow
you
to provide repeating lists or grids that can display more than one field of
information at a
time. For example, if you bind one of these controls to a full-fledged table in a
DataSet,
you can display the values from multiple fields. These controls offer the most
powerful
and flexible options for data binding.

Using Repeated-Value Data Binding Example :


protected void Page_Load(Object sender, EventArgs e)
{
// Create and fill the collection.
List<string> fruit = new List<string>();
fruit.Add("Kiwi");
fruit.Add("Pear");
fruit.Add("Mango");
fruit.Add("Blueberry");
fruit.Add("Apricot");
fruit.Add("Banana");
fruit.Add("Peach");
fruit.Add("Plum");

Using Repeated-Value Data Binding Example :


// Define the binding for the list controls.
MyListBox.DataSource = fruit;
MyDropDownListBox.DataSource = fruit;
MyHtmlSelect.DataSource = fruit;
MyCheckBoxList.DataSource = fruit;
MyRadioButtonList.DataSource = fruit;
// Activate the binding.
this.DataBind();
}
make it in pointers without naming each pointers a unecessary name and if there
are many examples then only show one easy example

6) Grid View
->
GridView, DetailsView, and FormView
have the ability to display more than one field at a time, often in a table based
layout or
according to what you’ve defined. They also support higher-level features such
as
selecting, editing, and sorting.
The rich data controls include the following:
• GridView: The GridView is an all-purpose grid control for showing large tables
of
information. The GridView is the heavyweight of ASP.NET data controls.
• DetailsView: The DetailsView is ideal for showing a single record at a time, in a
table
that has one row per field. The DetailsView also supports editing.
• FormView: Like the DetailsView, the FormView shows a single record at a time
and
supports editing. The difference is that the FormView is based on templates,
which allow
you to combine fields in a flexible layout that doesn’t need to be table based.
• ListView: The ListView plays the same role as the GridView—it allows you to
show
multiple records. The difference is that the ListView is based on templates. As a
result,
using the ListView requires a bit more work and gives you slightly more layout
flexibility.

The GridView is an extremely flexible grid control that displays a multicolumn


table. Each record in your data source becomes a separate row in the grid. Each
field in the record becomes a separate column in the grid.
This functionality includes features for automatic paging, sorting, selecting, and
editing.
Here’s all you need to create a basic grid with one column for each field:
<asp:GridView ID = "GridView1" runat = "server" />
Once you’ve added this GridView tag to your page, you can fill it with data.
Here’s an example that performs
a query using the ADO.NET objects and binds the retrieved DataSet:

protected void Page_Load(object sender, EventArgs e)


{
// Define the ADO.NET objects.
string connectionString =
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
string selectSQL = "SELECT ProductID, ProductName, UnitPrice FROM
Products";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// Fill the DataSet.
DataSet ds = new DataSet();
adapter.Fill(ds, "Products");
// Perform the binding.
GridView1.DataSource = ds;
GridView1.DataBind();
}
GridView: Generating Columns with Visual Studio
select the GridView and click the ellipsis ( . . . ) next to the Columns property in
the Properties window. You’ll see a Fields dialog box that lets you add, remove,
and refine your columns

GridView: Generating Columns with Visual Studio


Formatting: How to format rows and data values Selecting: How to let users
select a row in the GridView and respond accordingly
Editing: How to let users commit record updates, inserts, and deletes
Sorting: How to dynamically reorder the GridView in response to clicks on a
column header
Paging: How to divide a large result set into multiple pages of data
Templates: How to take complete control of designing, formatting, and editing by
defining templates

7) Detail View and Form View


->
https://www.youtube.com/watch?v=fY83kbet0Sw&list=PLf2Wj8X3RbBTsxK3tahV
BBHX8yvgPi_em&index=42

You might also like