012 - AWT MATERIAL For Cs Students
012 - AWT MATERIAL For Cs Students
SEMESTER II
Core Course - VII –ADVANCED WEB TECHNOLOGY
UNIT - I
OVERVIEW OF ASP.NET - The .NET framework – Learning the.NET languages Data types –
Declaring variables - Scope and Accessibility- Variable operations- Object Based manipulation -
Conditional Structures - Loop Structures- Functions and Subroutines. Types, Objects and
Namespaces : The Basics about Classes- Value types and Reference types - Advanced class
programming - Understanding name spaces and assemblies - Setting up ASP.NET and IIS.
UNIT – II
DevelopingASP.NETApplications-ASP.NETApplications:ASP.NET Code behind- The Global.asax
application file - Understanding ASP.NET Classes- ASP.NET Configuration. Web Form
fundamentals: A simple page applet-Improving the currency converter- HTML control classes- The
page class- Accessing HTML server controls. Web controls: Web Control Classes –Auto Post Back
and Web Control events- Accessing web controls. Using Visual Studio.NET: Starting a Visual
Studio.NET Project- Web form Designer- Writing code- Visual studio.NET debugging. Validation and
Rich Controls: Validation- A simple Validation example- Understanding regular expressions- A
validated customer form. State management - Tracing, Logging, and Error Handling.
UNIT – III
Working with Data - Overview of ADO.NET - ADO.NET and data management- Characteristics of
ADO.NET-ADO.NET object model. ADO.NET data access : SQL basics– Select , Update, Insert,
Delete statements- Accessing data- Creating a connection- Using a command with a Data Reader -
Accessing Disconnected data - Selecting multiple tables – Updating Disconnected data. Data
binding: Single value Data Binding- Repeated value data binding- Data binding with data bases.
Data list – Data grid – Repeater – Files, Streams and Email – Using XML.
UNIT - IV
Web Services - Web services Architecture: Internet programming then and now- WSDL– SOAP-
Communicating with a web service-Web service discovery and UDDI. Creating Web services: Web
service basics- The Stock Quote web service – Documenting the web service- Testing the web
service- Web service Data types- ASP.NET intrinsic objects. Using web services: Consuming aweb
service- Using the proxy class- An example with Terra Service.
UNIT – V
Advanced ASP.NET - Component Based Programming: Creating a simple component – Properties
and state- Database components- Using COM components. Custom controls: User Controls-
Deriving Custom controls. Caching and Performance Tuning: Designing and scalability–
Profiling- Caching- Output caching- Data caching – Object Caching. Implementing security:
Determining security requirements- The ASP.NET security model- Forms authentication-
Windows authentication.
ADVANCED WEB TECHNOLOGY UNIT - I
OVERVIEW OF ASP.NET
ASP.NET is a web development platform, which provides a programming model, a comprehensive
software infrastructure and various services required to build up robust web applications for PC,
as well as mobile devices.
ASP.NET works on top of the HTTP protocol, and uses the HTTP commands and policies to set a
browser- to-server bilateral communication and cooperation.
ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled codes, written
using the extensible and reusable components or objects present in .Net framework. These codes
can use the entire hierarchy of classes in .Net framework.
The ASP.NET application codes can be written in any of the following languages:
C#
Visual Basic.Net
Jscript
J#
Page request This stage occurs before the lifecycle begins. When a page is requested by the
user, ASP.NET parses and compiles that page.
Start In this stage, page properties such as Request and response are set. It also
determines the Request type.
Initialization In this stage, each control's UniqueID property is set. Master page is applied to
the page.
Load During this phase, if page request is postback, control properties are loaded with
information.
Postback In this stage, event handler is called if page request is postback. After that, the
event Validate method of all validator controls is called.
handling
Rendering Before rendering, view state is saved for the page and all controls. During the
rendering stage, the page calls the Render method for each control, providing a
text writer that writes its output to the OutputStream object of the page's
Response property.
Unload At this stage the requested page has been fully rendered and is ready to
terminate.at this stage all properties are unloaded and cleanup is performed.
A requested page first loaded into the server memory after that processes and sent to the bowser.
At last it is unloaded from the server memory. ASP.NET provides methods and events at each stage
of the page lifecycle that we can use in our application. In the following table, we are tabled events.
ASP.NET Life Cycle Events
PreInit This event is raised after the start stage is complete and before the
initialization stage.
PreLoad This event is occurs before the post back data is loaded in the controls.
Load This event is raised for the page first time and then recursively for all child
controls.
Control events This event is used to handle specific control events such as Button control'
Click event.
PreRender This event occurs after the page object has created all controls that are
required in order to render the page.
PreRenderComplet This event occurs after each data bound control whose DataSourceID
e property is set calls its DataBind method.
SaveStateComplete It is raised after view state and control state have been saved for the page
and for all controls.
Render This is not an event; instead, at this stage of processing, the Page object calls
this method on each control.
Unload This event raised for each control and then for the page.
Fig: This diagram shows the components of the ASP.NET
The main purpose of Web Forms is to overcome the limitations of ASP and separate view
from the application logic.
Server Controls
The following table contains the server-side controls for the Web Forms.
PageIndexChanged,
SortCommand, paging, sorting, and formatting very
easily with this control.
UpdateCommand, ItemCreated,
ItemDataBound
DataList CancelCommand, EditCommand, It is used to create datalist that is
DeleteCommand, non- tabular and used to show data.
ItemCommand, SelectedIndexChanged,
UpdateCommand, ItemCreated,
ItemDataBound
Repeater ItemCommand, ItemCreated, It allows us to create a non-tabular
ItemDataBound type of format for data. You can
bind the data to template items,
which are like bits of HTML put
together in a specific repeating
format.
Controls Description
Name
Reset Button Resets all other HTML form elements on a form to a default value
Submit Automatically POSTs the form data to the specified page listed in the Action attribute
Button in the FORM tag
File Field Places a text field and a Browse button on a form and allows the user to select a file
name from their local machine when the Browse button is clicked
Passwor An input area on an HTML form, although any characters typed into this field are
d Field displayed as asterisks
CheckBox Gives the user a check box that they can select or clear
Radio Used two or more to a form, and allows the user to choose one of the controls
Butto
n
Table Allows you to present information in a tabular format
ListBox Displays a list of items to the user. You can set the size from two or more to specify
how many items you wish show. If there are more items than will fit within this limit,
a scroll bar is automatically added to this control.
Dropdown Displays a list of items to the user, but only one item at a time will appear. The user can
click a down arrow from the side of this control and a list of items will be displayed.
decimal 16 byte at least -7.9 * 10?28 - 7.9 * 1028, with at least 28-digit precision
operators
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise etc.
There are following types of operators to perform different types of operations in C# language.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operators
o Unary Operators
o Ternary Operators
o Misc Operators
Precedence of Operators in C#
The precedence of operator specifies that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right to left.
Let's understand the precedence by the example given below:
int data= 10+ 5*5
The "data" variable will contain 35 because * (multiplicative operator) is evaluated before +
(additive operator).
The precedence and associativity of C# operators is given below:
C# if-else
In C# programming, the if statement is used to test the condition. There are various types of if
statements in C#.
o if statement
o if-else statement
o nested if statement
o if-else-if ladder
C# IF Statement
The C# if statement tests the condition. It is executed if condition is true.
Syntax:
if(condition){
//code to be executed}
If Example
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 10;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
}
}
Output:
It is even number
IF-else Statement
The C# if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is
false 5. }
If-else Example
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 11;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
else
{
Console.WriteLine("It is odd number");
}
}
}
Output:
It is odd number
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
else
{
Console.WriteLine("It is odd number");
}
}
}
Output
Enter a number:11
It is odd number
:
Enter a number:12
It is even number
Output
C# If else-if Example
using System;
public class IfExample
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number to check grade:");
int num = Convert.ToInt32(Console.ReadLine());
C# switch
The C# switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement in C#.
Syntax:
switch(expression
){ case value1:
//code to be executed;
break;
case
value2:
//code to be executed;
break;
......
default:
//code to be executed if all cases are not matched;
break;
}
Switch Example
using System;
public class SwitchExample
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine());
switch (num)
{
case 10: Console.WriteLine("It is 10"); break;
case 20: Console.WriteLine("It is 20"); break;
case 30: Console.WriteLine("It is 30"); break;
default: Console.WriteLine("Not 10, 20 or 30"); break;
}
}
Output }
:
Enter a number:
10
It is 10
Output:
Enter a number:
55
Not 10, 20 or 30
C# For Loop
The C# for loop is used to iterate a part of the program several times. If the number of iteration is
fixed, it is recommended to use for loop than while or do-while loops.
The C# for loop is same as C/C++. We can initialize variable, check condition and
increment/decrement value.
Syntax:
for(initialization; condition; incr/decr){
//code to be executed
}
Flowchart:
C# Do-While Loop
The C# do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to use
do-while loop.
The C# do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed
}while(condition);
do-while Loop Example
Let's see a simple example of C# do-while loop to print the table of 1.
using System;
public class DoWhileExample
{
public static void Main(string[] args)
{
int i = 1;
do{
Console.WriteLine(i);
i++;
} while (i <= 10) ;
}
}
Output:
1
2
3
4
5
6
7
8
9
10
do{
int j = 1;
do{
Console.WriteLine(i+" "+j); j+
+;
} while (j <=
3) ; i++;
} while (i <= 3) ;
}
}
Output:
11
12
13
21
22
23
31
32
33
do{
Console.WriteLine("Infinitive do-while Loop");
} while(true);
}
}
Output
:
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
ctrl+c
C# Break Statement
The C# break is used to break loop or switch statement. It breaks the current flow of the program
at the given condition. In case of inner loop, it breaks only inner loop.
Syntax:
jump-statement;
break
; Flowchart:
C# Continue Statement
The C# continue statement is used to continue loop. It continues the current flow of the program
and skips the remaining code at specified condition. In case of inner loop, it continues only inner
loop.
Syntax:
1. jump-statement;
2. continue;
C# Continue Statement Example
1. using System;
2. public class
ContinueExample 3. {
4. public static void Main(string[]
args) 5. {
6. for(int i=1;i<=10;i++){
7. if(i==5){
8. continue;
9. }
10. Console.WriteLine(i);
11. }
12. }
13. }
Output
:
1
2
3
4
6
7
8
9
10
C# Continue Statement with Inner Loop
C# Continue Statement continues inner loop only if you use continue statement inside the inner loop.
1. using System;
2. public class
ContinueExample 3. {
4. public static void Main(string[]
args) 5. {
6. for(int i=1;i<=3;i++){
7. for(int j=1;j<=3;j++){
8. if(i==2&&j==2){
9. continue;
10. }
11. Console.WriteLine(i+" "+j);
12. }
13. }
14. }
15. }
Output
:
11
12
13
21
23
31
32
33
C# Goto Statement
The C# goto statement is also known jump statement. It is used to transfer control to the other
part of the program. It unconditionally jumps to the specified label.
It can be used to transfer control from deeply nested loop or switch case label.
Currently, it is avoided to use goto statement in C# because it makes the program
complex. C# Goto Statement Example
Let's see the simple example of goto statement in C#.
1. using System;
2. public class
GotoExample 3. {
4. public static void Main(string[]
args) 5. {
6. ineligible:
7. Console.WriteLine("You are not eligible to
vote!"); 8.
9. Console.WriteLine("Enter your age:\n");
10. int age = Convert.ToInt32(Console.ReadLine());
11. if (age < 18){
12. goto ineligible;
13. }
14. else
15. {
16. Console.WriteLine("You are eligible to vote!");
17. }
18. }
19. }
Output
:
You are not eligible to vote!
Enter your age:
11
You are not eligible to vote!
Enter your age:
5
You are not eligible to vote!
Enter your age:
26
You are eligible to vote!
C# Comments
The C# comments are statements that are not executed by the compiler. The comments in C#
programming can be used to provide explanation of the code, variable, method or class. By the help
of comments, you can hide the program code also.
There are two types of comments in C#.
o Single Line comment
o Multi Line
comment C# Single Line
Comment
The single line comment starts with // (double slash). Let's see an example of single line comment in C#.
1. using System;
2. public class
CommentExample 3. {
4. public static void Main(string[]
args) 5. {
6. int x = 10;//Here, x is a variable
7. Console.WriteLine(x);8.
}
9. }
Output:
10
C# Multi Line Comment
The C# multi line comment is used to comment multiple lines of code. It is surrounded by slash and
asterisk (/* */). Let's see an example of multi line comment in C#.
1. using System;
2. public class
CommentExample 3. {
4. public static void Main(string[]
args) 5. {
6. /* Let's declare and
7. print variable in C#. */
8. int x=20;
9. Console.WriteLine(x);
10. }
11. }
Output
:
20
A function is a procedure that returns a value to the caller. By "caller", we mean the place in the
ASP code where you invoke the procedure through a "function call". Functions are declared using
the Function statement and terminated with an End Function statement.
' A totally useless function to get the current date and time
Function TodaysDate
TodaysDate = Now()
End Function
Above, we have an example of a function definition that will return the current date and time
using the built-in function Now. By assigning a value to a variable which has the same name as
the function (TodaysDate), we return a value to the calling process. There is no return
statement like the PHP scripting language or in C programming.
This function can be declared anywhere in your web page and it will be made available for you
to call from within anywhere in the page. As we will see later, you can even place commonly
used procedures within a Server-Side Include page so that you don't have to write duplicate
procedures on multiple pages from your web site.
This function is totally useless because it's easier to just call the built-in function Now.
It is important to note that a procedure declaration like this will not do anything meaningful until
it is actually called. It simply declares a procedure which will do work when it is called.
Subroutines:
A subroutine is a procedure that does not return a value to the caller. Subroutines are declared
using the Sub statement and terminated with an End Sub statement.
' a subroutine to output today's date
Sub ShowDate
Response.Write(Now())
End Sub
The subroutine call above will output text that looks like "Today's Date is: Jan, 23 2004
06:43:12AM" when it is called. The location in the web page where this is output depends on
where the subroutine is called. You should call the subroutine at the exact point where you would
like it to output the text.
Unlike a function declaration, you are not allowed to assign a return value to the procedure name
(ShowDate). If you attempt to use a subroutine as a function, you will receive a runtime error.
The same is true when you try to use a function as a subroutine.
Types:
In ASP.Net framework, Data types play most importance role. A Variable must be declared with
the data type. There are mainly six Data Types in .NET Framework.
Integral Numbers:
Integral numbers are whole numbers that do not have decimal values. For instance: 1, 12353, and
–10. If you are familiar with computer programming, you’ll probably recognize the Byte, Short,
Integer, and Long data types. These are 8, 16, 32, and 64-bit integers respectively, and each
requires different amounts of memory. In other words, they can hold different ranges of
values. Such as the Integer data type can hold values from –2,147,483,648 to 2,147,483,647.
Example:
dim A, B as Integer
dim C as Integer
A=4
B= 6
C= A+B
Floating-Point Numbers:
Floating-point numbers are numbers with fractions or decimal points, such as 3.141592654 or –
0.45. The specific data types are Single (System.Single, 4 bytes), Double (System.Double, 8 bytes),
and Decimal (System.Decimal, 12 bytes).
Example:
dim X, Y as Single
dim Z as Single
X = 10.5
Y= 5.5
Z= X-Y
Strings:
The String data type that most programmers are familiar with is a class in VB.NET, rather than
a primitive. This enables you to create new instances, override, and inherit from a String,
which gives the programmer a lot of power when designing applications.
There is also the Char data type, which represents a single Unicode character because it is
Unicode, it can represent a lot more than just the alphanumeric characters.
Dates:
The DateTime data type can be in many formats: “5/6/01,” “Wednesday, July 4th, 2001,” or
“8:30:34 PM,” Such as- This provides you with great flexibility in representing your date valuesand
enables you to perform simple arithmetic (such as adding or subtracting days or hours) on your
values.
Booleans:
Booleans are simply true-or-false values, such as Yes / No, and so on. Although the Boolean
data type in VB.NET strictly uses true/false to represent data, you can easily convert it to the
other pairs of values.
Objects:
The Object data type is a generic type that’s used for a variable if no other type is specified.
Objects:
The Object data type is a generic type that’s used for a variable if no other type is specified.
Namespaces:
Namespaces is a “logical naming scheme for grouping related types“. What that means to us is
that all objects used in ASP.NET are grouped by type, which makes them easy to find and to
use. Imagine the .NET namespaces as a file cabinet.
Namespaces represent exactly the same concept. Like objects are grouped together, an
HTMLInputTextBox object is grouped in the same namespace as the HTMLAnchor object,
because they both represent HTML-user interface controls displayed to the user.
Example: To use a namespace in an ASP.NET page, you must use the Import directive.
<%@ Import Namespace="System.Data" %>
System Namespace:
The System namespace is the root namespace for the entire .NET Framework thus, it
contains all the basic and generic classes you’ll use in ASP.NET.These include the primitives
(integers, strings, and so on), as well as all of the other namespaces in .NET. Since it is the root
namespace.
3. The first step in the wizard responsible with the virtual directory creation is to choose an
alias (see Figure 3). The alias is the name a user will use in his URL to access the files in this
virtual directory. For example, if your alias is MyApp and your computer is MyServer, you can
request pages using URLs such as http://MyServer/MyApp/MyPage.aspx.
6. The final step in this wizard is to choose your permissions for the virtual directory (see
Figure 5). Usually, to host an ASP.NET application, read and execute permissions are enough
(the first two check boxes). Of course, in order to fulfill your needs you can choose other
permissions too.
Use Visual C# .NET to work with code-behind class files in an ASP.NET application5
This article describes how to develop .aspx pages that use code-behind class files in Microsoft
ASP.NET applications. The code samples in this article include the requirements for both code-
behind class files that are precompiled and code-behind class files that are compiled on demand.
Requirements
The following list outlines the recommended hardware, software, and network infrastructure that
you need:
Windows
.NET Framework
Internet Information Services (IIS)
This section demonstrates how to create a new ASP.NET web application that is named
CodeBehindSamples.
If you use code-behind class files with .aspx pages, you can separate the presentation code from the
core application logic (or code-behind). The code-behind class file is compiled so that it can be
created and used as an object. This allows access to its properties, its methods, and its event
handlers. For this to work, the .aspx page must specify to inherit from the code-behind base class.
To do this, use the Inherits attribute for the @
Page directive. The .aspx page inherits from the code-behind class, and the code-behind class
inherits from the Page class.
By default, if you are using Visual Studio .NET, a Codebehind attribute is added to the @ Page
directive. The .NET Framework does not actually use this attribute. Instead, Visual Studio .NET
uses this attribute to maintain a reference to the associated code- behind file for the .aspx page.
To demonstrate how Visual Studio .NET uses the Codebehind attribute, remove the
Codebehind attribute. You can no longer right-click the .aspx page and then
click View Code. This behavior occurs because Visual Studio .NET no longer contains a reference
for the class file it can use for the page. Remember that this is not how the .NET Framework uses
code-behind class files, but how Visual Studio .NET manages these project files.
If you precompile your code-behind classes into an assembly, you can use
the Inherits attribute to specify the class from which to inherit. In this scenario, you do not have to
include the actual code-behind class file when you deploy the application.
Instead, you must deploy the assembly and the .aspx page. You must put the assembly in the Bin
folder for the application when you deploy the application.
This section demonstrates how to create a new Web Form that uses the precompiled approach and
inherits from the code-behind class.
1. To add a new Web Form that is named InheritSample.aspx to your Visual Studio
.NET project, follow these steps:
1. In Solution Explorer, right-click the project node, click Add, and then click Add Web
Form.
2. In the Name box, type InheritSample.aspx, and then click Open.
2. Switch to Design view, and then add a Web Form Label control to the .aspx page.
3. Right-click the .aspx page, and then click View Code. The code-behind file opens in the
editor.
4. In the code-behind file, add the following code to the Page_Load event handler: C#
ASP.NET (C#)
<%@ Page language="c#" Codebehind="InheritSample.aspx.cs" AutoEventWireup="false"
Inherits="CodeBehindSamples.InheritSample" %>
In this example, the .aspx page inherits from the code-behind class that is
named InheritSamples in the CodeBehindSamples namespace. By default, a web application
that is created in Visual Studio .NET uses
a ProjectName.ClassName structure for the Inherits attribute value.
7. On the File menu, click Save All to save the Web Form and other associated project files.
8. In the Visual Studio .NET IDE, on the Build menu, click Build to build the project.
9. On the Project menu, click Show All Files.
10. In Solution Explorer, click to expand the Bin folder. The assembly that is generated when
you compile the project from the previous section (which
is CodeBehindSamples.dll in this example) appears in the Bin folder.
11. In Visual Studio .NET, right-click the page in Solution Explorer, and then
click View in Browser to run the code. The label is populated with the following value:
If your code-behind class files will be compiled on demand instead of precompiled, you must use
the Src attribute to specify the relative path of the code-behind class file. Make sure that you
include the actual class file when you use this method to deploy the application.
1. To add a new Web Form that is named SrcSample.aspx to your project in Visual
Studio .NET, follow these steps:
1. In Solution Explorer, right-click the project node, click Add, and then click Add Web
Form.
2. In the Name box, type SrcSample.aspx, and then click Open.
2. Switch to Design view, and then add a Web Form Label control to the .aspx page.
3. Right-click the .aspx page, and then click View Code. The code-behind file opens in the
editor.
4. In the code-behind file, add the following code to the Page_Load event:
C#
private void Page_Load(object sender, System.EventArgs e)
{
Label1.Text = "(Src): Page_Load fired!";
}
5. Switch from the code-behind class file to the .aspx page in the editor, and then switch to
HTML view.
6. At the top of the page, review the code for the @ Page directive. The code should be similar
to the following default code:
ASP.NET (C#)
<%@ Page language="c#" Codebehind="SrcSample.aspx.cs" AutoEventWireup="false"
Inherits="CodeBehindSamples.SrcSample"%>
7. To simplify this example, delete the Global.asax file from your project. This is only done in
this example to prevent additional errors that are related to the code-behind page of the
Global.asax file.
8. On the File menu, click Save All to save the Web Form and other associated project files.
9. If you followed the steps that are listed in the Use the Inherits attribute with
precompiled classes section, you must delete the assembly in the Bin directory of the
application before you follow the rest of the steps in this section.
10. To run the page, start Internet Explorer and then manually enter the URL of the page. Do
not select the View in Browser or the Browse With options from the Visual Studio .NET
IDE. Otherwise, if you are using Visual Studio .NET 2003, the code-behind page will be
precompiled into an assembly that is located in
the Bin directory by default. After viewing the page, you will receive an error message that
is similar as below:
This error occurs because the code-behind class file is not yet compiled, and you have not
yet included the Src attribute to reference the code-behind class file.
ASP.NET (C#)
<%@ Page language="c#" Codebehind="SrcSample.aspx.cs"
AutoEventWireup="false" Inherits="CodeBehindSamples.SrcSample" Src="SrcSample.aspx.cs"%>
The Src attribute is listed with the relative path of the code-behind class file (SrcSample.aspx.cs), and
the Inherits attribute value is set to
reference CodeBehindSamples.SrcSample.
12. On the File menu, click Save All to save the Web Form and other associated project files.
Remember, do not build the solution because you want the code-behind class file for this
sample to be compiled on demand.
13. To run the page, start Internet Explorer and then manually enter the URL of the page. Do
not select the View in Browser or the Browse With options from the Visual Studio .NET
IDE. Otherwise, if you are using Visual Studio .NET 2003, the code-behind page will be
precompiled into an assembly that is located in
the Bin directory by default. At this point, the page should be loaded in the browser, and the
label is populated with the following value:
The code-behind class file has now been compiled on demand and functions correctly.
What is Global.asax file: global.asax allows us to write event handlers that react to global events
in web applications.
How it gets called: Global.asax files are never called directly by the user, rather they are called
automatically in response to application events.
After you have added the global.asax file, you will find that Visual Studio has added
Application Event handlers:
Purpose of these application event handlers: To reach and handle any HttpApplication event.
If you want to know about HttpApplication events, see the MSDN article.
1. global.asax file aren't attached in the same way as the event handlers for ordinary
control events
2. Way to attach them is to use the recognized method name, i.e. for event handler
Application_OnEndRequest(), ASP.NET automatically calls this method when the
HttpApplication.EndRequest event occurs.
1) Events that occurs only under specific conditions, i.e. request / response related events.
This method is invoked some time after the application has been
shut down and the .NET garbage collector is about to reclaim the
6 Application_Disposed() memory it occupies. This point is too late to perform critical
cleanup, but you can use it as a last-ditch failsafe to verify that
critical resources are released.
So now it's time to write codes under these event handlers. Let's
Response.Write("Authenticating request...<br>");
HttpCookie cookie;
cookie = Request.Cookies[i];
if (cookie.Name == FormsAuthentication.FormsCookieName)
{
cookieFound = true;
authCookie = cookie;
break;
// If the cookie has been found, it means it has been issued from either
if (cookieFound)
// Extract the roles from the cookie, and assign to our current principal, which is at tached
to the
// HttpContext.
HttpContext.Current.User = princ;
else
// No cookie found, we can redirect to the Windows auth site if we want, or let it p ass
through so
// that the forms auth system redirects to the logon page for us.
}
If there is no error, see below the order in which application events are handled.
As per your requirement, you can write your codes to use these application events
handlers.
ASP.NET - Configuration
The behavior of an ASP.NET application is affected by different settings in the configuration files:
machine.config
web.config
The machine.config file contains default and the machine-specific value for all supported settings.
The machine settings are controlled by the system administrator and applications are generally
not given access to this file.
An application however, can override the default values by creating web.config files in its roots
folder. The web.config file is a subset of the machine.config file.
If the application contains child directories, it can define a web.config file for each folder. Scope of
each configuration file is determined in a hierarchical top-down manner.
Any web.config file can locally extend, restrict, or override any settings defined on the upper level.
Visual Studio generates a default web.config file for each project. An application can execute
without a web.config file, however, you cannot debug an application without a web.config file.
The following figure shows the Solution Explorer for the sample example used in the web services
tutorial:
In this application, there are two web.config files for two projects i.e., the web service and the web
site calling the web service.
The web.config file has the configuration element as the root node. Information inside this element
is grouped into two main areas: the configuration section-handler declaration area, and the
configuration section settings area.
The following code snippet shows the basic syntax of a configuration file:
<configuration>
<section2>
<s2Setting1 attribute1="attr1" />
</section2>
<system.web>
<authentication mode="Windows" />
</system.web>
</configuration>
Configuration Section Handler declarations
The configuration section handlers are contained within the <configSections> tags. Each
configuration handler specifies name of a configuration section, contained within the file, which
provides some configuration data. It has the following basic syntax:
<configSections>
<section />
<sectionGroup />
<remove />
<clear/>
</configSections>
Application Settings
The application settings allow storing application-wide name-value pairs for read-only access.
For example, you can define a custom application setting as:
<configuration>
<appSettings>
<add key="Application Name" value="MyApplication" />
</appSettings>
</configuration>
For example, you can also store the name of a book and its ISBN number:
<configuration>
<appSettings>
<add key="appISBN" value="0-273-68726-3" />
<add key="appBook" value="Corporate Finance" />
</appSettings>
</configuration>
Connection Strings
The connection strings show which database connection strings are available to the website. For
example:
<connectionStrings>
<add name="ASPDotNetStepByStepConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=E:\\projects\datacaching\ / datacaching\
App_Data\ASPDotNetStepByStep.mdb"
providerName="System.Data.OleDb" />
<add name="booksConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\ \databinding\App_Data\books.mdb"
providerName="System.Data.OleDb" />
</connectionStrings>
System.Web Element
The system.web element specifies the root element for the ASP.NET configuration section and
contains configuration elements that configure ASP.NET Web applications and control how the
applications behave.
It holds most of the configuration elements needed to be adjusted in common applications. The
basic syntax for the element is as given:
<system.web>
<anonymousIdentification>
<authentication>
<authorization>
<browserCaps>
<caching>
<clientTarget>
<compilation>
<customErrors>
<deployment>
<deviceFilters>
<globalization>
<healthMonitoring>
<hostingEnvironment>
<httpCookies>
<httpHandlers>
<httpModules>
<httpRuntime>
<identity>
<machineKey>
<membership>
<mobileControls>
<pages>
<processModel>
<profile>
<roleManager>
<securityPolicy>
<sessionPageState>
<sessionState>
<siteMap>
<trace>
<trust>
<urlMappings>
<webControls>
<webParts>
<webServices>
<xhtmlConformance>
</system.web>
The following table provides brief description of some of common sub elements of the
system.web element:
AnonymousIdentification
This is required to identify users who are not authenticated when authorization is required.
Authentication
It configures the authentication support. The basic syntax is as given:
<authentication mode="[Windows|Forms|Passport|None]">
<forms>...</forms>
<passport/>
</authentication>
Authorization
It configures the authorization support. The basic syntax is as given:
<authorization>
<allow .../>
<deny .../>
</authorization>
Caching
It Configures the cache settings. The basic syntax is as given:
<caching>
<cache>...</cache>
<outputCache>...</outputCache>
<outputCacheSettings>...</outputCacheSettings>
<sqlCacheDependency>...</sqlCacheDependency>
</caching>
CustomErrors
It defines custom error messages. The basic syntax is as given:
Deployment
It defines configuration settings used for deployment. The basic syntax is as follows:
<hostingEnvironment idleTimeout="HH:MM:SS"
shadowCopyBinAssemblies="true|false"
shutdownTimeout="number" urlMetadataSlidingExpiration="HH:MM:SS" />
Identity
It configures the identity of the application. The basic syntax is as given:
MachineKey
It configures keys to use for encryption and decryption of Forms authentication cookie data.
It also allows configuring a validation key that performs message authentication checks on view-
state data and forms authentication tickets. The basic syntax is:
Membership
This configures parameters of managing and authenticating user accounts. The basic syntax is:
Pages
It provides page-specific configurations. The basic syntax is:
<controls>...</controls>
<namespaces>...</namespaces>
<tagMapping>...</tagMapping>
<ignoreDeviceFilters>...</ignoreDeviceFilters>
</pages>
Profile
It configures user profile parameters. The basic syntax is:
<properties>...</properties>
<providers>...</providers>
</profile>
RoleManager
It configures settings for user roles. The basic syntax is:
<providers>...</providers>
</roleManager>
SecurityPolicy
It configures the security policy. The basic syntax is:
<securityPolicy>
<trustLevel />
</securityPolicy>
UrlMappings
It defines mappings to hide the original URL and provide a more user friendly URL. The basic
syntax is:
<urlMappings enabled="true|false">
<add.../>
<clear />
<remove.../>
</urlMappings>
WebControls
It provides the name of shared location for client scripts. The basic syntax is:
ASP.NET Applications:
When an ASP.Net application is launched, there are series of steps which are carried out. These
series of steps make up the lifecycle of the application.Let’s look at the various stages of a typical
page lifecycle of an ASP.Net Web Application.
1) Application Start – The life cycle of an ASP.NET application starts when a request is made by a
user. This request is to the Web server for the ASP.Net Application. This happens when the first
user normally goes to the home page for the application for the first time. During this time, there is
a method called Application_start which is executed by the web server. Usually, in this method, all
global variables are set to their default values.
2) Object creation – The next stage is the creation of the HttpContext, HttpRequest &
HttpResponse by the web server. The HttpContext is just the container for the HttpRequest and
HttpResponse objects. The HttpRequest object contains information about the current request,
including cookies and browser information. The HttpResponse object contains the response that is
sent to the client.
3) HttpApplication creation – This object is created by the web server. It is this object that is used
to process each subsequent request sent to the application. For example, let’s assume we have 2
web applications. One is a shopping cart application, and the other is a news website. For each
application, we would have 2 HttpApplication objects created. Any further requests to each website
would be processed by each HttpApplication respectively.
4) Dispose – This event is called before the application instance is destroyed. During this time, one
can use this method to manually release any unmanaged resources.
5) Application End – This is the final part of the application. In this part, the application is finally
unloaded from memory.
ASP.NET CodeBehind:
While our first example was fine, we unfortunately broke one of the coding principles of
ASP.NET: To separate markup and code. As you noticed, we added a scripting block (using
<% %>), where we wrote a line of C# code to use the label. While this is just fine for a small and
simple example like this, we would soon get a real mess with a bunch of C# code within an even
bigger amount of HTML code. If you throw in some JavaScript and some CSS as well, it will soon
become very chaotic to edit. That's why MS introduced CodeBehind, a technique which allows you
to completely separate markup (HTML, CSS
etc.) and code (C#, VB.NET etc.). So let's remove the script block (from <% to %>) and save the file.
As we talked about earlier, VS added a file called Default.aspx.cs. If you can't see it in the Solution
Explorer, then click the little plus sign left of the Default.aspx file. Open this file. Now, if you haven't
worked with .NET or another non-web programming language before, it might look a bit scary at
this point. It looks nothing like HTML. However, I will try to explain the different parts of the
content, and soon you will hopefully see that CodeBehind is a great tool to get a better overview of
your work. Here is a complete listing of the file as it looks right now:
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
publicpartialclass_Default:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
}
}
global.asax allows us to write event handlers that react to global events in web applications.
How it gets called: Global.asax files are never called directly by the user, rather they are called
automatically in response to application events.
<script runat="server">
Web Forms are web pages built on the ASP.NET Technology. It executes on the server and
generates output to the browser. It is compatible to any browser to any language supported
by .NET common language runtime. It is flexible and allows us to create and add custom controls.
We can use Visual Studio to create ASP.NET Web Forms. It is an IDE (Integrated Development
Environment) that allows us to drag and drop server controls to the web forms. It also allows us to
set properties, events and methods for the controls. To write business logic, we can choose
any .NET language like: Visual Basic or Visual C#.
Web Forms are made up of two components: the visual portion (the ASPX file), and the code
behind the form, which resides in a separate class file.
The HtmlControl class is the basis for all HTML server controls in Visual Basic. You don't use it
directly—instead, you use classes derived from it, or, more usually, classes derived from them.
Here are the classes derived from the HtmlControl class:
Object
Control
HtmlControl
HtmlContainerControl
HtmlImage
HtmlInputControl
The real purpose of the HtmlControl class is to provide a set of properties shared by all HTML
server controls:
Attributes— Holds all attribute name and value pairs for the server control's HTML element.
Disabled— Gets/sets whether the disabled attribute is included when an HTML control is
displayed in the browser.
Style— Gets all cascading style sheet (CSS) properties for the specified HTML server control.
TagName— Gets the element name that contains the runat=server attribute.
The classes derived from HtmlControl—in particular
the HtmlContainerControl and HtmlInputControl classes—form the basis of the HTML server
control classes.
The HtmlContainerControl Class
The HtmlContainerControl class defines the methods, properties, and events available to all
HTML server controls that can act as a container (in HTML terms, these elements all require a
closing tag). This class is the base class for
the HtmlTableCell, HtmlTable, HtmlTableRow, HtmlButton, HtmlForm, HtmlAnch or,
HtmlGenericControl, HtmlSelect, and HtmlTextArea classes, all of which share these properties:
InnerHtml— Gets/sets the content between the opening and closing tags of the HTML control.
InnerText— Gets/sets all text between the opening and closing tags of the specified HTML
control. (Note that unlike the InnerHtml property, InnerText supports automatic HTML
encoding and decoding.)
The HtmlInputControl Class
The HtmlInputControl class serves as the abstract base class that defines the methods, properties,
and events common to all HTML input controls, such as the <input type="text">, <input
type="submit">, and other elements that the user can enter data into.
The classes derived from the HtmlInputControl classarethe HtmlInputText,
HtmlInputButton, HtmlInputCheckBox, HtmlInputImage, Html InputHidden, HtmlInputFile,
and HtmlInputRadioButton classes, all of which share the following properties:
Name— Gets/sets a unique name for the input control.
Value— Gets/sets the contents of an input control.
Type— Gets the type of an input control.
The HtmlImage Class
This class creates an HTML <img> element, used to display images. Using the properties of this
class, you change the image displayed and the image size, as well as the alignment of the image
with respect to other HTML elements.
The Page Class:
HTML server controls are HTML elements that contain attributes to accessible at server side. By
default, HTML elements on an ASP.NET Web page are not available to the server. These
components are treated as simple text and pass through to the browser. We can convert an HTML
element to server control by adding a runat="server" and an id attribute to the component.
Example
<input id="UserName" type="text" size="50"runat="server" />
All the HTML Server controls can be accessed through the Request object.
Web Controls:
Web controls are basically HTML elements wrapped under easy to use scripting tags of ASP+ and
provide rich functionality in your FORMs or pages. Web controls range from simple text box to
advance girds and lists. Some of the controls like data grid can be bound to data sources much like
Visual Basic data bound controls.
This inheritance diagram includes some controls that you won't study in this chapter, including
the data controls, such as the GridView, DetailsView, and FormView, and the validation controls.
ASP.NET also adds two additional hidden input fields that are used to pass information back to the
server. This information consists of ID of the Control that raised the event and any additional
information if needed. These fields will empty initially as shown below,
ASP.NET generates the _doPostBack() function automatically, provided at least one control
on the page uses automatic postbacks.
Any Control that has its AutoPostBack Property set to true is connected to the
_doPostBack() function using the onclick or onchange attributes. These attributes indicate what
action should Browser take in response to the Client-Side javascript events onclick and onchange.
In other words, ASP.Net automatically changes a client-side javascript event into a server-
side ASP.Net event, using the _doPostBack() function as an intermediary.
Web control are processed at server side. This means that all the events generated by a control will
be handled at server end. The event handling has changed with ASP+.
publicsubmyeventhandler(sourceasObject,evtasEventArgs)
'accessyourwebcontrolshereand'manipulatetheirproperties end
sub
Here, source is the object which caused the event to be raised and evt is an object providing more
information about the event.
First, you'll create a .NET Core console application project. The project type comes with all the
template files you'll need, before you've even added anything!
If the start window is not open, choose File > Start Window.
After you apply the language and platform filters, choose the Console
Application template for .NET Core, and then choose Next.
4. In the Configure your new project window, type or enter get-started-debugging in the
Project name box. Then, choose Next.
5. On the Additional Information window, ensure the recommended target framework is
(.NET 6.0), and then choose Create.
Writing Code:
In Program.vb, replace all of the default code with the following code instead: Imports
System
Class ArrayExample
Dim letters As Char() = {"f"c, "r"c, "e"c, "d"c, " "c, "s"c, "m"c, "i"c, "t"c, "h"c} Dim name As
String = ""
Dim a As Integer() = New Integer(9) {}
letters(i)
a(i) = i + 1
SendMessage(name, a(i))
Next Console.ReadKey()
End Sub
Private Shared Sub SendMessage(ByVal name As String, ByVal msg As Integer) Console.WriteLine("Hello,
End Sub
End Class
1. Press F5 (Debug > Start Debugging) or select the green Start Debugging button in the
Debug Toolbar.
F5 starts the app with the debugger attached to the app process, but right now we haven't
done anything special to examine the code. So the app just loads and you see the console
output.
sm! Count to 7
Hello, fred smi! Count to 8 Hello,
smith! Count to 10
2.Stop the debugger by pressing (Shift + F5) or select the red Stop Debugging button in the
Debug Toolbar.
3.In the console window, press a key to close the console window.
An important aspect of creating ASP.NET Web pages for user input is to be able to check that
the information users enter is valid. ASP.NET provides a set of validation controls that provide an
easy-to-use but powerful way to check for errors and, if necessary, display messages to the user.
Control
Checks that the user enters a value that falls between two values
RangeValidator
One validation control will validate only one input control but multiple validate control can be
assigned to a input control.
Rich Controls:
ASP.NET provides large set of controls. These controls are divided into different categories,
depends upon their functionalities. The followings control comes under the rich controls
category.
FileUpload control
Calendar control
AdRotator control
MultiView control
Wizard control
Validation:
ASP.NET validation controls validate the data entered by the user. If the data does not pass validation, it will
display an error message to the user.
CompareValidator: This validator validates the value of one input with the value of another input.
ControlToValidate, ControlToComapre, ValueToCompare and ErrorMessage are the properties of
CompareValidator.
RangeValidator: This validator determines whether the values entered by the users fall between
two values. ControlToValidate, MaximumValue, MinimumValue and ErrorMessage are properties of
RangeValidator.
CustomValidator: This validator allows the user to write a method to handle the validation of the
value entered. ControlToValidate, ClientValidationFunction, ErrorMessage and ServerValidate
event are properties of the CustomValidator.
RegularExpressionValidator: This validator ensures that the value of an input control matches a
specified pattern. ControlToValidate, ValidationExpression and ErrorMessage are properties of the
RegularExpressionValidator.
ValidationSummary: This validator displays a report of all validation errors that occurred on a web
page.
Regular expressions provide a powerful, flexible, and efficient method for processing text. The
extensive pattern-matching notation of regular expressions enables you to quickly parse large
amounts of text to:
The centerpiece of text processing with regular expressions is the regular expression engine, which
is represented by the System.Text.RegularExpressions.Regex object in .NET. At a minimum,
processing text using regular expressions requires that the regular expression engine be provided
with the following two items of information:
In .NET, regular expression patterns are defined by a special syntax or language, which is
compatible with Perl 5 regular expressions and adds some additional features such as right-
to-left matching. For more information, see Regular Expression Language - Quick Reference.
State management:
Whenever we use Client-Side State Management, the state related information will directly get
stored on the client-side. That specific information will travel back and communicate
with every request generated by the user then afterwards provides responses after server- side
communication.
Server-Side State Management is different from Client-Side State Management but the operations
and working is somewhat the same in functionality. In Server-Side State Management all the
information is stored in the user memory. Due to this functionality there is more secure domains at
the server side in comparison to Client-Side State Management.
View State
Hidden field
Cookies
Control State
Query Strings
Server-side | Technique
Session State
Application State
Tracing:
The other useful tool provided by ASP.NET for debugging is the trace feature. Tracing allows you,
through a simple configuration setting or page-level attribute, to have ASP.NET write a whole host
of information about the currently executing request to the page or to a trace log. This information
includes the SessionID; the time, type, and status code of the request; timing information for events
such as Init, PreRender, SaveViewState, and Render; a Control Tree of all controls in the page; and
the contents of the Cookies collection, the
HTTP Headers, the QueryString collection (if any QueryString values were passed), the Form
collection (if any form fields were passed), and the ServerVariables collection.
Essentially, tracing allows you to automatically write out the contents of all collections exposed by
the classic ASP Request object, plus some really useful additional information. This allows you to
examine a great deal of information about a request on a single page, which can assist greatly in
debugging.
More importantly, you can also write to the trace output using the Trace.Write and Trace.Warn
methods, which are exposed by the Trace property of the Page class. These methods can now be
used in place of Response.Write when you determine the value of a variable on a page at a certain
point in page execution or write out a notification that a certain point in the page has been hit. With
Trace.Write or Trace.Warn, once you've disabled tracing, you can leave the statements in your code
and you don't have to worry about anyone seeing the output. If you've ever deployed a page to
production without removing or commenting out your Response.Write statements used for
debugging, you'll be grateful for this feature.
Page-Level Tracing
Enabling tracing at the page level is very simple. Simply add the Trace attribute to the @ Page
directive and set its value to True, as shown in the following code snippet:
This provides a quick and easy way to get an overview of what's going on for a given page. The
output from a page with tracing enabled looks similar to Figure 10-8.
Page-level tracing
One downside to enabling tracing at the page level is that if you use it with many pages, it's more
work to add and remove the Trace attribute for each page (or to set the attributes to False). This
can also make it more likely that you'll forget one and end up with trace information being written
out in a production application. Not what you want.
Application-Level Tracing
ASP.NET provides the ability to enable tracing at the application level throughthe
<trace> element in web.config. Application-level tracing makes it possible to disable tracing in a
single location in your application and makes it easier to enable tracing for multiple pages. Example
10-8 shows a web.config file with tracing enabled at the application level.
Logging:
ASP.NET Core has built-in support for logging, and allows developers to easily leverage their
preferred logging framework’s functionality as well. Implementing logging in your application
requires a minimal amount of setup code. Once this is in place, logging can be added wherever it is
desired.
Error Handling:
The goal of error handling (also known as exception handling) is quite simple: to prevent
exceptions or errors thrown during the execution of an application request from reaching users.
Ideally, users should not know that an exception occurred, or they should at least be provided with
an informative message that tells them what they can do to resolve the problem. ASP.NET provides
three techniques for achieving this goal:
Allow you to assign one or more error pages to be displayed when an exception occurs.
Page_Error and Application_Error events
Writing event handlers for either or both of these events allows you to catch and handle
exceptions at the page or application level.
Structured exception handling
New to Visual Basic .NET, and also available in C#, this type of exception handling allows
exceptions to be caught and handled in particular blocks of code.
These three techniques provide broadest (custom error pages, which can handle exceptions from
any page in the application) to narrowest (structured exception handling, which handles
exceptions for a specific block of code) coverage for handling application
exceptions. Figure 10-1 illustrates the relationship of these exception handling techniques to both
the exception (shown at the center) and the user, who you're trying to prevent from encountering
the exception.
Exception handling techniques
The following sections describe these techniques and explain how they fit into an ASP.NET
application. Note that you can use all three techniques together, individually, or in whatever
combination you like. Using all three techniques in combination would provide broad coverage for
most exceptions and more robust specific exceptions handling, but at the cost of maintaining your
exception-handling logic in more places.
UNIT III
Overview of ADO.NET
ADO.NET Introduction
It is a module of .Net Framework which is used to establish connection between application and
data sources. Data sources can be such as SQL Server and XML. ADO.NET consists of classes that
can be used to connect, retrieve, insert and delete data.
All the ADO.NET classes are located into System.Data.dll and integrated with XML classes located
into System.Xml.dll.
ADO.NET has two main components that are used for accessing and manipulating data are the .NET
Framework data provider and the DataSet.
These are the components that are designed for data manipulation and fast access to data. It
provides various objects such as Connection, Command, DataReader and DataAdapter that are
used to perform database operations. We will have a detailed discussion about Data Providers in
new topic.
The DataSet
It is used to access data independently from any data resource. DataSet contains a collection of one or more
DataTable objects of data. The following diagram shows the relationship between .NET Framework
Properties Descripti
on
CaseSensitive Indicates whether string comparisons within the data tables are case-
sensitive.
Events Gets the list of event handlers that are attached to this component.
ExtendedProperties Gets the collection of customized user information associated with the
DataSet.
Locale Gets or sets the locale information used to compare strings within the
table.
Prefix Gets or sets an XML prefix that aliases the namespace of the DataSet.
The following table shows some important methods of the DataSet class:
Method Descripti
s on
Load(IDataReader, LoadOption, DataTable[]) Fills a DataSet with values from a data source
using the supplied IDataReader, using an array
of DataTable instances to supply the schema
and namespace information.
Load(IDataReader, LoadOption, String[]) Fills a DataSet with values from a data source
using the supplied IDataReader, using an
array of strings to supply the names for the
tables within the DataSet.
Merge() Merges the data with data from another
DataSet. This method has different overloaded
forms.
ReadXML() Reads an XML schema and data into the DataSet.
This method has different overloaded forms.
RejectChanges Rolls back all changes made since the last call
to AcceptChanges.
Properties Descripti
on
PrimaryKey Gets or sets an array of columns as the primary key for the table.
The following table shows some important methods of the DataTable class:
Method Descripti
s on
GetChanges Returns a copy of the DataTable with all changes made since the
AcceptChanges method was called.
LoadDataRow Finds and updates a specific row, or creates a new one, if not found any.
RejectChanges Rolls back all changes made since the last call to AcceptChanges.
Reset Resets the table to its original state.
Properties Descripti
on
The following table shows some important methods of the DataRow class:
Method Descripti
s on
AcceptChanges Accepts all changes made since this method was called.
Example
So far, we have used tables and databases already existing in our computer. In this example, we
will create a table, add column, rows and data into it and display the table using a GridView object.
The source file code is as given:
<head runat="server">
<title>
Untitled
Page
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
The code behind file is as given:
namespace createdatabase
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = CreateDataSet();
GridView1.DataSource =
ds.Tables["Student"];
GridView1.DataBind();
}
}
// adding columns
AddNewColumn(Students, "System.Int32", "StudentID");
AddNewColumn(Students, "System.String", "StudentName");
AddNewColumn(Students, "System.String", "StudentCity");
// adding rows
AddNewRow(Students, 1, "M H Kabir", "Kolkata");
AddNewRow(Students, 1, "Shreya Sharma", "Delhi");
AddNewRow(Students, 1, "Rini Mukherjee",
"Hyderabad"); AddNewRow(Students, 1, "Sunil
Dubey", "Bikaner"); AddNewRow(Students, 1, "Rajat
Mishra", "Patna");
return Students;
}
}
}
}
When you execute the program, observe the following:
The application first creates a data set and binds it with the grid view control using the
DataBind() method of the GridView control.
The Createdataset() method is a user defined function, which creates a new DataSet object
and then calls another user defined method CreateStudentTable() to create the table and
add it to the Tables collection of the data set.
The CreateStudentTable() method calls the user defined methods AddNewColumn() and
AddNewRow() to create the columns and rows of the table as well as to add data to the
rows.
When the page is executed, it returns the rows of the table as shown:
Characteristics Of ADO.NET
• Bulk copying of data from a data source to another data source is a new feature added to
ADO.NET 2.0. Bulk copy classes provides the fastest way to transfer set of data from once
source to the other. Each ADO.NET data provider provides bulk copy classes. For example,
in SQL .NET data provider, the bulk copy operation is handled by SqlBulkCopy class, which
can read a DataSet, DataTable, DataReader, or XML objects.
2. Batch Update
• Batch update can provide a huge improvement in the performance by making just one
round trip to the server for multiple batch updates, instead of several trips if the database
server supports the batch update feature. The UpdateBatchSize property provides the
number of rows to be updated in a batch. This value can be set up to the limit of decimal.
3. Data Paging
• Now command object has a new execute method called ExecutePageReader. This method
takes three parameters - CommandBehavior, startIndex, and pageSize. So if we want to get
rows from 101 - 200, We can simply call this method with start index as 101 and page size
as 100.
4. Connection Details
• Now you can get more details about a connection by setting Connection's StatisticsEnabled
property to True. The Connection object provides two new methods - RetrieveStatistics
and ResetStatistics. The RetrieveStatistics method returns a HashTable object filled with
the information about the connection such as data transferred, user details, curser details,
buffer information and transactions.
5. DataSet.RemotingFormat Property
• In previous version of ADO.NET, only DataSet had Load and Save methods. The Load
method can load data from objects such as XML into a DataSet object and Save method
saves the data to a persistent media. Now DataTable also supports these two methods.
• We can also load a DataReader object into a DataTable by using the Load method.
7. New Data Controls
• This class provides a list of available data providers on a machine. We can use this class
and its members to find out the best suited data provider for our database when writing a
database independent applications.
9. Customized Data Provider
• By providing the factory classes now ADO.NET extends its support to custom data
provider. Now we don't have to write a data provider dependent code. We use the base
classes of data provider and let the connection string does the trick for us.
10. DataReader's New Execute Methods
• Now command object supports more execute methods. Besides old ExecuteNonQuery,
ExecuteReader, ExecuteScaler, and ExecuteXmlReader, the new execute methods are
ExecutePageReader, ExecuteResultSet, and ExecuteRow.
The goal of ADO.NET is to provide a bridge between your objects in ASP.NET and your back-end
database. ADO.NET provides an object-oriented view into the database, encapsulating many of the
database properties and relationships within ADO.NET objects. Further, and in many ways most
important, the ADO.NET objects encapsulate and hide the details of database access; your objects
can interact with ADO.NET objects without you knowing or worrying about the details of how the
data is moved to and from the database.
An overview of the ADO.NET architecture is shown in Figure 10-1. We will return to the aspects of
this figure throughout the chapter.
A .NET Data Provider is responsible for providing and maintaining the connection
to the database.
Following are the various .NET Data Providers:
o This is the object that allows you to establish a connection with the data source.
o Depending on the actual .NET Data Provider involved, connection objects
automatically pool physical databases connections for you.
o Examples of connection objects are OleDbConnection, SqlConnection,
OracleConnection and so on.
B. Command:
o This object represents an executable command on the underlying data source. The
command may or may not return any results. These commands can be used to
manipulate existing data.
o In addition, the commands can be used to manipulate underlying table structures.
o Examples of command objects are SqlCommand, OracleCommand and so on. A
Command needs to be able to accept parameters. The Parameter object of
ADO.NET allows commands to be more flexible and accept input values and act
accordingly.
C. Data Reader:
o This object is designed to help you retrieve and examine the rows returned by the
query as quickly as possible.
o DataReader object examines the results of a query one row at a time. When you
move forward to the next row, the contents of the previous row are discarded.
o The DataReader doesn’t support updating. The data returned by the DataReader is
read- only. Because the DataReader object supports such a minimal set of features,
it is extremely fast and lightweight.
o The disadvantage of using a DataReader object is that it requires an open
database connection and increases network activity.
D. DataAdapter:
o This object acts a gateway between the disconnected and connected flavours of
ADO.NET. The architecture of ADO.NET, in which connection must be opened to
access the data retrieved from the database is called as connected architecture
whereas as in a disconnected architecture data retrieved from database can be
accessed by holding it in a memory with the help of DataSet object even when the
connection is closed.
o Examples of DataAdapters are SqlDataAdapter, OracleDataAdapter and so on. It
has commands like Select, Insert, Update and Delete .
o Select command is used to retrieve data from the database and insert, update and
delete commands are used to send changes to the data in dataset to database.
DataSet :
It is an in-memory cache of data retrieved from the data source. Data is organized into
multiple tables using DataTable objects, tables can be related using DataRelation objects
and data integrity can be enforced using the constraint objects like UnqueConstraint and
ForeignKeyConstraint.
DataSet are also fully XML-featured. They contain methods such as GetXML and
WriteXML that respectively produce and comsume XML data easily.
The DataSet object provides a consistent programming model that works with all the
current models of data storage: flat, relational and hierarchial.
Another feature of DataSet is that it tracks changes that are made to the data it holds
before updating the source data.
Record Navigation
Recording navigation is nothing but the moving of control across the database to view the
record. Generally navigation in any database is possible with the four operations they are,
move next, move previous, mover first and move last.
But we also need to check that inc does not go past zero, which is the first record in the
DataSet. Here's the code to add to your btnPrevious
This new If Statement now checks to see if inc is equal to minus 1, and displays a message if it
does. It also checks if inc is equal to zero, and displays the First Record message box.
(ii) Moving to the Last Record in the DataSet
To jump to the last record in the DataSet, you only need to know how many records have been
loaded into the DataSet - the MaxRows variable in our code. You can then set the inc counter to
that value, but minus 1. Here's the code to add to your btnLast:
If inc <> MaxRows - 1 Then inc = MaxRows
- 1 NavigateRecords()
End If
The reason we're saying MaxRows - 1 is that the row count might be 5, say, but the first record
in the DataSet starts at zero. So the total number of records would be zero to 4. Inside of the If
Statement, we're setting the inc counter to MaxRows - 1, then calling the NavigateRecords()
subroutine.
That's all we need to do. So run your program. Click the Last button, and you should see the last
record displayed in your textboxes.
(iii) Moving to the First Record in the DataSet
Moving to the first record is fairly straightforward. We only need to set the inc counter to zero, if
it's not already at that value. Then call the Sub:
If inc <> 0 Then inc = 0
NavigateRecords() End If
Add the code to your btnFirst. Run your program and test out all of your buttons. You should be
able to move through the names in the database, and jump to the first and last records.
As yet, though, we don't have a way to add new records, to update records, or to delete them. Let's do that
next.
Change the Text properties of the buttons to "Add New Record ", "Commit Changes", "Update
Record ", "Delete Record", and "Clear/Cancel". Your form might look as depicted in figure 9.1.
Updating record
To reference a particular column (item) in a row of the DataSet, the code is this:
ds.Tables("AddressBook").Rows(2).Item(1)
This will retrieve the data available from Item 1 on Row 2. You can also
set a value with the following syntax
ds.Tables("AddressBook").Rows(2).Item(1) = "Jane"
Now Item 1 Row 2 will consist of text "Jane". This will not affect the database. The alterations will
happen only in DataSet. To demonstrate this, enter the code to your btnUpdate
ds.Tables("AddressBook").Rows(inc).Item(1) = txtFirstName.Text
ds.Tables("AddressBook").Rows(inc).Item(2) = txtSurname.Text
MsgBox("Data updated")
Execute your application, and click the Next Record button to move to the first record. "John"
should be displayed in your first textbox, and "Smith" in the second textbox. Click inside the
textboxes and change "John" to "Joan" and "Smith" to "Smithy". Now you can click your Update
Record button. Move to the next record by clicking your Next Record button, and then move
back to the first record. You should see that the first record is now "Joan Smithy".
Close the application and run it again. Click the Next Record button to move to the first record.
It will still be "John Smith". The data you updated has been lost: it is because
Changes are made to the DataSet, and NOT to the Database
You require some extra code In order to update the database,.
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("AddressBook").Rows(inc).Item(1) = txtFirstName.Text
ds.Tables("AddressBook").Rows(inc).Item(2) = txtSurname.Text
To update the database itself, you need something called a Command Builder. The Command
Builder will build a SQL string for you. In between round brackets, you type the name of your
Data Adapter, da in our case. The command builder is then stored in a variable, which we have
called cb.
The second new line is where the action is:
da.Update(ds, "AddressBook")
The da variable is holding our Data Adapter. One of the methods of the Data Adapter is Update.
In between the round brackets, you need the name of your DataSet (ds, for us). The AddressBook
part is optional. It's what we've called our DataSet, and is here to avoid any confusion.
But the Data Adapter will then contact the database. Because we have a Command Builder, the
Data Adapter can then update your database with the values from the DataSet.
Without the Command Builder, though, the Data Adapter can't do it's job. Try this. Comment out
the Command Builder line (put a single quote before the D of Dim). Run your program again, and
then try and update a record. You'll get this error message as shown in figure .
Error Message
The error is because you have not got a command builder - a Valid Update Command. Delete the
comment from your Command Builder line and the error message goes away. You should now be
able to make changes to the database itself (as long as the Access database isn't Read Only).
Try it out. Run your program, and change one of the records. Click the Update button. Then close the
program
down, and load it up again. You should see your new changes displayed in the textboxes.
Adding a new record
Adding a new record is slightly more complex. First, you have to add a new Row to the DataSet,
then commit the new Row to the Database.
But the Add New Record button on our form is quite simple. The only thing it does is to switch
off other buttons, and clear the textboxes, ready for a new entry. Here's the code for your Add
New Record button:
btnCommit.Enabled = True btnAddNew.Enabled
= False btnUpdate.Enabled = False
btnDelete.Enabled = False txtFirstName.Clear()
txtSurname.Clear()
So three buttons are switched off when the Add New Record button is clicked, and one is
switched on. The button that gets switched on is the Commit Changes button. The Enabled
property of btnCommit gets set to True. But, for this to work, you need to set it to False when
the form loads. So return to your Form. Click btnCommit to select it. Then locate the Enabled
Property in the Properties box. Set it to False. When the Form starts up, the button will be
switched off.
The Clear/Cancel button can be used to switch it back on again. So add this code to your btnClear:
= True inc = 0
NavigateRecords()
We're switching the Commit Changes button off, and the other three back on. The other two lines
just make sure that we display the first record again, after the Cancel button is clicked. Otherwise
the textboxes will all be blank.
To add a new record to the database, we'll use the Commit Changes button. So double click
your
btnCommit to access its code. Add the following:
If inc <> -1 Then
Dim cb As New OleDb.OleDbCommandBuilder(da) Dim dsNewRow As DataRow
The code is somewhat longer than usual, but we'll go through it.
The first line is an If Statement. We're just checking that there is a valid record to add. If there's
not, the inc variable will be on minus 1. Inside of the If Statement, we first set up a Command
Builder, as before. The next line is this:
Dim dsNewRow As DataRow
If you want to add a new row to your DataSet, you need a DataRow object. This line just sets up a variable
called
dsNewRow. The type of variable is a DataRow.
To create the new DataRow object, this line comes next: dsNewRow =
ds.Tables("AddressBook").NewRow()
We're just saying, Create a New Row object in the AddressBook DataSet, and store this in the
variable called dsNewRow. As you can see, NewRow() is a method of ds.Tables. Use this method
to add rows to your DataSet.
The actual values we want to store in the rows are coming from the textboxes. So we have these two lines:
dsNewRow.Item("FirstName") = txtFirstName.Text
dsNewRow.Item("Surname") = txtSurname.Text
The dsNewRow object we created has a Property called Item. This is like the Item property you
used earlier. It represents a column in your DataSet. We could have said this instead:
dsNewRow.Item(1) =
txtFirstName.Text
dsNewRow.Item(2) =
txtSurname.Text
The Item property is now using the index number of the DataSet columns, rather than the names.
The results is the same, though: to store new values in these properties. We're storing the text
from the textboxes to our new Row
We now only need to call the Method that actually adds the Row to the DataSet:
ds.Tables(‘AddressBook’).Rows.Add(dsNewRow)
To add the Row, you use the Add method of the Rows property of the DataSet. In between the
round brackets, you need the name of your DataRow (the variable dsNewRow, in our case).
You should know what the rest of the code does. Here's the next line:
da.Update(ds, "AddressBook")
Again, we're just using the Update method of the Data Adapter, just like last time. The rest of the
code just displays a message box, and resets the button.
But to add a new Row to a DataSet, here's a recap on what to do:
Create a DataRow variable
Create an Object from this variable by using the NewRow() method of the DataSet Tables
property
Assign values to the Items in the new Row
Use the Add method of the DataSet to add the new row
A little more complicated, but it does work Try your program out. Click your Add New Record
button. The textboxes should go blank, and three of the buttons will be switched off. Enter a new
First Name and Surname, and then
click the Commit Changes button. You should see the message box telling you that a new record
has been added to the database. To see the new record, close down your program, and run it
again. The new record will be there.
Deleting a record
The code to delete a record is a little easier than last time. Double click your btnDelete and add the
following:
inc = 0 NavigateRecords()
da.Update(ds, "AddressBook")
Here you should first set up a Command Builder. Then we have this line:
ds.Tables("AddressBook").Rows(inc).Delete()
Just as there is an Add method of the DataSet Rows property, so there is a Delete method. You
don't need anything between the round brackets, this time. We've specified the Row to delete
with:
Rows(inc)
The inc variable is setting which particular Row we're on. When the Delete method is called, it
is this row that will be deleted.
However, it will only be deleted from the DataSet. To delete the row from the underlying
database, we have this again:
da.Update(ds, "AddressBook")
The Command Builder, in conjunction with the Data Adapter, will take care of the deleting. All you
need to is call the Update method of the Data Adapter.
The MaxRows line in the code just deducts 1 from the variable. This just ensures that the
number of rows in the DataSet matches the number we have in the MaxRows variable.
We also reset the inc variable to zero, and call the NavigateRecords() subroutine. This will
mean that the first record is displayed, after a record has been deleted.
Try out your program. Click the Next Record button a few times to move to a valid record. Then
click the Delete Record button. The record will be deleted from the DataSet AND the database.
The record that is then displayed will be the first one.
There's another problem, though: if you click the Delete Record button before the Next Record
button, you'll get an error message. You can add an If Statement to check that the inc variable does
not equal minus 1.
Another thing you can do is to display a message box asking users if they really want to delete this
record as shown in figure 9.3.
Sub End If
The first three lines of the code are really one line. The underscore has been used to spread it out,
so as to fit on this page.
But we're using the new message box function:
MessageBox.Show()
In between the round brackets, we specifying the message to display, followed by a caption for
the message box. We then have this:
MessageBoxButtons.YesNo
You won't have to type all that out; you'll be able to select it from a popup list. But what it does is
give you Yes and No buttons on your message box.
After typing a comma, we selected the MessageBoxIcon. Warning icon from the popup list. But you need
to
check which button the user clicked. This is done with this:
= DialogResult.No
Again, you select from a popup list. We want to check if the user clicked the No button. This will
mean a change of mind from the user. A value of No will then be returned, which is what we're
checking for in the If Statement.
The code for the If Statement itself is this:
MsgBox(‘Operation Cancelled’) Exit Sub
This will display another message for the user. But most importantly, the subroutine will be
exited: we don't want the rest of the Delete code to be executed, if the user clicked the No button.
And that's it for our introduction to database programming. You not only saw how to construct a
database program using the Wizard, but how to write code to do this yourself. There is an awful
lot more to database programming, and we've just scratched the surface. But in a beginner's
course, that's all we have time for.
System.Data.OleDb: Supports OLE DB data source such as Oracle, Jet etc. This name space
includes OleDbCommand, OleDbDataReader, OleDbConnection and OleDbDataAdapter. Using
these object we accessed database, that we discussed in the last unit
System.Data.SqlClient: it supports with SQL server 6.5 and above versions. Includes
SqlCommand, SqlConnection, SqlDataAdapter and SqlDataReader objects.
SQL Connection class
SqlConnection class cannot be inherited and establish an open connection towards the SQL server
database. Public NotInheritable Class SqlConnection _
Inherits
DbConnection _
Implements
ICloneable
Has the SqlConnection constructor that initializes the instantiation of the SqlConnection class.
This constructor also accepts the connection string to establish a connection.
This class has methods that supports the database transitions like BeginTransaction,
changeDatabase, CreateCommand, GetSchema, GetType etc. Following are the list of events
supported by the SslConnection Such as Disposed, InfoMessage and StateChange.
SQLDataAdapter
The DataAdapter is an interface between the database and the dataset. It is located between the
connected and disconnected parts of Ado.Net as a connector. DataAdapter class will be
instantiated by the constructor that are generally overloaded. If we use the default constructor
for the DataAdapter, we need to specify the Command object for the actions performed. This
means that if we want to retrieve rows from the Data Source, we will have to set the Select
command property.
The DataAdapter class is not inheritable Declaration is
Punlic NotInheritable Class SqlDataAdapter Inherits DbDataAdapter_
Implements IDbDataAdapter, IDataAdapter,ICloneable
DataSet class
DataSet class consists of information about the set of tables and the relation among those set of
tables. Figure 9.4 depicts the DataSet and its related classes. DataSet will not have any idea about
the data source or the tables. This will be created dynamically whenever required based on the
data source. In SQL server provider, DataSet will be loaded with the help of SqlDataAdapter. Once
the data is loaded it is editable and we can manipulate the data without disturbing the data
source. Even the data base connectivity is not necessary for this action. When the process is over
we can create a new connection and update using the SqlDataAdapter object.
SQL Basics:
1970 – Dr. Edgar F. “Ted” Codd described a relational model for databases.
1974 – Structured Query Language appeared.
1978 – IBM released a product called System/R.
1986 – IBM developed the prototype of a relational database, which is standardized by
ANSI.
1989 – First ever version launched of SQL
1999 – SQL 3 launched with features like triggers, object-orientation, etc.
SQL 2003 – window functions, XML-related features, etc.
SQL 2006 – Support for XML Query Language
SQL 2011 -improved support for temporal databases
SQL Process
When you want to execute an SQL command for any DBMS system, you need to find the best
method to carry out your request, and SQL engine determines how to interpret that specific task.
A classic query engine allows you to manage all the non-SQL queries.
SQL Process
SQL Commands
The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT,
UPDATE, DELETE and DROP. These commands can be classified into the following groups based
on their nature −
CREATE
1
Creates a new table, a view of a table, or other object in the database.
ALTER
2
Modifies an existing database object, such as a table.
DROP
3 Deletes an entire table, a view of a table or other objects in the database.
1 SELECT
Retrieves certain records from one or more tables.
2 INSERT
Creates a record.
3 UPDATE
Modifies records.
4 DELETE
Deletes records.
1 GRANT
Gives a privilege to user.
2 REVOKE
Takes back privileges granted from user.
SELECT
The SQL SELECT statement is used to fetch the data from a database table which returns this data
in the form of a result table. These result tables are called result-sets.
Syntax
The basic syntax of the SELECT statement is as follows −
SELECT column1, column2, columnN FROM table_name;
Here, column1, column2... are the fields of a table whose values you want to fetch. If you want to
fetch all the fields available in the field, then you can use the following syntax.
SELECT * FROM table_name;
Example
Consider the CUSTOMERS table having the following records −
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
The following code is an example, which would fetch the ID, Name and Salary fields of the
customers available in CUSTOMERS table.
INSERT INTO
The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
Syntax
There are two basic syntaxes of the INSERT INTO statement which are shown below.
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
Here, column1, column2, column3,...columnN are the names of the columns in the table into which
you want to insert the data.
You may not need to specify the column(s) name in the SQL query if you are adding values for all
the columns of the table. But make sure the order of the values is in the same order as the columns
in the table.
The SQL INSERT INTO syntax will be as follows −
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
Example
The following statements would create six records in the CUSTOMERS table.
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
You can create a record in the CUSTOMERS table by using the second syntax as shown below.
INSERT INTO CUSTOMERS
VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
All the above statements would produce the following records in the CUSTOMERS table as shown below.
++ +++ +
| ID | NAME | AGE | ADDRESS | SALARY |
++ +++ +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi| 1500.00 |
| 3 | kaushik | 23 | Kota| 2000.00 |
| 4 | Chaitali | 25 | Mumbai| 6500.00 |
| 5 | Hardik | 27 | Bhopal| 8500.00 |
| 6 | Komal| 22 | MP| 4500.00 |
| 7 | Muffy| 24 | Indore| 10000.00 |
+ ++ + ++
UPDATE
The SQL UPDATE Query is used to modify the existing records in a table. You can use the WHERE
clause with the UPDATE query to update the selected rows, otherwise all the rows would be
affected.
Syntax
The basic syntax of the UPDATE query with a WHERE clause is as follows −
UPDATE table_name
SET column1 = value1, column2 = value2. , columnN = valueN
WHERE [condition];
You can combine N number of conditions using the AND or the OR operators.
Example
Consider the CUSTOMERS table having the following records −
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
The following query will update the ADDRESS for a customer whose ID number is 6 in the table.
SQL> UPDATE CUSTOMERS
DELETE
The SQL DELETE Query is used to delete the existing records from a table.
You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the
records would be deleted.
Syntax
The basic syntax of the DELETE query with the WHERE clause is as follows −
DELETE FROM table_name
WHERE [condition];
You can combine N number of conditions using AND or OR operators.
Example
Consider the CUSTOMERS table having the following records −
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
The following code has a query, which will DELETE a customer, whose ID is 6.
SQL> DELETE FROM CUSTOMERS
WHERE ID = 6;
The following figure shows how to work with the connected and disconnected architectures.
Connected Architecture
1. In the connected architecture, connection with a data source is kept open constantly for
data access as well as data manipulation operations.
2. The ADO.NET Connected architecture considers mainly three types of objects.
o SqlConnection con;
o SqlCommand cmd;
o SqlDataReader dr;
Disconnected Architecture
1. Disconnected is the main feature of the .NET framework. ADO.NET contains various classes
that support this architecture. The .NET application does not always stay connected with
the database. The classes are designed in a way that they automatically open and close the
connection. The data is stored client-side and is updated in the database whenever
required.
2. The ADO.NET Disconnected architecture considers primarily the following types of objects:
o DataSet ds;
o SqlDataAdapter da;
o SqlConnection con;
o SqlCommandBuilder bldr;
1. Connection Object and Connection string
Connection Object
1. One of the first ADO.NET objects is the connection object, that allows you to establish a
connection to a data source.
2. The connection objects have the methods for opening and closing connections, for
beginning a transaction of data.
3. The .Net Framework provides two types of connection classes:
The sqlconnection object, that is designed specially to connect to Microsoft SQL Server
and the OleDbConnection object, that is designed to provide connection to a wide range
of databases, such as Microsoft Access and Oracle.
4. A connection is required to interact with the database. A Connection object helps to
identify the database server name, user name and password to connect to the database.
The Connection object is used by commands on the database.
5. A Connection object has the responsibility of establishing a connection with the data store.
6. How to use the Sqlconnection object:
o Instantiate the SqlConnection class.
o Open connection.
o Pass the connection to ADO.NET objects.
o Perform the database operations with ADO.NET object.
o Close the connection.
Connection String
Connection String
No Description
Parameter Name
.
Identify the server. Could be a local machine, machine domain
1 Data Source
name, or IP Address.
2 Initial Catalog Data base name.
3 Integrated Security Set to SSIP to make a connection with the user's window log in.
4 User ID Name of user configured in SQL Server.
The connection string is different for each of the various data providers available in .NET 2.0.
There are different connection strings for the various types of data sources. You can find a list of all
the available providers for creating a connection in a table:
No Provider Description
2 System.Data.OleDb Provides data access for data sources exposed using OLE DB
3 System.Data.Odbc Provides data access for data source exposed using ODBC.
Example
1. SqlConnection con;
2. con = new SqlConnection("Server=Krushna;Database=Anagha;Uid=sa;Pwd=sa"
2. Command Object
A Command object executes SQL statements on the database. These SQL statements can
be SELECT, INSERT, UPDATE, or DELETE. It uses a connection object to perform these
actions on the database.
A Connection object specifies the type of interaction to perform with the database, like
SELECT, INSERT, UPDATE, or DELETE.
A Command object is used to perform various types of operations, like SELECT, INSERT,
UPDATE, or DELETE on the database.
SELECT
1. cmd =new SqlCommand("select * from Employee", con);
INSERT
1. cmd = new SqlCommand("INSERT INTO Employee(Emp_ID,
2. Emp_Name)VALUES ('" + aa + "','" + bb + "')", con);
UPDATE
1. SqlCommand cmd =new SqlCommand("UPDATE Employee SET
2. Emp_ID ='" + aa + "', Emp_Name ='" + bb + "' WHERE
3. Emp_ID = '" + aa + "'", con);
DELETE
1. cmd =new SqlCommand("DELETE FROM Employee where
2. Emp_ID='" + aa + "'", con);
A Command object exposes several execute methods like:
1. ExecuteScaler()
Executes the query, and returns the first column of the first row in the result set
returned by the query. Extra columns or rows are ignored.
2. ExecuteReader()
Display all columns and all rows in the client-side
environment. In other words, we can say that they
display datatables client-side.
3. ExecuteNonQuery()
Something is done by the database but nothing is returned by the database.
Example
1. dr = cmd.ExecuteReader();
2. DataTable dt = new DataTable();
3. dt.Load(dr);
It is used in Connected architecture.
Provide better performance.
DataReader Object has Read-only access.
DataReader Object Supports a single table based on a single SQL query of one database.
While DataReader Object is Bind to a single control.
DataReader Object has Faster access to data.
DataReader Object Must be manually coded.
we can't create a relation in the data reader.
whereas Data reader doesn't support.
The data reader communicates with the command object.
DataReader can not modify data.
A Data Adapter represents a set of data commands and a database connection to fill the
dataset and update a SQL Server database.
A Data Adapter contains a set of data commands and a database connection to fill the
dataset and update a SQL Server database. Data Adapters form the bridge between a data
source and a dataset.
Data Adapters are designed depending on the specific data source. The following table
shows the Data Adapter classes with their data source.
A Data Adapter object accesses data in a disconnected mode. Its object contains a
reference to a connection object.
It is designed in a way that implicitly opens and closes the connection whenever required.
It maintains the data in a DataSet object. The user can read the data if required from the
dataset and write back the changes in a single batch to the database. Additionally, the Data
Adapter contains a command object reference for SELECT, INSERT, UPDATE, and DELETE
operations on the data objects and a data source.
A Data Adapter supports mainly the following two methods:
o Fill ()
The Fill method populates a dataset or a data table object with data from the
database. It retrieves rows from the data source using the SELECT statement specified
by an associated select command property.
The Fill method leaves the connection in the same state as it encountered it before
populating the data. If subsequent calls to the method for refreshing the data are
required then the primary key information should be present.
o Update ()
The Update method commits the changes back to the database. It also analyzes the
RowState of each record in the DataSet and calls the appriopriate INSERT,
UPDATE, and DELETE statements.
A Data Adapter object is formed between a disconnected ADO.NET object and a data source.
Example
In the disconnected scenario, the data retrieved from the database is stored in a local buffer
called DataSet. It is explicitly designed to access data from any data source. This class is
defined in the System.Data namespace.
A Data Set object is an in-memory representation of the data. It is specially designed to
manage data in memory and to support disconnected operations on data.
A Data Set is a collection of DataTable and DataRelations. Each DataTable is a collection of
DataColumn, DataRows, and Constraints.
A DataTable, DataColumn, and DataRows could be created as follows.
Example
1. DataTable dt = new DataTable();
2. DataColumn col =new DataColumn();
3. Dt.columns.Add(col2);
4. DataRow row = dt.newRow();
OracleDataAdapter Oracle
Example
DataReader object supports a single table A DataSet object supports multiple tables from
4
based on a single SQL query of one database various databases
5 A DataReader object is bound to a single A DataSet object is bound to multiple controls
control
6 A DataReader object has faster access to data A DataSet object has slower access to data
7 A DataReader object must be manually coded A DataSet object is supported by Visual Studio
tools
8 We can't create a relation in a data reader We can create relations in a dataset
Whereas a DataReader doesn't support data A Dataset supports integration with XML
9
reader communicates with the command Dataset communicates with the Data Adapter
object. only
1 DataReader cannot modify data A DataSet can modify data
0
4: DataView Object
Coding Part
1. SqlConnection con;
2. SqlCommand cmd;
3. SqlDataReader dr;
4. public DataTable GetTable()
5. {
6.con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=information;Integrated Security= True;Pooling=Fa
7. con.Open();
8. cmd = new SqlCommand("select * from Customers", con);
9. dr = cmd.ExecuteReader();
10.DataTable dt = new DataTable();
11.dt.Load(dr);
12.dataGridView1.DataSource = dt;
13.con.Close();
14.return dt;
15. }
Form1_Load
1. dataGridView1.DataSource = GetTable().DefaultView;
ShortByCity_Click
1. DataView dv = new DataView(GetTable());
2. dv.Sort = "City ASC";
3. dataGridView1.DataSource = dv;
OnlyInMexico_Click
At the click of the sort by city button, the data already in the DataGridView control is sotred dy city.
On clicking the second button, only the records in Mexico are displayed in the
DataGridView control. The output after clicking the only in Mexico button is as the Mexico
button.
Program: Design a simple Winform for accepting the details of Employee. Using the connected
architecture of ADO.NET, perform the following operations:
Insert record.
Search record.
Update record.
Delete record.
1. Form
Design 2.
3. Coding Part
Step3: Form1_Load
Insertbtn_Click
15. con.Open();
16. int aa = Convert.ToInt32(textBox1.Text);
17. string bb = textBox2.Text;
18. int cc = Convert.ToInt32(textBox3.Text);
19. cmd =new SqlCommand("INSERT INTO Employee(Emp_ID, Emp_Name,Salary)VALU
ES ('" + aa +"','" + bb + "','" + cc + "')", con);
20. cmd.ExecuteNonQuery();
21. MessageBox.Show("one record inserted:");
22. con.Close();
23. Display();
Deletebtn_Click
24. con.Open();
25. int aa = Convert.ToInt32(textBox1.Text);
26. cmd =new SqlCommand("DELETE FROM Employee where Emp_ID='" + aa + "'", con);
27. cmd.ExecuteNonQuery();
Updatebtn_Click
31. con.Open();
32. int aa = Convert.ToInt32(textBox1.Text);
33. string bb = textBox2.Text;
34. int cc = Convert.ToInt32(textBox3.Text);
35. string abc = "UPDATE Employee SET Emp_ID ='" + aa + "', Emp_Name ='" + bb + "',Sa
lary ='" + cc + "' WHERE Emp_ID = '" + aa +"'";
36. SqlCommand cmd =new SqlCommand(abc, con);
37. cmd.ExecuteNonQuery();
38. MessageBox.Show("one record updated:");
39. con.Close();
40. Display();
Displaybtn_Click
41. Display();
Searchbtn_Click
42. con.Open();
43. int aa = Convert.ToInt32(textBox1.Text);
44. string abc = "SELECT Emp_ID,Emp_Name,Salary FROM Employee where Emp_ID='"
+ aa +"'";
45. cmd =new SqlCommand(abc, con);
46. MessageBox.Show("one record search:");
47. dr = cmd.ExecuteReader();
48. DataTable dt =new DataTable();
49. dt.Load(dr);
50. dataGridView1.DataSource = dt;
51. con.Close();
Totalrecordbtn_Click
52. con.Open();
53. cmd = new SqlCommand("select Count(*) from Employee", con);
54. int a = (int)cmd.ExecuteScalar();
55. label4.Text = "Total Record:--> " + a.ToString();
56. con.Close();
Exit_Click
57. Application.Exit();
Program: Design a Simple Winform for accepting the details of an Employee. Using the connected
architecture of ADO.NET, perform the following operations:
Insert record.
Search record.
Update record.
Delete record.
Form Design
Coding Part
Step 1: add namespace using System.Data.Oledb; for access Database.
Step 2: Create connection object.
1. OleDbConnection con;
2. OleDbCommand cmd;
3. OleDbDataReader dr;
Step 3: Form1_Load
Display_Click
1. display();
Insert_Click
1. con.Open();
2. int aa = Convert.ToInt32(textBox1.Text);
3. string bb = textBox2.Text;
4. int cc = Convert.ToInt32(textBox3.Text);
5. cmd = new OleDbCommand("INSERT INTO Employee(Emp_ID, Emp_Name,Salary) VALUES
('" + aa + "','" + bb + "','" + cc + "')", con);
6. cmd.ExecuteNonQuery();
7. MessageBox.Show("one record inserted:");
8. con.Close();
9. display();
Delete_Click
1. con.Open();
2. int aa = Convert.ToInt32(textBox1.Text);
3. cmd = new OleDbCommand("DELETE FROM Employee where Emp_ID='" + aa + "'", con);
4. cmd.ExecuteNonQuery();
5. MessageBox.Show("one record Delete:");
6. con.Close();
7. display();
update_Click
1. con.Open();
2. int aa = Convert.ToInt32(textBox1.Text);
3. string bb = textBox2.Text;
4. int cc = Convert.ToInt32(textBox3.Text);
5. string abc = "UPDATE Employee SET Emp_ID ='" + aa + "', Emp_Name ='" + bb + "', Salary ='
" + cc + "' WHERE Emp_ID = '" + aa + "'";
6. OleDbCommand cmd = new OleDbCommand(abc, con);
7. cmd.ExecuteNonQuery();
8. MessageBox.Show("one record updated:");
9. con.Close();
10. display();
Find_Click
1. con.Open();
2. int aa = Convert.ToInt32(textBox1.Text);
3. string abc = "SELECT Emp_ID,Emp_Name,Salary FROM Employee where Emp_ID='" + aa + "'
";
4. cmd = new OleDbCommand(abc, con);
5. MessageBox.Show("one record search:");
6. dr = cmd.ExecuteReader();
7. DataTable dt = new DataTable();
8. dt.Load(dr);
9. dataGridView1.DataSource = dt;
10. con.Close();
Exit_Click
Application.Exit();
Program: Design a simple Winform for accepting the details of an Employee. Using the
disconnected architecture of ADO.NET, perform the following operations.
Insert record.
Display record.
Update record.
Delete record
Form Design
Coding Part
1. DataSet ds;
2. SqlDataAdapter da;
3. SqlConnection con;
4. SqlCommandBuilder bldr;
Step 3: Form1_Load
Display_Click
1. display();
Insert_Click
Delete_Click
Update_Click
1. DataRow dr = ds.Tables[0].Rows.Find(textBox1.Text);
2. dr["Emp_Name"] = textBox2.Text;
3. dr["Salary"] = textBox3.Text;
4. da.Update(ds, "Emp");
5. MessageBox.Show("updated..");
6. dataGridView1.DataSource = ds.Tables[0];
FirstRcd_Click
1. this.BindingContext[ds.Tables[0]].Position = 0;
LastRcd_Click
1. this.BindingContext[ds.Tables[0]].Position = ds.Tables[0].Rows.Count - 1;
NextRcd_Click
1. if (this.BindingContext[ds.Tables[0]].Position > 0)
2. {
3. this.BindingContext[ds.Tables[0]].Position -= 1;
4. }
PreviousRcd_Click
Consider an example to display the result of the students in an examination. The details are added
in the following format.
1. Create a Windows Form Application in Visual Studio .NET. The following customized
format is created for user.
2. Once the design of the form is created, select the View option from the menu bar. Click
on the Properties window.
3. Select the first text box and the properties for it appear in the window.
4. Expand the DataBindings property
5. Select the Text property for enabling the drop down list.
6. Click the Add Project Data Source from the drop down list
7. Make a connection with the CurrentInfo database and select the Student table
8. Select the Other Data Sources, Project Data Sources, CurrentInfoDataSet, Student table.
9. Select the Name column and bind it with the textbox.
10. Bind all the other text boxes with the database values.
11. Press F5 and execute the Windows Form.
12. The following output is displayed to the user.
2. Complex Data Binding
The Complex Data Binding is the process of binding the component with the Database. The
controls can be GridView, Dropdown list, or combo box. Multiple values can be displayed from the
dataset through the binding.
The controls that can be used for binding the multiple values from the database to the Windows
Form are listed below.
1. DataGridView: It is used to display the multiple records and columns. The DataSource
property of the DataGridView control is used for binding the specific data element.
2. ComboBox: The control contains a text box for entering the data and drop down list for
displaying the values. The DataSource property is useful for binding the control. The element
specific information can be bind through the DisplayMember property
3. ListBox: It is used for displaying the data for the column from several records of
datasets. The DataSource property is used for binding the control to the data source.
4. The DisplayMember property is used for binding the control to the specific data element.
A BindingNavigator control is used for handling the binding to the data source through the pointer
to the current item in the list of records.
The navigator control is used with the BindingSource control for enabling the users to navigate
the data records on a form. It provides a layer between the controls and windows form of the
data source. Users can navigate and modify the records in the Windows form.
The following figure displays the BindingNavigator control and the BindingSource control in the
Windows Form.
The Binding Navigator control has many controls for modifying the data source. The list of
controls and their functions are mentioned below:
1. bindingNavigatorAddNewItem Button: The + sign indicates that the new row can be added
to the data source.
2. bindingNavigatorDeleteItem Button: The X sign indicates that the current row can be
deleted from the data source.
3. bindingNavigatorMoveFirstItem Button: The button indicates that the user can move to
the first item in the data source.
4. bindingNavigatorMoveLastItem Button: The button indicates that the user can move to
the last item in the data source
5. bindingNavigatorMoveNextItem Button: The button indicates that the user can move to
the next item in the data source
6. bindingNavigatorMovePreviousItem Button: The button indicates that the user can move
to the previous item in the data source
7. bindingNavigatorPositionItem textbox: The returns current position in the data source
8. bindingNavigatorCountItemText box: The is used to return the total number of items in the data
source.
Consider the Order details table containing the data about the orders to be added. The data is
organized into a format as shown below:
1. Open Visual studio application and add Windows Forms Application from the template pane.
2. Add the labels and a binding Navigator control, and textbox controls to the form
3. Click OK button
4. Click View, Properties Window, and open the Properties Window.
5. Add the appropriate names to the controls present in the web form.
6. Open the Data Source Configuration Wizard. The Database icon must be selected. Click
Next Button
7. Click New Connection Button. Add Connection dialog box is shown.
8. Add the Server Name, select Use SQL Server Authentication option from the Log on the
server section
9. Add the User name as sa and password as abcd1234
10. Select the Order Details database and click Test Connection button
11. Click OK and close the Add Connection dialog box
12. Click Next button. In the Choose Your Database Objects dialog box, expand Tables node.
13. Select the Orderdata table and click Finish button.
For binding the data to the control in the Windows Form, the following steps are executed.
1. Select the textbox1, and expand the DataBindings property.
2. Select the Text property and click on the drop down list.
3. Expand the Other Data Sources, Project Data, Sources, Orderdataset, Orderdata nodes.
4. Select the OrderID column and bind it with textbox1.
5. Perform the similar operations for all the textboxes.
Press F5 or click Debug -> Start Debugging option from the menu. The Order Details form is
displayed as shown below:
User can navigate through the other records using the navigator button of the
control. Close the form and exit the Visual Studio application.
Filtering Data
There are requirements when user wants to display only limited data to the client. The filtering of
data is possible for displaying the desired results. The data can be sorted in ascending or
descending order.
There are two ways by which the data can be filtered. They are as mentioned below:
1. Parameterized Queries
2. Filtering data using controls in Windows Form.
1. Parameterized Queries
The stored procedures are always useful for accessing data from the database. By using the stored
procedures users can precompiled execution, use of code, less network traffic, and security is high
for the data stored in the system.
The parameterized queries are useful for filtering the data based on the conditions defined by the
user at runtime. They are useful when user wants to execute the data based on the situation.
The following query is useful for selecting the student with the ID specified.
In the above code, the @StudID is the parameter in the query. The value is passed at the runtime
by the user.
In ADO.NET, for populating the @StudID parameter, the SqlParameter object in the SqlParameter class
for the command. The SqlParameter object is used for assigning the parameterized values to the queries.
Consider the example for extracting the details of the student. The following code shows the
execution parameterized query.
Once the data is retrieved from the data source by binding the data to the control of the Windows
form, the data filter is used for displaying the selective records.
Consider the example of a company where user wants to view the information about the
employee data. The information is displayed in the form of a grid view. The connection is
established with the database and the data binding through the DataGridView control.
If user wants the data only of the specific employees in the organization, they can be filtered using
the following steps.
1. Select the DataGridView control in the form and open the DataGridViewTasks window.
2. Click on the Add Query option. The SearchCriteria Builder dialog box will open.
3. Add the following query in the query text box.
SELECT EmpID, EmpName, EmpRole FROM Employee WHERE ( EmpID = 101 )
4. Click on the Query Builder button
5. Click on the Execute Query button. The output generated by the query can be checked
6. Click OK button and close the Search Criteria Builder dialog box
7. Press F5 and execute the Windows Form.
In the above example, TableAdapter queries are the SQL statements or procedures that are
executed. The FillBy method is useful for executing the TableAdapter queries.
The following code can be added to the Click event of the FillByToolStrip control.
}
catch( System.Exception ex )
{
System.Windows.Forms.MessageBox.Show( ex.Message );
}
}
In the above code, the FillBy method is used for adding data from the Employee table of the EmpDataSet.
Databinding with DataGridView in ADO.NET
DataGridView is very powerful and flexible control for displaying records in a tabular (row-
column) form. Here I am describing a different way of databinding with a DataGridView
control.
Step 1 : Select DataGridView control and click at smart property. Look at the following figure.
Step 4 : Click at Add Project Data Source (Look at above figure). A new window will be opened to choose
Data Source Type.
Step 5 : Choose Database (By default it is selected) and click the next button. A new window will be open to
Database Model.
Step 6 : Select DataSet (By default it is selected) and click the next button. A new window will be open.
Step 15 : Click the Finish button. You will note that the DataGridView will show all columns of the
table (Here, "Student_detail").
Output
Now we bind the DataGridView with database by code. Take another DataGridView control and
write the following code on the form load event.
using System;
using
System.Collections.Generic
; using
System.ComponentModel;
using System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Windows.Forms
; using
System.Data.SqlClient;
namespace DatabindingWithdataGridView
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlDataAdapter
dadapter; DataSet
dset;
string connstring =
"server=.;database=student;user=sa;password=wintellect";
private void Form1_Load(object sender, EventArgs e)
{
dadapter = new SqlDataAdapter("select * from
student_detail", connstring); dset = new
System.Data.DataSet();
dadapter.Fill(dset);
dataGridView1.DataSource = dset.Tables[0].DefaultView;
}
}
}
CloseOutput Gets or Sets a value indicating whether the System.Xml.XmlWriter should clos
underlying stream or System.IO.TextWriter when the
System.Xml.XmlWriter.C method is called.
ConformanceLevel Gets or Sets the level of compliance with which the System.Xml.XmlWriter
co with
NewLineHandling Gets or Sets a value indicating whether to normalize line breaks in the output
or
NewLineAttributes Gets or Sets a value indicating whether to write attributes on a new line or not.
Creating elements in an XML file
OmitXmlDeclaration Gets or Sets a value indicating whether to write an XML declaration or not.
Elements can be created in two ways:
By calling the WriteElementString() Method:
WriteElementString() method takes two parameters, the name of the element and the value of the
element. Like:
writer.WriteElementString(“Student”,”Robin”
); Here student is the element name and Robin is the
value By calling the WriteStartElement() Method:
WriteStartElement() method takes the name of the element as a parameter. After calling it,
WriteString() method is called to specify a value for this element. Then WriteEndElement()
method is called to end the element tag. Like:
writer.WriteStartElement(“Student”);
writer.WriteString(“Robin”);
writer.WriteEndElement();
Comments can be write using the WriteComment() method. This method takes a string as a
parameter. This string is written as a comment in the XML file.
writer.WriteComment(“This XML file is created for students details”);
Creating an XML file
By using XmlWriter
using System;
using
System.Collections.Generic
; using System.Text;
using System.Xml;
using
System.Data.SqlClient;
namespace xmlWrite
class Program
{
XmlWriterSettings settings=new
XmlWriterSettings();
settings=.Indent=true;
settings.IndentChars=” ”;
settings.NewLineOnAttribut
es=true;
using(XmlWriter writer=XmlWriter.Create(“D:\\productdetails.xml”,settings));
writer.WriteComment(“Product details”);
writer.WriteStartElement(“Product_detail
s”); writer.WriteStartElement(“Product”);
writer.WriteAttributeString(“Product_ID”
,”P-0001”);
writer.WriteElementString(“ProductNam
e”,”Toys”);
writer.WriteElementString(“Price”,”200”)
; writer.WriteEndElement();
writer.WriteStartElement(“Product”);
writer.WriteAttributeString(“Product_ID”
,”P-0213”);
writer.WriteElementString(“ProductName”,
”Mouse”);
writer.WriteElementString(“Price”,”500”)
; writer.WriteEndElement();
writer.WriteEndElement();
writer.Flush();
By using XmlTextWriter
Methods of XmlTextWriter
Methods Description
writeStartDocument() Writes the XML declaration in the beginning of XML document: <? xml
version=”1.0”
Method Description
WriteXml() Enables to write the data of the datset into an XML file
Following code can be used to write the details stored in the Product table to an XML file:
using System;
using
System.Collections.Generic
; using System.Text;
using System.Xml;
using System.Data.SqlClient;
namespace xmlWrite
class Program
{
Con.ConnectionString=”DataSource=SQLSERVER01;Intial Catalog=HR;User
ID=sa;Password=password#1234”;
da.Fill(ds,”Product”);
ds.WriteXml(“D:\\ProductDetails.xml”);
WriteXml( ) takes two parameters first the destination file where the output of XML file will be stored
and second but optional parameter is XmlWriteMode option that specifies how the XML output is to be
written.
IgnoreSchema Used to write the contents of dataset as XML data without an XML Schema. It is
defa
WriteSchema Used to write the contents of dataset as XML data with the dataset structure as an inli
schema
ValidationType Gets or Sets a value indicating whether the reader should perform validation
or
Schemas Gets or Sets the XmlSchemaSet object to use while performing schema
validat
XmlReader reader=null;
Reader=XmlReader.Create(“D:\\
Products.xml”,settings);write.WriteStartAttribute(“StudentID”); writer.WriteString(“S-
109”); writer.WriteEndAttribute();writer.WriteStartElement(“Student”);
writer.WriteString(“Robin”);
writer.WriteEndElement();
XmlTextReader
XmlTextReader class is derived class of XmlReader class. The XmlTextReader class reads the XML
document but does not allow to access or validate the schema information.
Method Description
MoveToElement() Moves to the element that contains of the current attribute node
ReadAttributeValue() Reads the value of the attribute and parses it into one or more nodes.
ReadStartElement() Verifies if the current node is an element and moves the reader to the next
node.
ReadEndElement() Verifies if the current node is an end tag and moves the reader to the next
node
XmlValidatingReader validatingReader=new
XmlValidatingReader(“textReader”);
XmlTextReader textReader=new
XmlTextReader(“Product.xml”); XmlValidatingReader
validatingReader=new XmlValidatingReader(textReader);
xdoc.Load(validatingReader);
After loading the XmlValidaingReader for an XML document, the ValidationType property is
used to specify the type of validation that we have to perform on that document.
DiffGrams
When we create an XML representation of a dataset, ADO.NET enables to present the data in a
DiffGram format. The DiffGram format preserves information about changes to the data in the
dataset so that we can choose whether to accept or reject the changes when we read the XML data
back to the dataset.
A DiffGram is an XML format that identifies current and original versions of data elements.Elements of
DiffGram
Block Description
<DataInstance> It contains the name of the dataset or the data table. It contains the current data.
Attributes of DiffGram
Attribute Description
Id Used to pair the elements in the <diffgr:before> and <diff:errors> blocks to elements in the
<DataInstance> block
parented It identifies which element from the <DataInstance> block is the parent element of the current
ele
hasChanges It identifies a row in the <DataInstance> block as modified. It has three values:
inserted
modified
descent
Following code explains it:
hasErrors It identifies a row in the<DataInstance> block with a RowError. The error is placed in the
using System;
<diffgr block
using
Error It contains the text of the RowError for an element in the <diff:errors> block
System.Collections.Generic
; using System.Text;
using System.Xml;
using
System.Data.SqlClien
t; namespace
xmlWrite
class Program
{
ID=sa;Password=password#1234”; con.Open();
da.Fill(ds,”Product”);
//write dataset contents to an XML file by calling WriteXml() method in a diffgram mode
ds.WriteXml(“D:\\ProductDetails.xml”, XmlWriteMode.DiffGram);
con.Close();
}
UNIT IV
WEB SERVICES:
As you can see in the figure, Java, .net, and PHP applications can communicate with other
applications through web service over the network. For example, the Java application can interact
with Java, .Net, and PHP applications. So web service is a language independent way of
communication.
As we already know, a typical Web Services architecture comprises three entities i.e. a
Client, a Web Server, and an Internet to carry out the operation. The operation is nothing but the
request and response in a client-server architecture.
A Client is typically a set of all the applications or software systems that requests a Web
Service thereby making it a Service Consumer.
A Web Server is a set of all applications or software systems that provide Web Service. Every
Web Service requires a network to perform and this results in the third entity called the Internet.
The working diagram of a Web Service is defined by the three components shown below.
Service Requestor
(Find()) Service Provider
(Publish())
Service Registry or Repository (Bind())
These three entities interact with each other to carry out a successful Web Service
Implementation. This is done in three phases. The first phase is the Publish() phase where a
Service Provider feeds all the details about a Web Service in a Service Registry or Repository.
The second phase is Find() where a Service Request mainly the client application finds the
details about Web Service from a repository (also has WSDL XML file). The last phase is Binding()
where the
client application or the Service Requester synchronizes with the Service Provider for the final
implementation of the Web Service.
2) RESTful Service
REST stands for Representational State Transfer which is a Stateless Service. It is called
Stateless as the Web Server does not store any information about the client session (time duration
till the client application is connected and in execution) which means each request type is treated
and performed easily with the help of REST inbuilt methods like GET, POST, CUSTOM (PUT),
DELETE, HEAD and so on. Indeed, these methods are not present in SOAP.
Each method in REST has its significance. Given Below is the briefing about each of them.
GET: This method is used to retrieve the information that is sent to the server using any of
the methods like PUT or POST. This does not have a request body. Successful execution will
give you 200 response objects.
POST: This method is used to create a document or record using a request body, specified
URL, document key, context key, etc. The same can be retrieved using the GET method.
Successful execution will give you a 201 response.
PUT: This is under the CUSTOM option that is available in POSTMAN or PARASOFT. This
method is used to update any document or record that is already present. Successful
execution will give you a 201 or 200 response.
DELETE: This method is used to delete any record. Successful execution will give you a 204
response (no content).
SOAP vs REST
desired response.
The above communication model has the below serious limitations
1. Not Language Independent – The server hosting the methods would be in a particular
programming language and normally the calls to the server would be in that programming
language only.
2. Not the standard protocol – When a call is made to the remote procedure, the call is not
carried out via the standard protocol. This was an issue since mostly all communication over
the web had to be done via the HTTP protocol.
3. Firewalls – Since RPC calls do not go via the normal protocol, separate ports need to be
open on the server to allow the client to communicate with the server. Normally all firewalls
would block this sort of traffic, and a lot of configuration was generally required to ensure
that this sort of communication between the client and the server would work.
To overcome all of the limitations cited above, SOAP would then use the below communication model
1. The client would format the information regarding the procedure call and any arguments
into a SOAP message and sends it to the server as part of an HTTP request. This process of
encapsulating the data into a SOAP message was known as Marshalling.
2. The server would then unwrap the message sent by the client, see what the client requested
for and then send the appropriate response back to the client as a SOAP message. The
practice of unwrapping a request sent by the client is known as Demarshalling.
Step 1) The first step is to create an empty ASP.Net Web application. From Visual Studio 2013, click
on the menu option File->New project.
Once you click on the New Project option, Visual Studio will then give you another dialog
box for choosing the type of project and to give the necessary details of the project. This is
explained in the next step.
Step 2) In this step,
1. Ensure to first choose the C# web template of ASP.NET Web application. The project has to
be of this type in order to create SOAP services project. By choosing this option, Visual
Studio will then carry out the necessary steps to add required files which are required by
any web-based application.
2. Give a name for your project which in our case has been given as webservice.asmx. Then
ensure to give a location where the project files will be stored.
Once done you will see the project file created in your solution explorer in Visual Studio 2013.
Step 4) Add the following code to your Tutorial Service asmx file.
Code Explanation:
1. This line of code provides a name for your web service file. This is an important step
because it gives way for the client application to call the web service via the name of the web
service.
2. Normally a class file is used to encapsulate the functionality of a web service. So the class file
will have the definition of all the web methods which will provide some functionality to the
client application.
3. Here [WebMethod] is known as an attribute which describes a function. The subsequent
step creates a function called “Guru99WebService”, but with the inclusion of this step of
adding a [WebMethod] attribute makes sure that this method can be invoked by a client
application. If this attribute is not in place, then the method can never be called by a client
application.
4. Here we are defining a function called ‘Guru99WebService’ which will be used to return a
string to the calling client application. This function is a web service which can be called by
any client application.
5. We are using the return statement to return the string “This is a Guru99 Web service” to the
client application.
If the code is executed successfully, the following Output will be shown when you run your code in
the browser.
Output:
The output clearly shows that the name of our web service is “Guru99 Web Service” which
is the result of giving a name for our web service.
We can also see that we can to invoke the web service. If we click the Invoke button, we will
get the below response in the web browser.
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance">
<soap:Body>
<Guru99WebServiceResponse xmlns="http://tempuri.org/">
<Guru99WebServiceResult>string</Guru99WebServiceResult>
</Guru99WebServiceResponse>
</soap:Body>
</soap:Envelope>
Code Explanation:
1. The first part of the SOAP message is the envelope element which is what was discussed in
the prior chapters. This is the encapsulating element which is present in every SOAP
message.
2. The SOAP Body is the next element and contains the actual details of the SOAP message.
3. The interesting part you will see now is the ‘string’ attribute. This tells the client application
that the web service being called returns an object of the type string. This is very useful
because if the client application which otherwise would not know what the web service
returns.
<message name="TutorialResponse">
<part name="TutorialName" type="xsd:string"/>
</message>
<portType name="Tutorial_PortType">
<operation name="Tutorial">
<input message="tns:TutorialRequest"/>
<output message="tns:TutorialResponse"/>
</operation>
</portType>
<output>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/
encoding/" namespace="urn:examples:Tutorialservice"
use="encoded"/>
</output>
</operation>
</binding>
</definitions>
The important aspects to note about the above WSDL declaration examples of web services are as
follows:
1. <message> – The message parameter in the WSDL definition is used to define the different
data elements for each operation performed by the web service. So in the web services
examples above, we have 2 messages which can be exchanged between the web service and
the client application, one is the “TutorialRequest”, and the other is the “TutorialResponse”
operation. The TutorialRequest contains an element called “TutorialID” which is of the type
string. Similarly, the TutorialResponse operation contains an element called “TutorialName”
which is also a type string.
2. <portType> – This actually describes the operation which can be performed by the web
service, which in our case is called Tutorial. This operation can take 2 messages; one is an
input message, and the other is the output message.
3. <binding> – This element contains the protocol which is used. So in our case, we are
defining it to use http (http://schemas.xmlsoap.org/soap/http). We also specify other
details for the body of the operation, like the namespace and whether the message should
be encoded.
Structure of a WSDL
WSDL Elements
The WSDL file contains the following main parts
1. The <types> tag is used to define all the complex datatypes, which will be used in the
message exchanged between the client application and the web service. This is an important
aspect of the client application, because if the web service works with a complex data type,
then the client application should know how to process the complex data type. Data types
such as float, numbers, and strings are all simple data types, but there could be structured
data types which may be provided by the web service.
For example, there could be a data type called EmployeeDataType which could have 2
elements called “EmployeeName” of type string and “EmployeeID” of type number or
integer. Together they form a data structure which then becomes a complex data type.
2. The <messages> tag is used to define the message which is exchanged between the client
application and the web server. These messages will explain the input and output
operations which can be performed by the web service. An example of a message can be a
message which accepts the EmployeeID of an employee, and the output message can be the
name of the employee based on the EmpoyeeID provided.
3. The <portType> tag is used to encapsulate every input and output message into one logical
operation. So there could be an operation called “GetEmployee” which combines the input
message of accepting the EmployeeID from a client application and then sending the
EmployeeName as the output message.
4. The <binding> tag is used to bind the operation to the particular port type. This is so that
when the client application calls the relevant port type, it will then be able to access the
operations which are bound to this port type. Port types are just like interfaces. So if a client
application needs to use a web service they need to use the binding information to ensure
that they can connect to the interface provided by that web service.
5. The <service> tag is a name given to the web service itself. Initially, when a client
application makes a call to the web service, it will do by calling the name of the web service.
For example, a web service can be located at an address such as
http://localhost/Guru99/Tutorial.asmx . The service tag will actually have the URL
defined as http://localhost/Guru99/Tutorial.asmx, which will actually tell the client
application that there is a web service available at this location.
Why WSDL
A web service is an important component in building modern day web applications. Their main
purpose is to allow multiple applications built on various programming languages to talk to each
other. For instance, we can have a .Net web application talks to a Java application via a Web service.
A web service has the following key features
It is built using the XML programming language. Almost all modern day technologies such as
.Net and Java have corresponding commands that have the ability to work with XML. Hence,
XML was taken as the most appropriate language for building web services.
Web services communicate over HTTP. HTTP is a protocol used by all web-based
applications. Hence, it just made sense to ensure that Web services also had the ability to
work over the HTTP protocol.
Web services conform to a particular language specification. This specification is set by the
W3C, which is the governing body for all web standards.
Web services have a description language known as WSDL, which is used to describe the
web service.
The WSDL file is written in plain old XML. The reason that it is in XML is so that the file can be read
by any programming language.
So if the client application was written in .Net, it would understand the XML file. Similarly, if the
client application was written in the Java programming language then also it would be able to
interpret the WSDL file.
The WSDL file is what binds everything together. From the above diagram, you can see that
you can create a web service in the .Net language.
<?xml version="1.0"?>
<definitions name="Tutorial"
targetNamespace=http://Guru99.com/
Tutorial.wsdl xmlns:tns=http://Guru99.com/Tutorial.wsdl
xmlns:xsd1=http://Guru99.com/Tutorial.xsd
xmlns:soap=http://schemas.xmlsoap.org/wsdl/soap/
xmlns="http://schemas.xmlsoap.org/wsdl/">
<types>
<schema targetNamespace=http://Guru99.com/Tutorial.xsd
xmlns="http://www.w3.org/2000/10/XMLSchema">
<element name="TutorialNameRequest">
<complexType>
<all>
<element name="TutorialName" type="string"/>
</all>
</complexType>
</element>
<element name="TutorialIDRequest">
<complexType>
<all>
<element name="TutorialID" type="number"/>
</
all>
</complexType>
</element>
</schema>
</types>
<message name="GetTutorialNameInput">
<part name="body" element="xsd1:TutorialIDRequest"/>
</message>
<message name="GetTutorialNameOutput">
<part name="body" element="xsd1:TutorialNameRequest"/>
</message>
<portType name="TutorialPortType">
<operation name="GetTutorialName">
<input message="tns:GetTutorialNameInput"/>
<output message="tns:GetTutorialNameOutput"/>
</operation>
</portType>
<binding name="TutorialSoapBinding" type="tns:TutorialPortType">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="GetTutorialName">
<soap:operation soapAction="http://Guru99.com/GetTutorialName"/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="TutorialService">
<documentation>TutorialService</documentation>
<port name="TutorialPort" binding="tns:TutorialSoapBinding">
<soap:address location="http://Guru99.com/Tutorial"/>
</port>
</service>
</definitions>
Publishing the Web Service Example
In this example, we will create a web service with one WebMethod. This method will accept
an Integer parameter called “TutorialID.” The Web method will then return a string called “Web
Services.”
We will then create a console based application, which will consume this web service and
call our web method accordingly.
Let’s look at the steps required to carry out this example.
Step 1) The first step is to create your web service. The detailed steps of how the Asp.Net web
project and a web service is created has been explained here; Please follow the same steps to create
the project and web service accordingly. The key part is to enter the below code in the Web services
file.
namespace webservic asmx
{
[WebService(Name = "Guru99 Web service")]
public class TutorialService : System.Web.Services.WebService
{
[WebMethod]
public string GetTutorialService(int TutoriallD)
{
string TutorialName = "Web Services";
return TutorialName;
}
}
}
Code Explanation:
1. Here we are creating a WebMethod called “Guru99WebService.” In this web method, we are
including an integer parameter which needs to be passed whenever this web method is
called.
2. Next we are defining a variable called “TutorialName” which will hold the string value of
“Web Services.” This is the value which will be returned when the web service is called.
Step 2) Once we have defined the web services file, the next step is to create a client project which
will consume this web service.
Follow the below steps to create a console application. Right-click the Visual Studio solution
file and choose the option Add->New project
Step3) In this step,
1. Ensure to first choose the Visual C# Windows option. Then choose the option of creating a
console application.
2. Give a name for your project which in our case has been given as “DemoApplication.”
After you click the OK button in the above screen, you will be able to see the project in the Solution
explorer in Visual Studio.
Step 4) In this step, you be setting the DemoApplication Console application as the startup project.
This is done to ensure that this application launches first when the entire Visual Studio project is
run. This Console application will, in turn, call the web service which will be automatically launched
by Visual Studio.
To complete this step, right-click the DemoApplication project and choose the option “Set as
StartUp Project.”
Step 5) The next step is to add the service reference of our “Guru99Webservice” to our console
application. This is done so that the DemoApplication can reference the web service and all of the
web methods in the web service.
To do this, right-click the DemoApplication project file and choose the menu option Add->Service
Reference.
Step 6) In this step, we will provide the different values which are required to add our service reference
1. Firstly we need to choose our discover option. This option will automatically pick up the
WSDL file for our TutorialService web service.
2. Next, we should give a name for our service reference. In our case, we are giving it a name of
Guru99Webservice.
3. Then we need to expand on the TutorialService.asmx option so that we can have the ability
to see the ‘GetTutorialService’ method on the right-hand side. Here TutorialService.asmx is
the name of our Visual Studio .Net file which contains the code for our web service.
4. We will then see our Web method which we had in our web service known as “GetTutorialService”
When we click on the ‘OK’ button, all of the required code to access this web service will be
added to our DemoApplication Console application as shown below.
The screenshot shows that the “Guru99Webservice” was successfully added to our console application.
Step 7) The next step is to add the code to our console application to access the web method in our
web service. Open the Program.cs code file which comes automatically with the console application
and add the below code
namespace DemoApplication
{
class Program
{
static void Main(string[ ] args)
{
var client = new
Guru99Webservice.Guru99WebserviceSoapClient();
Console.WriteLine(client.GetTutorialService(l));
Console.ReadKey();
}
}
}
Code Explanation:-
1. The first part is to choose the Program.cs file. This is the main file which is created by Visual
Studio when a console application is created. This file is what gets executed when the
console application (in our case demo application) is executed.
2. We then create a variable called “client” which will be set to an instance of our Service
reference which was created in an earlier step. In our case, the service reference is
‘Guru99Webservice.Guru99WebserviveSoapClient()’
3. We are then calling our Webmethod ‘GetTutorialService’ in the TutorialService web service
Remember that our GetTutorialService’ method accepts an integer parameter, so we are just
passing an integer parameter to the web method.
4. This final line is just to ensure the console log screen remains active so that we can view the
output. This command will just wait for some input from the user.
Output
When all of the above steps are followed, and the DemoApplication is run the below output will be
displayed.
From the output, we can clearly see that the DemoApplication calls our Web service and that the
string returned by the Web service is displayed in our Console log.
UDDI is an XML-based standard for describing, publishing, and finding web services.
UDDI stands for Universal Description, Discovery, and Integration.
UDDI is a specification for a distributed registry of web services.
UDDI is a platform-independent, open framework.
UDDI can communicate via SOAP, CORBA, Java RMI Protocol.
UDDI uses Web Service Definition Language(WSDL) to describe interfaces to web services.
UDDI is seen with SOAP and WSDL as one of the three foundation standards of web services.
UDDI is an open industry initiative, enabling businesses to discover each other and define
how they interact over the Internet.
UDDI has two sections −
A registry of all web service's metadata, including a pointer to the WSDL description of a service.
A set of WSDL port type definitions for manipulating and searching that registry.
UDDI - Elements
A business or a company can register three types of information into a UDDI registry. This
information is contained in three elements of UDDI.
These three elements are −
White Pages,
Yellow Pages, and
Green Pages.
White Pages
Contains Basic information about the company and its business.
Basic contact information including business name, address, contact phone number, etc.
A Unique identifiers for the company tax IDs. This information allows others to discover
your web service based upon your business identification.
Yellow Pages
Yellow pages contain more details about the company. They include descriptions of the kind
of electronic capabilities the company can offer to anyone who wants to do business with it.
Yellow pages uses commonly accepted industrial categorization schemes, industry codes,
product codes, business identification codes and the like to make it easier for companies to
search through the listings and find exactly what they want.
Green Pages
Green pages contains technical information about a web service. A green page allows someone
to bind to a Web service after it's been found. It includes −
The various interfaces
The URL locations
Discovery information and similar data required to find and run the Web service.
UDDI - Technical
Model
UDDI Data Model is an XML Schema for describing businesses and web services. The data model is
described in detail in the "UDDI Data Model" chapter.
UDDI API Specification
It is a specification of API for searching and publishing UDDI
data. UDDI Cloud Services
These are operator sites that provide implementations of the UDDI specification and synchronize
all data on a scheduled basis.
The UDDI Business Registry (UBR), also known as the Public Cloud, is a conceptually single
system built from multiple nodes having their data synchronized through replication. The current
cloud services provide a logically centralized, but physically distributed, directory. It means the
data submitted to one root node will automatically be replicated across all the other root nodes.
Currently, data replication occurs every 24 hours.
UDDI cloud services are currently provided by Microsoft and IBM. Ariba had originally
planned to offer an operator as well, but has since backed away from the commitment. Additional
operators from other companies, including Hewlett-Packard, are planned for the near future.
It is also possible to set up private UDDI registries. For example, a large company may set
up its own private UDDI registry for registering all internal web services. As these registries are
not automatically synchronized with the root UDDI nodes, they are not considered as a part of the
UDDI cloud.
UDDI includes an XML Schema that describes the following data structures −
businessEntity
businessService
bindingTemplate
tModel
publisherAssertion
businessEntity Data
Structure
The business entity structure represents the provider of web services. Within the UDDI registry,
this structure contains information about the company itself, including contact information,
industry categories, business identifiers, and a list of services provided.
Here is an example of a fictitious business's UDDI registry entry −
<businessEntity businessKey = "uuid:C0E6D5A8-C446-4f01-99DA-
70E212685A40" operator = "http://www.ibm.com" authorizedName = "John
Doe">
<name>Acme Company</name>
<description>
We create cool Web services
</description>
<contacts>
<contact useType = "general info">
<description>General Information</description>
<personName>John Doe</personName>
<phone>(123) 123-1234</phone>
<email>[email protected]</email>
</contact>
</contacts>
<businessServices>
...
</businessServices>
<identifierBag>
<keyedReference tModelKey = "UUID:8609C81E-EE1F-4D5A-B202-3EB13AD01823"
name = "D-U-N-S" value = "123456789" />
</identifierBag>
<categoryBag>
<keyedReference tModelKey = "UUID:C0B9FE13-179F-413D-8A5B-5004DB8E5BB2"
name = "NAICS" value = "111336" />
</categoryBag>
</businessEntity>
businessService Data
Structure
The business service structure represents an individual web service provided by the business
entity. Its description includes information on how to bind to the web service, what type of web
service it is, and what taxonomical categories it belongs to.
Here is an example of a business service structure for the Hello World web service.
<businessService serviceKey = "uuid:D6F1B765-BDB3-4837-828D-
8284301E5A2A" businessKey = "uuid:C0E6D5A8-C446-4f01-99DA-
70E212685A40">
<name>Hello World Web Service</name>
<description>A friendly Web service</description>
<bindingTemplates>
...
</bindingTemplates>
<categoryBag />
</businessService>
Notice the use of the Universally Unique Identifiers (UUIDs) in the
businessKey and serviceKey attributes. Every business entity and business service is uniquely
identified in all the UDDI registries through the UUID assigned by the registry when the
information is first entered. bindingTemplate Data Structure
Binding templates are the technical descriptions of the web services represented by the business
service structure. A single business service may have multiple binding templates. The binding
template represents the actual implementation of the web service.
Here is an example of a binding template for Hello World.
<bindingTemplate serviceKey = "uuid:D6F1B765-BDB3-4837-828D-
8284301E5A2A" bindingKey = "uuid:C0E6D5A8-C446-4f01-99DA-
70E212685A40">
<description>Hello World SOAP Binding</description>
<accessPoint URLType = "http">http://localhost:8080</accessPoint>
<tModelInstanceDetails>
<tModelInstanceInfo tModelKey = "uuid:EB1B645F-CF2F-491f-811A-4868705F5904">
<instanceDetails>
<overviewDoc>
<description>
references the description of the WSDL service definition
</description>
<overviewURL>
http://localhost/helloworld.wsdl
</overviewURL>
</overviewDoc>
</instanceDetails>
</tModelInstanceInfo>
</tModelInstanceDetails>
</bindingTemplate>
In real life, you may add your models to the project then add the corresponding API controllers.
Since we are discussing about the documentation/testability, let us add an empty API Controller for
the project.
Right click the Controller folder, select Add -> Controller, select the template “Web API 2 Controller
– Empty” and then click on the Add button
For the purpose of this walkthrough I am going to add a Greeting Control that have some
methods/actions to greet a particular user.
The Web API controller is created. I am going to add two actions, the first one that accepts a user
and return the greeting based on the system time. The second action will accept a name, the hour of
day and return the greeting message based on the hour. The completed Controller code is given
below
The purpose of this article is not to evaluate whether the GreetMessage logic is ideal or not, instead
let us look into the Web API artifacts. One thing you will notice is that I am defining routes for both
actions. Though this works, in real life scenarios, it is better to define the route in the
WebApiConfig.cs file. By defining routes in one place increases the maintainability of the project.
Now Let us focus on the problem we are trying to solve. Basically we need to address the below two
issues that every developer needs to address
Documentation
Test Client
Documentation
The first step in generating the documentation is adding XML Comments to your controllers and
actions. XML Comments are out there for years to support the documentation.
Once you enabled the documentation, you need to ensure to select the XML documentation file
generation from the build properties of your project. From solution explorer, right click your
project and select properties. Now in the Build menu, make sure you have selected the checkbox
associated with XML documentation file.
You can use GhostDoc or any other Visual Studio extension to generate XML comments. Basically
you can do this without using any tool too, but the tools will dramatically reduce your efforts. I have
added the comments with the help of GhostDoc. Now the controller looks as below.
The next thing we need to do is to generate Help documentation from these XML comments.
Luckily Microsoft has released a Nuget package for this purpose. You can refer the package from
the link https://www.nuget.org/packages/Microsoft.AspNet.WebApi.HelpPage/
I have installed the HelpPage package from the package manager console. In Visual Studio you can
open the package manager console from Tools -> Package Manger
Once the package is successfully installed, you can see the Areas Folder, where the HelpPage
components are added.
You are not done yet! We need the help pages to read the documentation from your comments,
right. In order to do this, you need to ensure Visual Studio generates the XML file while building
your application. Right click the project in solution explorer click on properties, go to the Build tab,
you can see “XML documentation file” check box, make sure you select this.
Now you need to configure the help page to read from the generated XML file. Open the
HelpPageConfig.cs find under Areas -> App_Start -> HelpPageConfig.cs, by default the
HelpPageConfig.cs looks as below.
Just uncomment the config.SetDocumentationProvider method and update the path to your XML as
per the build configuration. The modified method is given below.
We are almost there! Let us enable the users to browse the documentation. Basically we need to
register the Help page. Open WebApiConfig.cs file from the App_Start folder, In the register method,
call RegisterAllAreas() method. See the modified webapiconfig.cs file
Now build & run the application and browse to “/help”, you will see the documentation in the
browser.Cool!
Test Client
Now we have the documentation, what is next? I need to test my APIs. In our case the service
methods are all HttpGet and is easy to test in the browser by entering the url. But what if the
methods are with HttpPost or other verbs, Definitely we need an effective way to test. There are
couple of Nuget packages available for this, you can find one from the link
https://www.nuget.org/packages/WebApiTestClient/
The Nuget packages are maintained with high level of documentation. The author of the package
already wrote a good blog in MSDN. You can read it from the below Uri.
https://blogs.msdn.microsoft.com/yaohuang1/2012/12/02/adding-a-simple-test-client-to-asp-
net-web-api- help-page/
Ok. Let me install it from the package manager console. The
command is Install-Package WebApiTestClient
Note:- There are some other packages available in Nuget that serves the same purpose. To be
honest with you I didn’t test them all, but you can try them.
Now once the WebApiTestClient package is installed, you will have the following files created in
the solution.
Scripts\WebApiTestClient.js
Areas\HelpPage\TestClient.css
Areas\HelpPage\Views\Help\DisplayTemplates\TestClientDialogs.cshtml
Areas\HelpPage\Views\Help\DisplayTemplates\
TestClientReferences.cshtml Now the only thing left is to call the API
methods from the Help pages. Open the file Api.cshtml from Areas ->
HelpPage -> Views-> Help
Now let us browse the help page, and when I select any method/action details, there is a button for
testing the API, great!
Click on the TestAPI button, you will be allowed to pass the parameters and test the service method.
Once you enter the parameter values, click Send and the Web API method will be called and you
can see the response. This work for all HTTP methods such as HttpPost, HttpGet and so on.
I entered some sample values and clicked on Send, and immediately I am able to view the response.
It is good that you can achieve the documentation and test without doing much work. That’s cool
and during the development process, the moment you add a service, other team members can view
the service documentation and test them.
Consuming the Web Service
For using the web service, create a web site under the same solution. This could be done by right
clicking on the Solution name in the Solution Explorer. The web page calling the web service
should have a label control to display the returned results and two button controls one for post
back and another for calling the service.
The content file for the web application is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="wsclient._Default" %>
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
</body>
</html>
The code behind file for the web application is as
follows: using System;
using System.Collections;
using
System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using
System.Web.UI.HtmlControls;
using
System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
//this is the
proxy using
localhost;
namespace wsclient
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblmessage.Text = "First Loading Time: " + DateTime.Now.ToLongTimeString
}
else
{
lblmessage.Text = "PostBack at: " + DateTime.Now.ToLongTimeString();
}
}
Step (2) : Select 'Web Services in this solution'. It returns the Stock Service reference.
Step (3) : Clicking on the service opens the test web page. By default the proxy created is called
'localhost',you can rename it. Click on 'Add Reference' to add the proxy to the client application.
UNIT – V
Advanced ASP.NET
Component-Based Programming
Component-based programming is a simple, elegant idea. When used properly, it allows your code to be
more organized, consistent, and reusable. It's also incredibly easy to implement in a .NET application,
because you never need to use the Windows registry or perform any
special configuration.
A component, at its simplest, is one or more classes that are compiled into a separate DLL assembly file.
These classes provide some unit of logically related functionality. You can access a component in a single
application, or you can share the component between multiple applications. Your web pages (or any
other .NET application) can use the classes in your components in the same way they use any other .NET
class. Best of all, your component is encapsulated, which means it provides exactly the features your code
requires and hides all the other messy details.
As we know components enable us to reuse application logic across multiple pages or even say across
multiple applications. We can write a method named GetConnection() once and use this method in all the
pages consist in website. By taking advantage of components, we can make our applications very easier to
maintain, execute, reuse and even extend the use in multiple aspects. But if we are working on simple website
project, there is no reason to take advantage of components.
In this article series we will discuss how to build simple and advanced components. I am writing this series
in multiple parts. If we are working on Components then we also have to discuss on its methods, properties,
constructors, inheritance and interfaces.
Basic Component
In this basic component we will create simple welcome application suing components. Here is the example given
below.
Class1.vb File Code
Class Class1
Public Function Welcome() As String Return
"Welcome to MINDCRACKER"
End Function End
Class
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
In the Page_Load() event handler, an instance of the Class1() component is created. Next, the result returned
by a call to the Welcome() method is assigned to a Label control. When we open the page in your browser,
we'll see the message "Welcome to MINDCRACKER" from the Class.vb File.
ASP.NET State Management
State management is very important and useful in ASP.NET. It is also asked in many interviews to fresher and
experienced developers.
ASP.NET State management is a preserve state control and object in an application because ASP.NET
web applications are stateless. A new instance of the Web page class is created each time the page is
posted to the server. If a user enters information into a web application, that information would be lost
in the round trip from the browser (MSDN).
In a single line, State management maintains and stores the information of any user till the end of the user
session.
Two types of State Management techniques are available in ASP.NET as in the following figure,
Figure 1: State Management Part
Server side
Session
Session is a very important technique to maintain state. Normally session is used to store information
and identity. The server stores information using Sessionid.
Session Event
Session_Start
The Session_start event is raised every time a new user requests without a session ID.
Session_End
The Session_End event is raised when session is ended by a user or a time out using Session end
method.
InProcMode
It is a default session mode and a value store in web server memory (IIS). In this the session value stored
with server start and it ends when the server is restarted.
Custom Mode
Generally under session data is stored in InProc, Sql Server, State server, etc. If you store session data
with other new techniques then provide ASP.NET.
Application
Application State is a server side management state. It is also called application level state management. In this
mainly store user activity in server memory and application event shown in Global.asax file.
Application_Start
Application_Error
Application_ End
Cache
Cache is stored on server side. It implements Page Caching and data caching. Cache is use to set expiration
polices
Response.Cache.SetExpiresTime(DateTime.Now.AddDays(1));
Client Side
Cookie is a small and an important part of ASP.NET. In this store user information, session and application. It
can be created constant and temporary and they work with browser request. Cookies are store on client side.
The server can read cookies and abstract data.
Persistence
Non-Persistence
This is a temporary cookie. It is created with access application and discards the close application.
Control state technique is developed to maintain data work properly in order. We can use view state but
suppose view state is disabled by the user, the control will not work as expected. For expected results of
the control we have to use Control State. In application, the Viewstate is by default true. Sometimes we
need to use custom control to manage application properly.
1. if (!IsPostBack)
3.lblmsg1.Text
2. { = "Welcome to C# corner"; 5. }
When two messages are displayed on a Postback event, then control which one is displayed by using
customized control state.
Hidden Field
Hidden fields are used to store value to client side. Hidden field is not displayed on the browser, but it
works on a request.
1. if (HiddenField1.Value != null)
2. {
3. int val = Convert.ToInt32(HiddenField1.Value) + 1;
4. HiddenField1.Value = val.ToString();
5. Label1.Text = val.ToString();
6. }
Viewstate is a very useful client side property. It is used for page level state management. Viewstate
stores any type of data and used for sending and receiving information,
Example 1 - Count.
1. if (ViewState["UserName"] != null)
2. lblName.Text = ViewState["UserName"].ToString();
OR,
1. ViewState["UserName"] = txtUserName.Text;
Viewstate is easy to apply and does not need access to any server resources. In a Viewstate, do not store big
data, only store small values. Viewstate enables and disables on page level control. It also supports
Encryption and Decryption and data/value is stored in hashed format. So we are not storing important data
such as password, account information, etc. When more data is stored in this, then the page becomes heavy.
Query String
Response.Redirect("ShowStringValue.aspx?Username=" +
link,
4. Click the COM tab in the Add Reference dialog box. A list of COM components is displayed.
5. Select the COM component that you want to use within your ASP.NET application. For example, select
the Microsoft ActiveX Data Objects 2.7 library option form the list and double click the Select button. The
component is added to the Selected Components pane, as displayed in the following figure:
6. Click the OK button. The component that you have added to the project is displayed in the
Reference node in Solution Explorer.
7. You can use the COM component in the application by specifying its library class, as follows:
ADODB.RecordsetClass rs=new ADODB.RecordsetClass();
You can use this COM object rs, in your application to call its method.
User controls
Custom controls
User Controls
User controls behaves like miniature ASP.NET pages or web forms, which could be used by many other
pages. These are derived from the System.Web.UI.UserControl class. These controls have the following
characteristics:
Inherits="customcontroldemo.footer" %>
To add the user control to your web page, you must add the Register directive and an instance of the
user control to the page. The following code shows the content file:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="customcontroldemo._Default" %>
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<Tfooter:footer ID="footer1" runat="server" />
</form>
</body>
</html>
When executed, the page shows the footer and this control could be used in all the pages of your
website.
(2) The following tag name and prefix should be used while adding the user control on the page:
<Tfooter:footer ID="footer1" runat="server" />
Custom Controls
Custom controls are deployed as individual assemblies. They are compiled into a Dynamic Link Library
(DLL) and used as any other ASP.NET server control. They could be created in either of the following way:
The above step adds a new project and creates a complete custom control to the solution, called
ServerControl1. In this example, let us name the project CustomControls. To use this control, this must be
added as a reference to the web site before registering it on a page. To add a reference to the existing
project, right click on the project (not the solution), and click Add Reference.
Select the CustomControls project from the Projects tab of the Add Reference dialog box. The Solution
Explorer should show the reference.
To use the control on a page, add the Register directive just below the @Page directive:
Further, you can use the control, similar to any other controls.
<form id="form1" runat="server">
<div>
<ccs:ServerControl1 runat="server" Text = "I am a Custom Server Control" />
</div>
</form>
When executed, the Text property of the control is rendered on the browser as shown:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
namespace CustomControls
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1 >")]
set
{
ViewState["Text"] = value;
}
}
using System;
using
System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CustomControls
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1 >")]
set
{
ViewState["Text"] = value;
}
}
The Click event handler for the button simply copies the text from the text box to the text property of the
custom control.
(2) The RenderContents method of the custom control class is overridden here, as you can add your
own methods and events.
(3) The RenderContents method takes a parameter of HtmlTextWriter type, which is responsible for
rendering on the browser.
In this article, we will walk through some performance improvement techniques in ASP.NET Web Applications.
As you know, good performance of a web application is what a customer expects. The web application
performance issue arises when the number of users increases in the application or it can also occur after a
few days in production or during load testing in UAT. At this point, it's a tedious task to fix the performance
issues since efforts are more toward making code changes and henceforth everyone blames developers for
this issue. The main point is more if it's an application like Online Banking in which more customers are
engaged at a time.
Now, if we came to understand that our web application has performance issues then we can fix it easily.
First, we will something that could be potentially the cause of performance issue. It is the time to learn which
one is the culprit for a performance issue and fix it soon. The major tasks I
categorize as being performance tuning issues are Collect Data, Analyze Results, Fine-tune the code and
again test it for performance measure in an iterative fashion.
CPU and memory are the two places where most of the performance issues occur. The following are the
points which one needs to check before collecting data as a .Net developer.
When you create the ASP.Net web application, by default this attribute is set to "true" in the web.config file
that is very useful when developing. However, when you are deploying your application, always set it to
"false". Setting it to "true" requires the pdb information to be inserted into the file and that results in a
comparatively larger file and hence processing will be
slow. So always set debug="false" before deployment.
One extremely powerful feature of ASP.NET is its ability to store session state for users for any web
applications. Since ASP.NET manages session state by default, we pay the cost in memory even if you don't
use it. In other words, whether you store your data in in-process or on a state server or in a SQL Database,
session state requires memory and it's also time consuming when you store or retrieve data from it. You may
not require session state when your pages are static or when you do not need to store information captured
in the page. In such cases where you need not use session state, disable it on your web form using the
directive:
1. <@%Page EnableSessionState="false"%>
In case you use the session state only to retrieve data from it and not to update it, make the session state
read-only using the following directive.
If the application needing session mode state is out of process then consider carefully whether there is a
need of the state server or SQL Server session mode. SQL Server session mode provides lower performance
than session state server mode.
Don't store Session Sate to store objects of any type (including objects you create) since they are stored by
serializing and then de-serializing them and that results in a big performance penalty.
Use the client-side session state management technique to transfer data from one page to other page like query
string and clientsidestorage if possible.
Be sure you use Release Build mode and not Debug Build when you deploy your site to production. If
you think this doesn't matter, think again. By running in debug mode, you are creating PDBs and
cranking up the timeout. Deploy Release mode and you will see the speed improvements.
View state is a technique in ASP.NET for storing some state data in a hidden input field inside the generated
page. When the page is posted back to the server, the server can parse, validate and apply this view state data
back to the page's tree of controls.
View state is a very powerful capability since it allows state to be persisted with the client and it requires no
cookies or server memory to save this state. Many ASP.NET server controls use view state to persist settings
made during interactions with elements on the page; for example, saving the current page that is being
displayed when paging through data.
There are a number of drawbacks to the use of view state, however it increases the total payload of the page,
both when served and when requested. There is also an additional overhead incurred when serializing or
deserializing view state data that is posted back to the server. View state increases the memory allocations
on the server. Several server controls, the most well known of which is the DataGrid, tend to make excessive
use of view state, even in cases where it is not needed. Pages that do not have any server postback events
can have the view state turned off.
The default behaviour of the View State property is enabled, but if you don't need it, you can turn it off at the
control or page level. Within a control, simply set the EnableViewState property to false, or set it globally
within the page using this setting.
<%@ Page EnableViewState="false" %>
Avoid Response.Redirect
To do client-side redirection in ASP.NET, users can call Response.Redirect and pass the URL. When
Response.Redirect is called, the server sends a command back to the browser telling it to request the page
redirected to it. An extra roundtrip happens that affects the performance. We can send information from the
source page using a query string. There is a limitation on the length of a query string, it cannot be used to
pass large amounts of data over the wire.
To do server-side redirection, users can use Server.Transfer. Since the execution is transferred on the server,
Server.Transfer does not require the client to request another page. In Server.Transfer, by using HttpContext
we can access the source page's items collection in the target page. The drawback of using this method is that
the browser does not know that a different page was returned to it. It displays the first page's URL in the
browser's address bar. This can confuse the user and cause problems if the user tries to bookmark the page.
Transfer is not recommended since the operations typically flow through several pages.
All the manipulations you do to the string are stored in memory as separate references and it must be
avoided as much as possible. In other words, when a string is modified, the runtime will create a new string
and return it, leaving the original to be garbage collected. Most of the time this is a fast and simple way to do
it, but when a string is being modified repeatedly it begins to be a burden on performance, all of those
allocations eventually get expensive. Use StringBuilder whenever a string concatenation is needed so that it
only stores the value in the original string and no additional reference is created.
Exceptions cause slowdowns you will never see in web applications, as well as Windows applications. You
can use as many try/catch blocks as you want. Using exceptions gratuitously is where you lose performance.
For example, you should stay away from things like using exceptions to control flow.
The finally method gets executed independent of the outcome of the block. Always use a finally block to kill
resources like closing database connections, closing files and other resources such that they are executed
independent of whether the code in the try worked or went to the catch.
User Input is evil and it must be thoroughly validated before processing to avoid overhead and possible
injections to your applications. Client-side validation can help reduce round trips required to process a user's
request. In ASP.NET you can also use client-side controls to validate user input. However, do a check at the
server side too to avoid the infamous JavaScript disabled scenarios.
Avoid unnecessary round trips to the server
Round trips significantly affect performance. They are subject to network latency and to downstream
server latency. Many data-driven Web sites heavily access the database for every user request. Whereas
connection pooling helps, the increased network traffic and processing load on the database server can
adversely affect performance. Keep round trips to an absolute minimum.
Implement Ajax UI whenever possible. The idea is to avoid full page refresh and only update the portion of
the page that needs to be changed.
Use Page.ISPostBack
Be sure you don't execute code needlessly. Use the Page.ISPostBack property to ensure that you only
perform page initialization logic when a page is first time loaded and not in response to client postbacks.
Explicitly using a return allows the JIT to perform slightly more optimizations. Without a return statement,
each function/method is given several local variables on the stack to transparently support returning values
without the keyword. Keeping these around makes it harder for the JIT to optimize and can impact the
performance of your code. Look through your functions/methods and insert a return as needed. It doesn't
change the semantics of the code at all and it can help you get more speed from your application.
A foreach statement is far more readable and in the future it will become as fast as a for loop for special cases
like strings. Unless string manipulation is a real performance hog for you, the slightly messier code may not
be worth it. Use a LINQ query expression when needed.
When you use byRef, you pass pointers instead of the actual object. Many times this makes sense (side-
effecting functions, for example), but you don't always need it. Passing pointers results in more indirection
and that is slower than accessing a value that is on the stack. When you don't need to go through the heap, it
is best to avoid it, thereby avoiding indirection.
Choose the right collection object that does better over another. For example, an ArrayList is better than an
array because an ArrayList has everything that is good about an array plus automatic sizing, Add, Insert,
Remove, Sort, Binary Search. All these great helper methods are added when implementing the IList
interface and the downside of an ArrayList is the need to cast objects upon retrieval. Carefully choosing a
collection over another gives better performance.
Here is the list of collection performance issues that helps us deciding which one gives better performance.
Always be sure you check Page.IsValid before processing your forms when using Validation Controls.
Most web applications need the data to be shown in tabular format. For that we need a Grid view, DataGrid,
JQgrid, Telerik grid, Kendo Grid UI and so on. When doing a selection we should use a thin grid that gives
better performance. ASP.NET grid view uses server-side code and makes the
page heavy, whereas JQGRID is faster since it does everything at the client side. Use paging to display data on
a user demand basis instead of pulling a huge amount of data and showing it in a grid. Use a Repeater control
instead of a DataGrid or DataList because it is efficient, customizable and programmable and faster in
performance than that of a GridView, DataGrid and DataList.
Call a web service from JavaScript or jQuery instead of server-side. Use asynchronous calls to call a web
method from a web service.
ASP.NET allows you to cache entire pages, fragments of pages or controls. You can cache also variable data by
specifying the parameters that the data depends on. By using caching you help the ASP.NET engine to return
data for repeated request for the same page much faster.
The proper use and fine tuning of the caching approach of caching will result in better performance and
scalability of your site. However improper use of caching will actually slow down and consume lots of server
memory and memory usage. A good candidate to use caching is if you have infrequent chance of data or
static content of a web page.
Authentication can also have an impact on the performance of your application. For example, Passport
authentication is slower than form-based authentication and that in turn is slower than Windows
authentication.
The use of web server controls increases the response time of your application because they need time to
be processed on the server side before they are rendered on the client side. One way to minimize the
number of web server controls is to take into consideration the use of HTML elements where they are
suited, for example if you want to display static text.
Calls to unmanaged code is a costly marshalling operation. Try to reduce the number of calls between
the managed and unmanaged code. Consider doing more work in each call rather than making frequent
calls to do small tasks. Use a using block.
If you are working with distributed applications then this involves additional overhead negotiating network
and application level protocols. In this case network speed can also be a bottleneck. Try to do as much work
as possible in fewer calls over the network.
Design with Value Types
Use simple structs when you can and when you don't do much boxing and unboxing.
ValueTypes are far less flexible than Objects and end up degrading performance if used incorrectly. You
need to be very careful about when you treat them like objects. This adds extra boxing and unboxing
overhead to your program and can end up costing you more than it would if you had stuck with objects.
There are several ASP.NET default Http Modules that sit in the request pipeline and intercept each and every
request. For example, SessionStateModule intercepts each request, parses the session cookie and then loads
the proper session in the HttpContext. Not all of these modules are always necessary for processing in the
page execution life cycle.
For example, if you aren't using Membership and Profile provider, you don't need FormsAuthentication
module remove this from web application web.config file.
Minimize assemblies
Minimize the number of assemblies you use to keep your working set small. If you load an entire assembly
just to use one method, you're paying a tremendous cost for very little benefit. See if you can duplicate that
method's functionality using code that you already have loaded.
By default, ASP.NET comes configured to encode requests and responses as UTF-8. If ASCII is all your
application needs, eliminating the UTF overhead can return a few cycles. Note that this can only be done on a
per-application basis.
These are general things to adopt in any programming language that consumes much memory. Always
avoid nested loops and recursive functions, to improve performance.
When you can, use toString() instead of Format(). In most cases, it will provide you with the functionality you
need, with much less overhead.
Make JavaScript and CSS External
Using external files generally produces faster pages because the JavaScript and CSS files are cached
by the browser. Inline JavaScript and CSS increases the HTML document size but reduces the number of
HTTP requests. With cached external files, the size of the HTML is kept small without increasing the number
of HTTP requests, thus improving the performance.
The problem arises when single-threaded code gets stuck on a long-running process. So when we call
multiple services in a single method we should call two methods in two different threads. Use of multiple
threads makes the application more responsive.
The manner in which you profile your application depends on the development tool that you use to create
the ASP.NET application. Any ASP.NET application created in any development tool can be profiled using IIS.
Additionally, Visual Studio versions 2005 - 2012 have their own server
- ASP.NET Development Server - that is generally used instead of IIS to develop and debug ASP.NET
applications. However, it is still possible to use IIS to profile your application outside of Visual Studio. The
following topics provide instructions on different ways to profile ASP.NET applications.
Profiling ASP.NET Applications via ASP.NET Development Server
Describes how to profile ASP.NET applications or services using the ASP.NET Development Server.
Profiling ASP.NET Applications via Internet Information Services
Describes how to profile ASP.NET applications or services using the Internet Information Services (IIS).
What is Caching?
Caching is a technique of storing frequently used data/information in memory, so that, when the same
data/information is needed next time, it could be directly retrieved from the memory instead of being
generated by the application.
Caching is extremely important for performance boosting in ASP.NET, as the pages and controls are
dynamically generated here. It is especially important for data related transactions, as these are expensive in
terms of response time.
Caching places frequently used data in quickly accessed media such as the random access memory of the
computer. The ASP.NET runtime includes a key-value map of CLR objects called cache. This resides with the
application and is available via the HttpContext and System.Web.UI.Page.
In some respect, caching is similar to storing the state objects. However, the storing information in state objects
is deterministic, i.e., you can count on the data being stored there, and caching of data is nondeterministic.
The data will not be available in the following cases:
Caching in ASP.Net
Put this directive under the page directive. This tells the environment to cache the page for 15 seconds. The
following event handler for page load would help in testing that the page was really cached.
protected void Page_Load(object sender, EventArgs e)
{
Thread.Sleep(10000);
Response.Write("This page was generated and cache at:" +
DateTime.Now.ToString());
}
The Thread.Sleep() method stops the process thread for the specified time. In this example, the thread is
stopped for 10 seconds, so when the page is loaded for first time, it takes 10 seconds. However, next time
you refresh the page it does not take any time, as the page is retrieved from the cache without being
loaded.
The OutputCache directive has the following attributes, which helps in controlling the behaviour of the
output cache:
Location
Any Any: page may be cached anywhere.
Client Client: cached content remains at
browser.
Downstream
Downstream: cached content stored in
Server
downstream and server both.
None Server: cached content saved only on
server.
None: disables caching.
Duration Number Number of seconds the page or control
is cached.
Let us add a text box and a button to the previous example and add this event handler for the button.
protected void btnmagic_Click(object sender, EventArgs e)
{
Response.Write("<br><br>");
Response.Write("<h2> Hello, " + this.txtname.Text + "</h2>");
}
When the program is executed, ASP.NET caches the page on the basis of the name in the text box.
Data Caching
The main aspect of data caching is caching the data source controls. We have already discussed that the
data source controls represent data in a data source, like a database or an XML file. These controls derive
from the abstract class DataSourceControl and have the following inherited properties for implementing
caching:
CacheDuration - It sets the number of seconds for which the data source will cache data.
CacheExpirationPolicy - It defines the cache behavior when the data in cache has expired.
CacheKeyDependency - It identifies a key for the controls that auto-expires the content of its
cache when removed.
EnableCaching - It specifies whether or not to cache the data.
Example
To demonstrate data caching, create a new website and add a new web form on it. Add a SqlDataSource control
with the database connection already used in the data access tutorials.
For this example, add a label to the page, which would show the response time for the page.
Apart from the label, the content page is same as in the data access tutorial. Add an event handler for the
page load event:
Object Caching
Object caching provides more flexibility than other cache techniques. You can use object caching to place
any object in the cache. The object can be of any type - a data type, a web control, a class, a dataset object,
etc. The item is added to the cache simply by assigning a new key name, shown as follows Like:
Cache["key"] = item;
ASP.NET also provides the Insert() method for inserting an object to the cache. This method has four
overloaded versions. Let us see them:
Overload Description
Sliding expiration is used to remove an item from the cache when it is not used for the specified time span.
The following code snippet stores an item with a sliding expiration of 10 minutes with no dependencies.
Example
Create a page with just a button and a label. Write the following code in the page load event:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
lblinfo.Text += "Page Posted Back.<br/>";
}
else
{
lblinfo.Text += "page Created.<br/>";
}
if (Cache["testitem"] == null)
{
lblinfo.Text += "Creating test item.<br/>";
DateTime testItem = DateTime.Now; lblinfo.Text
+= "Storing test item in cache "; lblinfo.Text +=
"for 30 seconds.<br/>"; Cache.Insert("testitem",
testItem, null,
DateTime.Now.AddSeconds(30), TimeSpan.Zero);
}
else
{
lblinfo.Text += "Retrieving test item.<br/>"; DateTime
testItem = (DateTime)Cache["testitem"]; lblinfo.Text +=
"Test item is: " + testItem.ToString(); lblinfo.Text +=
"<br/>";
}
lblinfo.Text += "<br/>";
}
When the page is loaded for the first time, it says:
Page Created.
Creating test item.
Storing test item in cache for 30 seconds.
If you click on the button again within 30 seconds, the page is posted back but the label control gets its
information from the cache as shown:
Page Posted Back.
Retrieving test item.
Test item is: 14-07-2010 01:25:04
ASP.NET - Security
Implementing security in a site has the following aspects:
Authentication : It is the process of ensuring the user's identity and authenticity. ASP.NET allows
four types of authentications:
o Windows Authentication
o Forms Authentication
o Passport Authentication
o Custom Authentication
Authorization : It is the process of defining and allotting specific roles to specific users.
Confidentiality : It involves encrypting the channel between the client browser and the web server.
Integrity : It involves maintaining the integrity of data. For example, implementing digital
signature.
Forms-Based Authentication
Traditionally, forms-based authentication involves editing the web.config file and adding a login page with
appropriate authentication code.
The web.config file could be edited and the following codes written on it:
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl ="login.aspx"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
...
...
</configuration>
The login.aspx page mentioned in the above code snippet could have the following code behind file with
the usernames and passwords for authentication hard coded into it.
if(uname == "Dick")
{
if(pass == "dick123")
return true;
}
if(uname == "Harry")
{
if(pass == "har123")
return true;
}
return false;
}
Step (3) : Select the authentication type to 'Forms based authentication' by selecting the 'From the Internet'
radio button.
Step (4) : Click on 'Create Users' link to create some users. If you already had created roles, you could assign
roles to the user, right at this stage.
Step (5) : Create a web site and add the following pages:
Welcome.aspx
Login.aspx
CreateAccount.aspx
PasswordRecovery.aspx
ChangePassword.aspx
Step (6) : Place a LoginStatus control on the Welcome.aspx from the login section of the toolbox. It has two
templates: LoggedIn and LoggedOut.
In LoggedOut template, there is a login link and in the LoggedIn template, there is a logout link on the
control. You can change the login and logout text properties of the control from the Properties window.
Step (7) : Place a LoginView control from the toolbox below the LoginStatus control. Here, you can put
texts and other controls (hyperlinks, buttons etc.), which are displayed based on whether the user is
logged in or not.
This control has two view templates: Anonymous template and LoggedIn template. Select each view and
write some text for the users to be displayed for each template. The text should be placed on the area
marked red.
Step (8) : The users for the application are created by the developer. You might want to allow a visitor to
create a user account. For this, add a link beneath the LoginView control, which should link to the
CreateAccount.aspx page.
Step (9) : Place a CreateUserWizard control on the create account page. Set the ContinueDestinationPageUrl
property of this control to Welcome.aspx.
Step (10) : Create the Login page. Place a Login control on the page. The LoginStatus control automatically links
to the Login.aspx. To change this default, make the following changes in the web.config file.
For example, if you want to name your log in page as signup.aspx, add the following lines to the
<authentication> section of the web.config:
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl ="signup.aspx" defaultUrl = “Welcome.aspx― />
</authentication>
</system.web>
</configuration>
Step (11) : Users often forget passwords. The PasswordRecovery control helps the user gain access to the
account. Select the Login control. Open its smart tag and click 'Convert to Template'.
Customize the UI of the control to place a hyperlink control under the login button, which should link to the
PassWordRecovery.aspx.
Step (12) : Place a PasswordRecovery control on the password recovery page. This control needs an email
server to send the passwords to the users.
Step (13) : Create a link to the ChangePassword.aspx page in the LoggedIn template of the LoginView
control in Welcome.aspx.
Step (14) : Place a ChangePassword control on the change password page. This control also has two views.
-------------------------------------------------------------------------------------------------------------