AWP Unit 3,4 and 5
AWP Unit 3,4 and 5
Unit 3:
1) Exception Handling
->
**Exception Handling in C#**
```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`.
```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);
}
```
```csharp
public class MyCustomException: Exception
{
public MyCustomException(string message) : base(message) { }
}
```
```csharp
try
{
// Code that might throw an exception
}
catch (Exception ex)
{
Console.WriteLine("Exception caught: " + ex.Message);
throw; // Rethrow the same exception
}
```
```csharp
try
{
// Code that might throw an exception
}
catch (Exception ex) when (ex.Message.Contains("specific"))
{
Console.WriteLine("Caught a specific exception: " + ex.Message);
}
```
```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
}
```
```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);
}
```
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.
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.
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.
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
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.
Unit 5:
1) XML
->
https://www.youtube.com/watch?v=F7a_6r575RQ
3. XML Declaration:
- Syntax: `<?xml version="1.0"?>`
- Use: To declare the XML version and encoding.
4. Attribute:
- Syntax: `<tag attribute="value">content</tag>`
- Use: To add extra information to an element.
5. Comment:
- Syntax: `<!-- This is a comment -->`
- Use: To add comments that are ignored during data processing.
6. Entity Reference:
- Syntax: `<`, `>`, `&`, `"`, `'`, ` `
- Use: To represent special characters within content.
7. CDATA Section:
- Syntax: `<![CDATA[content]]>`
- Use: To include blocks of text that should be ignored by the parser.
8. XML Namespace:
- Syntax: `<tag xmlns="namespaceURI">content</tag>`
- Use: To avoid naming conflicts in XML documents.
9. Processing Instruction:
- Syntax: `<?target instruction?>`
- Use: To provide instructions to applications processing the XML.
12. Whitespace:
- Use: Whitespace between elements is ignored, allowing for proper
formatting.
2) Ajax
->
- Ajax stands for Asynchronous JavaScript And XML.
- Ajax provides a better user experience by making web applications more
responsive.
- Ajax allows for client-side events such as mouse movements and key presses
to be reacted to immediately.
- Implementing Ajax can be complex, but using ASP.NET's Ajax-enabled features
can simplify the process.
- Browser support can be a challenge when using Ajax.
- ASP.NET provides partial rendering support through the UpdatePanel control,
which allows for partial updates instead of full postbacks.
- JavaScript is the language used for Ajax implementation, but it can be difficult
to program correctly due to browser variations and loose language rules.
- The ScriptManager control is the brains of ASP.NET AJAX and needs to be
placed on the page to use ASP.NET AJAX.
- Partial refreshes are a key technique in Ajax web applications, allowing for
specific regions of a page to be updated without refreshing the entire page.
- The UpdatePanel control in ASP.NET allows for partial updates and intercepts
events that would normally trigger a full-page postback.
- The UpdateProgress control can be used with the UpdatePanel to show a
message or simulate a progress bar during time-consuming updates.
- The Timer control can be used to implement timed refreshes in Ajax
applications.
- The ASP.NET AJAX Control Toolkit is a collection of controls that use the
ASP.NET AJAX libraries to create sophisticated effects.
- The ASP.NET AJAX Control Toolkit is free, includes full source code, and
enhances standard ASP.NET web controls with extenders.
- The ASP.NET AJAX Control Toolkit can be installed by downloading it from the
official website and adding the controls to the Visual Studio Toolbox.
```html
<asp:Timer ID="Timer1" runat="server" Interval="5000"
OnTick="Timer1_Tick"></asp:Timer>
<asp:Label ID="lblTime" runat="server"></asp:Label>
```
In this example, the Timer control is set to refresh every 5 seconds (5000
milliseconds). When the Timer control triggers the Tick event, the code in the
Timer1_Tick method will be executed.
```csharp
protected void Timer1_Tick(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString();
}
```
In the Timer1_Tick method, we update the text of the lblTime label with the
current time. So, every 5 seconds, the label will be refreshed with the updated
time.
```html
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<!-- Content to be updated -->
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnUpdate" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<!-- Progress message or animated GIF -->
</ProgressTemplate>
</asp:UpdateProgress>
```
In this example, we have an UpdatePanel that contains the content we want to
update. We also have a button (btnUpdate) that triggers the update when clicked.
The AsyncPostBackTrigger specifies that the button click event should trigger an
asynchronous postback.
```javascript
function refreshContent() {
// Make an AJAX request to get updated content
var xhr = new XMLHttpRequest();
xhr.open("GET", "getUpdatedContent.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// Update the content on the page
document.getElementById("content").innerHTML = xhr.responseText;
}
};
xhr.send();
}
I hope this helps! Let me know if you have any further questions.
The ASP.NET AJAX Control Toolkit provides a wide range of controls that
leverage the power of AJAX to create rich and interactive user interfaces. These
controls are built on top of the ASP.NET AJAX framework, making it easy to
integrate them into existing ASP.NET web applications.
1. Free and Open-Source: The ASP.NET AJAX Control Toolkit is completely free
to use and comes with full source code. This allows developers to customize and
extend the controls according to their specific needs.
3. Rich Controls: The toolkit offers a wide range of controls that enable
developers to create sophisticated user interfaces. These controls include
sliders, calendars, autocomplete, accordions, tabs, modal popups, and many
more.
4. Easy Integration: The controls in the toolkit can be easily integrated into
existing ASP.NET web applications. They can be added to the Visual Studio
Toolbox, allowing developers to drag and drop them onto web forms.
5. Cross-Browser Compatibility: The controls in the toolkit are designed to work
seamlessly across different web browsers, ensuring a consistent user experience
for all users.
To use the ASP.NET AJAX Control Toolkit, you need to download and install it
from the official website or through NuGet package manager. Once installed, you
can add the controls to your web forms by dragging and dropping them from the
Toolbox.
Overall, the ASP.NET AJAX Control Toolkit provides a valuable set of controls
and extenders that enhance the functionality and user experience of ASP.NET
web applications. It is a popular choice among developers for building interactive
and responsive web interfaces.