ASP.NET
ASP.NET
Introduction to .NET
1.0 Objectives
1.1 Introduction
1.2 .NET Framework
1.2.1 Net Framework and .Net Languages
1.2.2 Languages supported by .Net
Framework
1.3 .NET Class Library
1.4 ASP vs. ASP.NET
1.5 Summary
1.6 Check your Progress - Answers
1.7 Questions for Self – Study
1.8 Suggested Readings
1.0 OBJECTIVES
After studying this chapter you will be able to –
explain .NET Framework.
describe the .Net languages.
explain the .Net class library.
explain difference between ASP and ASP.NET.
1.1 INTRODUCTION
Microsoft .NET technology you will have access to a new generation of
advanced software joining the best of computing and communications in a
revolutionary new way. The effect will be to totally transform the Web and every other
aspect of the computing experience. .NET enables developers, businesses, and
consumers to harness technology on their terms. .NET will allow the creation of truly
distributed Web services that will integrate and collaborate with a range of
complementary services to help customers in ways that today’s dotcoms can only
dream of.
The fundamental idea behind .NET is that the focus is shifting from individual
Web sites or devices connected to the Internet to constellations of computers, devices,
and services that work together to deliver broader, richer solutions. People will have
control over how, when, and what information is delivered to them. Computers,
devices and services will be able to collaborate with each other to provide rich
services, instead of being isolated islands where the user provides the only integration.
Businesses will be able to offer their products and services in a way that lets
customers seamlessly embed them in their own electronic fabric.
Microsoft .NET will make computing and communicating simpler and easier
than ever. It will spawn a new generation of Internet services, and enable tens of
thousands of software developers to create revolutionary online services and
businesses. It will put you back in control, and enable greater control of your privacy,
digital identity, and data. And software is what makes it all possible. However,
Microsoft’s .NET technology will only succeed if others adopt this new standard.
Source: http://vig.prenhall.com/samplechapter/013093285X.pdf
NET Framework
Advantages of .NET
The .NET Framework provides the following advantages:
The table below lists all the languages supported by the .NET Framework and
describes those languages.
Introduction to .NET / 3
programming language to have more lines of code than
any other language.
Eiffel is an Object-Oriented (OO) programming
Eiffel language which emphasizes the production of robust
software. Eiffel is strongly statically typed mature
Object-Oriented language with automatic memory
management.
ASP .NET / 4
Practical Extraction and Report Language, Perl, is a
Perl language optimized for scanning arbitrary text files,
extracting information from those text files, and printing
reports based on that information. It's also a good
language for many system management tasks.
Python is an interpreter, interactive, Object-Oriented
Python programming language. Python combines remarkable
power with very clear syntax. It has modules, classes,
exceptions, very high level dynamic data types, and
dynamic typing.
Report Program Generator, RPG, is used for generation
RPG of reports from data files, including matching record and
sub-total reports. RPG is one of the few languages
created for punch card machines that are still in
common use today. RPG or RPG IV is a native
programming language for IBM's iSeries minicomputer
system.
Scheme is a statically scoped programming language. It
Scheme was designed to have an exceptionally clear and simple
semantics and few different ways to form expressions.
A wide variety of programming paradigms, including
imperative, functional, and message passing styles, find
convenient expression in Scheme.
Small Talk is an expressive language that uses a simple
Small Talk sub set of human languages, nouns and verbs.
Smalltalk was the first, and remains one of the few; pure
object a system, which simply means that everything in
a Smalltalk program is an object. Smalltalk is generally
recognized as the second Object Programming
Language (OPL).
Standard ML is a safe, modular, strict, functional,
Standard ML polymorphic programming language with compile-time
type checking and type inference, garbage collection,
exception handling, immutable data types and
updatable references, abstract data types, and
parametric modules. It has efficient implementations
and a formal definition with a proof of soundness.
Visual Basic is a "visual programming" environment for
Microsoft developing Windows applications. Visual Basic makes it
Visual Basic possible to develop complicated applications very
quickly. This site is all about Visual Basic.
Namespace Description
Introduction to .NET / 5
Other child namespaces contain classes used by the
ADO.NET Entity Data Model (EDM) and by WCF Data
Services.
ASP .NET / 6
then rendered back to the response. This architecture affects the efficiency of
page rendering in several ways. Thus, to improve efficiency of rendering, many
ASP developers resort to large blocks of server-side script, replacing static
HTML elements with Response.Write() invocations instead. Finally, this ASP
model actually allows different blocks of script within a page to be written in
different script languages.
5) In classic ASP it was very difficult for us to debug the application. ASP
developers had time to debug application due to limited support due to the
interpreted model.
6) Class=docText>especially if you are using ASP pages it is possible to include
executable code outside the scope of a function within a script block marked as
runat=server, and, it is possible to define a function within a pair of server-side
script tags.
7) New Page Directives: In ASP you must place all directives on the first line of a
page within the same delimiting block. For example:
<%LANGUAGE="VBSCRIPT" CODEPAGE="932"%>
ASP.NET
1) The ASP.NET worker process is a distinct worker process, aspnet_wp.exe,
separate from inetinfo.exe (IIS process), and the process model in ASP.NET is
unrelated to process isolation settings in IIS.
2) ASP.NET could be run on non-Microsoft Platforms also.
3) We are no longer constrained to the two scripting languages available in
traditional ASP: Any fully compliant .NET language can now be used with
ASP.NET, including C# and VB.NET.
4) In contrast, ASP.NET pages are always compiled into .NET classes housed
within assemblies. This class includes all of the server-side code and the static
HTML, so once a page is accessed for the first time (or any page within a
particular directory is accessed), subsequent rendering of that page is serviced
by executing compiled code. This eliminates all the inefficiencies of the scripting
model of traditional ASP. There is no longer any performance difference
between compiled components and server-side code embedded within a page
they are now both compiled components. There is also no performance
difference between interspersing server-side code blocks among static HTML
elements, and writing large blocks of server-side code and using Response
.Write() for static HTML content. Also, because the .aspx file is parsed into a
single code file and compiled, it is not possible to use multiple server-side
languages within a single .aspx file.
5) But in ASP.NET In addition to improved performance over the interpreted model,
pages that are compiled into classes can be debugged using the same
debugging tools available to desktop applications or component developers.
Errors with pages are generated as compiler errors, and there is a good chance
that most errors will be found at compilation time instead of runtime, because
VB.NET and C# are both strongly typed languages. Plus, all the tools available
to the .NET developer are applicable to the .aspx developer.
6) In ASP.NET it is no longer possible to include executable code outside the
scope of a function within a script block marked as runat=server, and conversely,
it is no longer possible to define a function within a pair of server-side script tags.
7) But in ASP.NET, you are now required to place the Language directive with a
Page directive, as follows:
<%@Page Language="VB" Code Page="932"%> <%@Output Cache
Duration="60" Vary By Param="none" %>
You can have as many lines of directives as you need. Directives may be
located anywhere in your .apsx file but standard practice is to place them at the
beginning of the file. Several new directives have been added in ASP.NET.
Introduction to .NET / 7
1.5 SUMMARY
The fundamental idea behind .NET is that the focus is shifting from individual
Web sites or devices connected to the Internet to constellations of computers,
devices, and services that work together to deliver broader, richer solutions.
The .NET Framework is a key Microsoft offering and is intended to be used by
most new applications created for the Windows platform.
.NET Framework is designed for cross-language compatibility. Cross-language
compatibility means .NET components can interact with each other irrespective
of the languages they are written in.
All the languages supported by the .NET Framework is C++, C#, COBOL, Eiffel,
Java, Perl etc.
1. Microsoft MSDN
2. http://vig.prenhall.com/samplechapter/013093285X.pdf
3. Source: http://devreminder.wordpress.com/net/net-framework-fundamentals/
4. https://sites.google.com/site/entirefacts/dotnet
5. http://en.wikipedia.org/wiki/.NET_Framework_version_history
ASP .NET / 8
NOTES
Introduction to .NET / 9
NOTES
ASP .NET / 10
Chapter 2
C# Fundamentals
2.0 Objectives
2.1 Introduction
2.2 Writing Simple C# Program
2.3 Flow control
2.3.1 The if Statement
2.3.2 The Switch Statement
2.4 Boolean logic
2.5 The goto statement
2.6 Branching
2.7 Looping
2.7.1 Do Statement
2.7.2 For Statement
2.7.3 For Reach Statement
2.7.4 While Statement
2.8 OOP in C#
2.8.1 Constructors & Overloading
2.8.2 Namespace & Class Library
2.9 Inheritance
2.10 Summary
2.11 Check your Progress - Answers
2.12 Questions for Self – Study
2.13 Suggested Readings
2.0 OBJECTIVES
After studying this chapter you will be able to –
Explain simple C# program.
explain the flow control from C#
explain the various statements like goto, branching, and looping
explain OOP in C#
2.1 INTRODUCTION
Microsoft has also developed a brand new programming language C# (C
Sharp). This language makes full use of .NET. It is a pure object oriented language.
C# is a simple, modern object oriented and type-safe programming language derived
from C and C++. It will immediately be familiar to C and C++ programmers. C# aims to
combine the high productivity of visual basic and the raw power of C++.
Visual C# .NET is Microsoft’s C# development tool. It includes an interactive
development environment, visual designers for building windows and web applications,
a compiler, and a debugger. Visual C# .NET is part of a suite of products; call Visual
Studio .NET, which also included Visual Basic .NET, Visual C++ .NET, and the Jscript
scripting language. All of these languages provide access to the Microsoft .NET
Framework, which includes a common execution engine and a rich class library.
C# Fundamentals / 11
The modern design of C# eliminates the most common C++ programming
errors. C# empowers the traditional C/C++ programmer by providing:
Automated garbage collection that relieves the programmer of the burden of
manual memory management
Automatically initialized variables
Type-safe variables
C# is a language that makes it far easier for developers to create and maintain
applications that solve complex business problems.
using System;
class Hello
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, world");
}
}
The default file extension for C# programs is .cs, as in hello.cs. The name of
the program can be hello.cs or any name you want.
OUTPUT: Hello, world
ASP .NET / 12
2.3.1 The if statement
if (Char.IsUpper(c))
{
Console.WriteLine("Character is uppercase.");
}
else if (Char.IsLower(c))
{
Console.WriteLine("Character is lowercase.");
}
else if (Char.IsDigit(c))
{
Console.WriteLine("Character is a number.");
}
else
{
Console.WriteLine("Character is not alphanumeric.");
}
}
}
Input
ABC
Output
Enter a character: ABC
The character is uppercase.
C# Fundamentals / 13
2.3.2 The Switch Statement
The switch statement is a control statement that handles multiple selections
and enumerations by passing control to one of the case statements within its body as
the following example:
// statements_switch.cs
using System;
class SwitchTest
{
static void Main()
{
Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");
Console.Write("Please enter your selection: ");
string s = Console.ReadLine();
int n = int.Parse(s);
int cost = 0;
switch(n)
{
case 1:
cost += 25;
break;
case 2:
cost += 25;
goto case 1;
case 3:
cost += 50;
goto case 1;
default:
Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
break;
}
if (cost != 0)
{
Console.WriteLine("Please insert {0} cents.", cost);
}
Console.WriteLine("Thank you for your business.");
}
}
Input
2
Sample Output
Coffee sizes: 1=Small 2=Medium 3=Large
Please enter your selection: 2
Please insert 50 cents.
Thank you for your business.
Example 2:
// statements_switch2.cs
using System;
class SwitchTest
{
static void Main()
{
int n = 2;
switch(n)
{
case 1:
case 2:
case 3:
Console.WriteLine("It's 1, 2, or 3.");
break;
default:
Console.WriteLine("Not sure what it is.");
break;
ASP .NET / 14
}
}
}
Output
Its 1, 2 or 3
C# Fundamentals / 15
2.5 THE GOTO STATEMENT
The goto statement transfers the program control directly to a labeled
statement. A common use of goto is to transfer control to a specific switch-case label
or the default label in a switch statement. The goto statement is also useful to get out
of deeply nested loops.
Example:
// statements_goto_switch.cs
using System;
class SwitchTest
{
static void Main()
{
Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");
Console.Write("Please enter your selection: ");
string s = Console.ReadLine();
int n = int.Parse(s);
int cost = 0;
switch (n)
{
case 1:
cost += 25;
break;
case 2:
cost += 25;
goto case 1;
case 3:
cost += 50;
goto case 1;
default:
Console.WriteLine("Invalid selection.");
break;
}
if (cost != 0)
{
Console.WriteLine("Please insert {0} cents.", cost);
}
Console.WriteLine("Thank you for your business.");
}
}
Input
2
Sample Output
Coffee sizes: 1=Small 2=Medium 3=Large
Please enter your selection: 2
Please insert 50 cents.
Thank you for your business.
2.6 BRANCHING
Changing the flow of control in a program in response to some kind of input or
calculated value is an essential part of a programming language. C# provides the
ability to change the flow of control, either unconditionally, by jumping to a new
location in the code, or conditionally, by performing a test.
Example :
using System;
class Program
{
static void Main()
{
int x = 1;
ASP .NET / 16
int y = 1;
if (x == 1)
Console.WriteLine("x == 1");
else
Console.WriteLine("x != 1");
if (x == 1)
{
if (y == 2)
{
Console.WriteLine("x == 1 and y == 2");
}
else
{
Console.WriteLine("x == 1 and y != 2");
}
}
}
}
Output:
Student should evaluate this program for practice.
2.7 LOOPING
You can create loops by using the iteration statements. Iteration statements
cause embedded statements to be executed a number of times, subject to the loop-
termination criteria. These statements are executed in order, except when a jump
statement is encountered.
The following keywords are used in iteration statements:
do
for
foreach
while
2.7.1 Do statement
C# Fundamentals / 17
Output
0
1
2
3
4
2.7.2 For Statement
For loop executes a statement or a block of statements repeatedly until a
specified expression evaluates to false. For loop is handy for iterating over arrays and
for sequential processing. In the following example, the value of int i is written to the
console and i is incremented each time through the loop by 1.
Example :
// statements_for.cs
// for loop
using System;
class ForLoopTest
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
}
}
Output
1
2
3
4
5
2.8 OOP IN C#
What is OOP?
Object-oriented programming (OOP) is a programming paradigm that represents
concepts as "objects" that have data fields and associated procedures known as
methods. Objects, which are usually instances of classes, are used to interact with one
another to design applications and computer programs.
All code and data in C# must be enclosed in a class. You can't define a
variable outside of a class, and you can't write any code that's not in a class. Classes
can have constructors, which execute when an object of the class is created, and a
destructor, which executes when an object of the class is destroyed. Classes support
C# Fundamentals / 19
single inheritance, and all classes ultimately derive from a base class called object. C#
supports versioning techniques to help your classes evolve over time while maintaining
compatibility with code that uses earlier versions of your classes.
As an example, take a look at a class called Family. This class contains the
two static fields that hold the first and last name of a family member as well as a
method that returns the full name of the family member.
class Class1
{
public string FirstName;
public string LastName;
public string FullName()
{
return FirstName + LastName;
}
}
Note Single inheritance means that a C# class can inherit from only one base
class.
C# enables you to group your classes into a collection of classes called a
namespace. Namespaces have names, and can help organize collections of classes
into logical groupings. As you begin to learn C#, it becomes apparent that all
namespaces relevant to the .NET Framework begin with System. Microsoft has also
chosen to include some classes that aid in backwards compatibility and API access.
These classes are contained within the Microsoft namespace.
The most significant enhancement of the C++ language is its support for
object-oriented programming (OOP). You will have to modify your approach to problem
solving to derive all of the benefits of C++. For example, objects and their associated
operations must be identified and all necessary classes and subclasses must be
constructed.
2.8.1 Constructors and overloading
Often you'll want to have more than one function with the same name. The
most common example of this is to have more than one constructor. In the examples
shown so far, the constructor has taken a single parameter: a DateTime object. It would
be convenient to be able to set new Time objects to an arbitrary time by passing in year,
month, date, hour, minute, and second values. It would be even more convenient if
some clients could use one constructor, and other clients could use the other
constructor. Function overloading provides for exactly these contingencies.
The signature of a method is defined by its name and its parameter list. Two
methods differ in their signatures if they have different names or different parameter
lists. Parameter lists can differ by having different numbers or types of parameters. For
example, in the following code the first method differs from the second in the number of
parameters, and the second differs from the third in the types of parameters:
Source : Programming C#: Building .NET Applications with C#
By Jesse Liberty
ASP .NET / 20
System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}",
Month, Date, Year, Hour, Minute, Second);
}
// constructors
public Time(System.DateTime dt)
{
Year = dt.Year;
Month = dt.Month;
Date = dt.Day;
Hour = dt.Hour;
Minute = dt.Minute;
Second = dt.Second;
}
Sample Output:
5/1/2002 8:53:05
11/18/2005 11:3:30
As you can see, the Time class in Example has two constructors. If a function's
signature consisted only of the function name, the compiler would not know which
constructors to call when constructing t1 and t2. However, because the signature
includes the function argument types, the compiler is able to match the constructor call
C# Fundamentals / 21
for t1 with the constructor whose signature requires a DateTime object. Likewise, the
compiler is able to associate the t2 constructor call with the constructor method whose
signature specifies six integer arguments.
2.8.2 Namespaces and Class Library
Namespaces in the .NET Runtime are used to organize classes and other
types into a single hierarchical structure. The proper use of namespaces will make
classes easy to use and prevent collisions with classes written by other authors.
Namespaces can also be thought of as way to specify really long names for classes
and other types without having to always type a full name.
Namespaces are defined using the namespace statement. For multiple levels of
organization, namespaces can be nested:
namespace Outer
{
namespace Inner
{
class MyClass
{
public static void Function() {}
}
}
}
That’s a fair amount of typing and indenting, so it can be simplified by using the
following instead:
namespace Outer.Inner
{
class MyClass
{
public static void Function() {}
}
}
Each source file can define as many different namespaces as needed.
Class library — refers to an assembly that can be used by other assemblies.
Use of a class library does not cause the creation of a new application domain. Instead,
a class library is loaded into the application domain that uses it. For instance, when an
application uses a class library, that class library is loaded into the application domain
for that application. If an application uses a class library A that itself uses a class library
B, then both A and B are loaded into the application domain for the application.
2.8.3 Properties
A property is a member that provides access to a characteristic of an object or
a class. Examples of properties include the length of a string, the size of a font, the
caption of a window, the name of a customer, and so on. Properties are a natural
extension of fields. Both are named members with associated types, and the syntax for
accessing fields and properties is the same. However, unlike fields, properties do not
denote storage locations. Instead, properties have accessors that specify the
statements to be executed when their values are read or written. Properties are defined
with property declarations. The first part of a property declaration looks quite similar to a
field declaration. The second part includes a get accessor and/or a set accessor. In the
example below, the Button class defines a Caption property.
public class Button
{
private string caption;
public string Caption {
get {
return caption;
}
set {
caption = value;
ASP .NET / 22
Repaint();
}
}
…
}
Properties that can be both read and written, such as Caption, include both get and set
accessors. The get accessor is called when the property’s value is read; the set
accessor is called when the property’s value is written. In a set accessor, the new value
for the property is made available via an implicit parameter named value.
2.9 INHERITANCE
In C#, the specialization relationship is typically implemented using
inheritance. This is not the only way to implement specialization, but it is the most
common and most natural way to implement this relationship. Saying that ListBox
inherits from (or derives from) Window indicates that it specializes Window. Window is
referred to as the base class, and ListBox is referred to as the derived class. That is,
ListBox derives its characteristics and behaviors from Window and then specializes to
its own particular needs.
Implementing Inheritance : In C#, you can create a derived class by adding a colon
after the name of the derived class, followed by the name of the base class: public
class ListBox : Window. This code declares a new class, ListBox, which derived from
Window. You can read the colon as "derives from." The derived class inherits all the
members of the base class, both member variables and methods. The derived class is
free to implement its own version of a base class method. It does so by marking the
new method with the keyword new.
Example :. Using a derived class
using System;
public class Window
{
// constructor takes two integers to
// fix location on the console
public Window(int top, int left)
{
this.top = top;
this.left = left;
}
C# Fundamentals / 23
base(top, left) // call base constructor
{
mListBoxContents = theContents;
}
Drawing Window at 5, 10
Drawing Window at 20, 30
Writing string to the listbox: Hello world
Source : Learning C# 2005 by Jesse Liberty
b) Define inheritance.
……………………………………………………………………………………
……………………………………………………………………………………
2.10 SUMMARY
C# is a simple, modern object oriented and type-safe programming language
derived from C and C++.
ASP .NET / 24
The bool type represents Boolean logical quantities. The possible values of
type bool are true and false.
All code and data in C# must be enclosed in a class. Classes can have
constructors, which execute when an object of the class is created, and a
destructor, which executes when an object of the class is destroyed. Classes
support single inheritance, and all classes ultimately derive from a base class
called object.
C# Fundamentals / 25
NOTES
ASP .NET / 26
Chapter 3
3.0 Objectives
3.1 Introduction
3.2 Features of ASP.net 2.0
3.3 Stages in Web Forms Processing
3.4 Introduction to Server Controls
3.5 HTML Controls
3.6 Validation Controls
3.7 User Control
3.8 Data Binding Controls
3.9 Configuration
3.10 Personalization
3.10.1 User profiles
3.10.2 Personalization Providers
3.10.3 Using personalization
3.10.4 Defining profiles in Web .Config
3.10.5 User Profile information
3.10.6 Saving Profile Changes
3.10.7 Profiles and Users
3.11 Session State
3.12 Summary
3.13 Check your Progress - Answers
3.14 Questions for Self – Study
3. 15 Suggested Readings
3.0 OBJECTIVES
After studying this Chapter You will be able to –
explain the features of ASP.NET 2.0
discuss how Web Forms pages work in Web applications
discuss the HTML server controls with validation.
state Data Binding control in .NET
describe configuration and personalization?
3.1 INTRODUCTION
ASP.NET is a server-side Web application framework designed for Web
development to produce dynamic Web pages. It was developed by Microsoft to allow
programmers to build dynamic web sites, web applications and web services.
ASP.NET is the latest version of Microsoft's Active Server Pages technology
(ASP).
It is the next generation ASP, but it's not an upgraded version of ASP.
ASP.NET is an entirely new technology for server-side scripting. It was written from the
Introduction to ASP .NET 2.0 / 27
ground up and is not backward compatible with classic ASP. ASP.NET is the major
part of the Microsoft's .NET Framework.
Before you continue you should have a basic understanding of the following:
WWW, HTML, XML and the basics of building Web pages scripting languages like
JavaScript or VBScript the basics of server side scripting like ASP or PHP
What is ASP.NET?
ASP.NET is a server side scripting technology that enables scripts (embedded in web
pages) to be executed by an Internet server.
Microsoft Technology
ASP.NET is a program that runs inside IIS
IIS (Internet Information Services) is Microsoft's Internet server
IIS comes as a free component with Windows servers
IIS is also a part of Windows 2000 and XP Professional
ASP .NET / 28
Full support for XML standards like, XHTML, XML, and WSDL
Improved compilation and deployment (installation)
Improved site management
New and improved development tools
1) Master Pages : ASP.NET didn't have a method for applying a consistent look
and feel for a whole web site. Master pages in ASP.NET 2.0 solve this problem.
A master page is a template for other pages, with shared layout and
functionality. The master page defines placeholders for content pages. The
result page is a combination (merge) of the master page and the content page.
2) Themes : Themes are another feature of ASP.NET 2.0. Themes, or skins, allow
developers to create a customized look for web applications.
3) Web Parts : ASP.NET 2.0 Web Parts can provide a consistent look for a site,
while still allowing user customization of style and content.
New controls:
Zone controls - areas on a page where the content is consistent
Web part controls - content areas for each zone
Site Maps
Dynamic HTML menus
Tree Views
8) Data Access: Many web sites are data driven, using databases or XML files as
data sources. With ASP.NET this involved code, and often the same code had to
be used over and over in different web pages. A key goal of ASP.NET 2.0 was to
ease the use of data sources. ASP.NET 2.0 has new data controls, removing
much of the need for programming and in-depth knowledge of data connections.
9) Mobility Support: The problem with Mobile devices is screen size and display
capabilities. In ASP.NET, the Microsoft Mobile Internet Toolkit (MMIT) provided
this support. In ASP.NET 2.0, MMIT is no longer needed because mobile
support is built into all controls.
10) Images: ASP.NET 2.0 has new controls for handling images:
These controls are important for better image display on mobile devices, like hand-
held computers and cell phones.
11) Automatic Compilation: ASP.NET 2.0 provides automatic compilation. All files
within a directory will be compiled on the first run, including support for WSDL,
and XSD files.
13) Site Management: ASP.NET 2.0 has three new features for web site
configuration and management:
New local management console
New programmable management functions (API)
New web-based management tool
14) Development Tools: With ASP.NET Visual Studio.NET was released with
project and design features targeted at corporate developers. With ASP.NET
2.0, Visual Studio 2005 was released. Key design features for Visual Studio
2005 include:
Support for the features described above
Upload files from anywhere (FTP, File System, Front Page....)
No project files, allowing code to be manipulated outside Visual Studio
Integrated Web Site Administration Tool
No "build" step - ability to compile on first run
Visual Web Developer is a new free ASP.NET 2.0 tool for non-corporate developers
who don't have access to Visual Studio.NET.
ASP .NET / 30
Check your progress 3.2
Answer the following questions in 1-2 sentences.
a) What is ASP.NET?
…………………………………………………………………………………………..…
…………………………………………………………………………………………..…
b) Write any two ASP.NET features.
…………………………………………………………………………………………..…
…………………………………………………………………………………………..…
ASP.NET saves page and control properties between round trips. This is
referred to as saving the view state of the control.
It provides state management facilities so that you can save your own variable
and application-specific or session-specific information between round trips.
It can detect when a form is requested for the first time versus when the form
is posted, and allows you to program accordingly. You may want a different
behavior during a page postback versus an initial request.
ASP .NET / 32
3.4 INTRODUCTION TO SERVER CONTROLS
For creating Web Forms pages, you can use these types of controls:
HTML server controls HTML elements exposed to the server so you can
program them. HTML server controls expose an object model that maps very
closely to the HTML elements that they render.
Web server controls with more built-in features than HTML server controls. Web
server controls include not only form-type controls such as buttons and text boxes,
but also special-purpose controls such as a calendar. Web server controls are
more abstract than HTML server controls in that their object model does not
necessarily reflect HTML syntax.
Validation controls that incorporate logic to allow you to test a user's input. You
attach a validation control to an input control to test what the user enters for that
input control. Validation controls are provided to allow you to check for a required
field, to test against a specific value or pattern of characters, to verify that a value
lies within a range, and so on.
User controls that you create as Web Forms pages. You can embed Web
Forms user controls in other Web Forms pages, which is an easy way to create
menus, toolbars, and other reusable elements.
Every server control has a tag with the runat="server" attribute and is
converted to client-specific XHTML. ASP.NET server controls are objects and have
their own properties, methods and event handlers. Interesting to know is that server
controls can keep their state (value and design) stored between subsequent page
requests thanks to StateView.
Every control is derived from the Control class and inherits the properties and the
methods of this Control class. The most useful inherited properties are:
Controls: gives a collection with all the child controls for a specified server
control
EnableViewState: Boolean to decide whether the control has to track his
current state or not
ID: id of the server control, maybe the most important property
Visible: Boolean to decide if the control will be rendered
The most useful inherited methods are:
DataBind(): binds the control with a certain data source (e.g. resultset of an sql
query)
FindControl(): searches a child control with the given name (string)
HasControls(): Booleans that defines if this server control owns child controls
1) Page in ASP.NET
It might sound strange but the whole page is a control itself and acts as
container for everything that is placed in it. Some of the properties are: Title,
Session, Cache, Trace, Special on the Page control are the directives (start with
a @). In the Page directive you find what language is used for the code behind,
the path to the source file and the name of the class in the code behind and
possible extra properties for the page document.
2) Label Control
The Label control displays text in a set location on the page. Unlike static text,
the Text property of a label can be changed programmatically. Layout of the
text can be done programmatically by changing properties or with HTML tags
(which are allowed) in the text itself.
3) TextBox Control
The TextBox control enables the user to enter text. You have the possibility to
use the textbox as a single line, multiline or password field by changing the
TextMode property. The display width of a textbox is determined by its
Columns property and the height of a textbox is determined by the Rows
property (only for MultiLine textmode). You can limit the number of signs the
user can enter for a textbox with its textmode set to SingleLine or Password by
entering a value for MaxLength.
4) Button Control
The Button control is used to submit the form back to the server (postback). This
happens automatically in opposite to other controls where you have to enable
the AutoPostBack property to have the same effect. Buttons have a Causes
Validation property to trigger validation of all validation controls assigned to the
same group.
It is possible to use several buttons in a container control like a DataGrid or a
GridView. All these buttons have the same ID and it will be impossible to bind an
event handler to each button control's OnClick event (or other event) to
determine the particular button that was clicked. That's why buttons have a
CommandName and CommandArgument property to determine which
button you clicked and deliver the correct arguments to the event handler.
There are three types of buttons: the standard button, the ImageButton
(image acting as a button) and the LinkButton (link acting as a button). Notice
that the ImageButton doesn't have a Text property, but instead it does have an
AlternateText property which shows the entered text if the browser doesn't
support images.
ASP .NET / 34
5) DropDownList Control
The DropDownList control provides a single-select dropdown list. Each list item
has a value and an index. You can add items to the list one by one yourself or
by data binding a static array or another data source (e.g. results from a sql
query). To bind a data source you'll be using the DataTextField property to
link the text content and the DataValueField property to link the value of each
list item.
There are several ways to add items to the list at Design time. In design view
you can use the smart tag 'Edit items' which shows on the dropdown list or you
can click on the "..." next to the property Items. Both give the same window in
which you can add the items one by one. Or you can write the code for each list
item in the source view.
8) Panel Control
The panel control is mainly used as a container for other controls. It's useful to
group, hide or generate controls programmatically. If you generate controls
programmatically you'll have to recreate them every time you load the page
since the ViewState only remembers the state and not the controls you
generated. If you only want to generate controls you can replace the panel by a
PlaceHolder.
3.5 HTML CONTROLS
HTML elements in ASP.NET files are, by default, treated as text. To make
these elements programmable, add a runat ="server" attribute to the HTML element.
This attribute indicates that the element should be treated as a server control.
Note: ASP.NET requires that all HTML elements must be properly closed and properly
nested.
ASP .NET / 36
1) Example of HTMLButton
<script runat="server">
Sub button1(Source As Object, e As EventArgs)
p1.InnerHtml="You clicked the blue button!"
Sub button2(Source As Object, e As EventArgs)
p1.InnerHtml="You clicked the pink button!"
End Sub
</script>
<html>
<body>
<form runat="server">
<button id="b1" OnServerClick="button1"
style="background-color:#e6e6fa;
height=25;width:100" runat="server">
Blue button!
</button>
<button id="b2"
OnServerClick="button2"
style="background-color:#fff0f5;
height=25;width:100" runat="server">
Pink button!
</button>
<p id="p1" runat="server" />
</form>
</body>
</html>
Output Result
2) Example of HTMLForm
<script language = “vb” runat= "server">
if name.value<>"" then
p1.InnerHtml="Welcome " & name.value & "!"
end if
End Sub
</script>
<html>
<body>
<form runat="server">
Enter your name: <input id="name" type="text" size="30" runat="server" />
<br /><br />
<input type="submit" value="Submit" OnServerClick="submit" runat="server" />
<p id="p1" runat="server" />
</form>
</body>
</html>
3) Example of HtmlInputCheckBox
<script language = “vb” runat="server">
if red.Checked=True then
p1.InnerHtml="You prefer red!"
else
p1.InnerHtml="You prefer blue!"
end if
red.checked=false
blue.checked=false
End Sub
</script>
<html>
<body>
<form runat="server">
What color do you prefer?
<br />
<input id="red" type="checkbox" runat="server" /> Red
<br />
<input id="blue" type="checkbox" runat="server" /> Blue
<br />
<input type="button" value="Submit" OnServerClick="submit" runat="server"/>
<p id="p1" runat="server" />
</form>
</body>
</html>
Output Result
ASP .NET / 38
If Validation is true
Compare two
data is saved
values
Validate
<form runat="server">
<table border="0" bgcolor="#b0c4de">
<tr valign="top">
<td colspan="4"><h4>Compare two values</h4></td>
</tr>
<tr valign="top">
<td><asp:TextBox id="txt1" runat="server" /></td>
<td> = </td>
<td><asp:TextBox id="txt2" runat="server" /></td>
<td><asp:Button Text="Validate" runat="server" /></td>
</tr>
</table>
<br />
<asp:CompareValidator
id="compval"
Display="dynamic"
ControlToValidate="txt1"
ControlToCompare="txt2"
ForeColor="red"
BackColor="yellow"
Type="String"
Introduction to ASP .NET 2.0 / 39
EnableClientScript="false"
Text="Validation Failed!"
runat="server" />
</form>
</body>
</html>
Output Result :
<form runat="server">
Enter a date between 2005-01-01 and 2005-12-31:
<br />
<asp:TextBox id="tbox1" runat="server" />
<br /><br />
<asp:Button Text="Submit" runat="server" />
<br /><br />
<asp:RangeValidator
ControlToValidate="tbox1"
MinimumValue="2005-01-01"
MaximumValue="2005-12-31"
Type="Date"
EnableClientScript="false"
Text="The date must be between 2005-01-01 and 2005-12-31!"
runat="server" />
</form>
</body>
</html>
Output Result :
ASP .NET / 40
Writing Your First User Control
Actually, writing a basic user control (also sometimes called pagelets) couldn't
be much easier... most any ASP.NET page can be used as a server control. Here's a
simple example:
basic.ascx
<p>
This is a user control... really!
</p>
<html>
<head>
<title>ASP.NET User Control Sample - Basic</title>
</head>
<body bgcolor="#FFFFFF">
<asp101samps:SomeText runat="server" />
</body>
</html>
The above page will output a standard HTML page with the text contained in
our user control in place of the user control's tag. How does it do it? The magic here is
in the Register directive. To use it you'll need to specify three attributes:
TagPrefix : The TagPrefix attribute defines a namespace in which the control
will live. You can think of this as the world in which the control will live. Because of this,
you can have different controls with the same name and as long as they have a
different TagPrefix (and as a result different namespaces) they can peacefully co-exist
on the same page.
TagName : The TagName attribute determines the name by which the control
will be refered to. It needs to be unique within the namespace, but you can choose
whatever you like. Generally names are chosen that are indicative of what the control
actually does.
Src : The Src (or source) attribute simply specifies where the code that makes
up the control being defined is to be found. Virtual paths are used so the value should
be something like "control.ascx" or "/path/control.ascx" and not a physical path like
"C:\path\control.ascx."
Once you've added the Register directive, the control is registered and can be
used just like any other server control. You specify the TagPrefix and TagName in the
control's tag just like you would with a built in control and make sure you've got the
runat="server" attribute and you're ready to roll. Here's the basic form for a user
control's tag:
<TagPrefix:TagName runat="server" />
properties.ascx
<p>
<font color="<%= Color %>">
<%= Text %>
</font>
</p>
By default the control will look the same as before, but now we can modify the
color or text it emits either by setting properties in the control's tag or programmatically
from our code (as long as we give the control an id attribute by which to reference it).
Also note that I'm able to reuse the same control a number of times in the page and
set the properties of each instance independently.
properties.aspx
<html>
<head>
<title>ASP.NET User Control Sample - Properties</title>
</head>
<body bgcolor="#FFFFFF">
</body>
</html>
events.ascx
If Page.IsPostBack Then
If txtName.Text = strInitialText
ASP .NET / 42
txtName.Text = ""
End If
Else
txtName.Text = strInitialText
End If
End Sub
<asp:RequiredFieldValidator ControlToValidate="txtName"
id="valtxtName" Display="Dynamic" runat=server>
Please Enter a Name!
</asp:RequiredFieldValidator>
events.aspx
<html>
<head>
<title>ASP.NET User Control Sample - Validation & Events</title>
</head>
<body bgcolor="#FFFFFF">
<form runat="server">
<br />
</form>
</body>
</html>
The following controls are list controls which support data binding:
asp:RadioButtonList
asp:CheckBoxList
asp:DropDownList
asp:Listbox
The selectable items in each of the above controls are usually defined by one
or more asp:ListItem controls, like this:
<html>
<body>
<form runat="server">
<asp:RadioButtonList id="countrylist" runat="server">
<asp:ListItem value="N" text="Norway" />
<asp:ListItem value="S" text="Sweden" />
<asp:ListItem value="F" text="France" />
<asp:ListItem value="I" text="Italy" />
</asp:RadioButtonList>
</form>
</body>
</html>
However, with data binding we may use a separate source, like a database,
an XML file, or a script to fill the list with selectable items. By using an imported
source, the data is separated from the HTML, and any changes to the items are made
in the separate data source.
Example of ArrayList RadioButtonList
ASP .NET / 44
<script language = “VB” runat="server">
Sub Page_Load (S as object, e As Event Args)
if Not Page.IsPostBack then
dim mycountries=New ArrayList
mycountries.Add("Norway")
mycountries.Add("Sweden")
mycountries.Add("France")
mycountries.Add("Italy")
mycountries.TrimToSize()
mycountries.Sort()
rb.DataSource=mycountries
rb.DataBind()
end if
end sub
<html>
<body>
<form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" onSelectedIndexChanged="displayMessage" />
<p><asp:label id="lbl1" runat="server" /></p>
</form>
</body>
</html>
Output Result :
3.9 CONFIGURATION
The ASP.NET configuration system features an extensible infrastructure that
enables you to define configuration settings at the time your ASP.NET applications are
first deployed so that you can add or revise configuration settings at any time with
minimal impact on operational Web applications and servers.
ASP .NET / 46
Profile schema is defined within Web.Config as name/type pairs. Imagine that
in the course of designing your site, you decided you'd like to track the following
information about a particular user:
User name
Gender
Visit count
Birthday
Defining these properties is a matter of populating them in Web.Config. A
definition for the properties listed above might look like this Web.Config:
<system.web>
<profile automaticSaveEnabled="true" >
<properties>
<add name="NumVisits" type="System.Int32"/>
<add name="UserName" type="System.String"/>
<add name="Gender" type="bool">
<add name="Birthday" type="System.DateTime">
</properties>
</profile>
</system.web>
The personalization properties consist of name/type pairs and will basically
become the schema under which the personalization data will be stored. Once defined
in the Web.Config file, the profile may be used in the site through the Profile property
found in the current HttpContext (and is also available via the Page).
3.10.5 Use Profile Information
To use the profile in the Web site, you access it in much the same way you
might access session state. However, instead of being represented by name/value
pairs accessed through an indexer, the ASP.NET compiler will synthesize a profile
object based upon the scheme defined in the Web.Config file.
For example, given the schema listed above, ASP.NET will synthesize a class
named ProfileCommon, based upon the ProfileBase class. The synthesized class will
reflect the instructions written into the Web.Config by inserting properties, shown here
in bold:
public class ProfileCommon : ProfileBase
{
public virtual HttpProfile GetProfile(string username);
public object GetPropertyValue(string propertyName);
public void SetPropertyValue(string propertyName,
object propertyValue);
public HttpProfileGroupBase GetProfileGroup(String groupName);
public void Initialize(String username,Boolean isAuthenticated);
public virtual void Save();
public void Initialize(SettingsContext context,
SettingsPropertyCollection properties,
SettingsProviderCollection providers);
public string UserName{get; set;};
public int NumVisits{get; set;};
public bool Gender(get; set; );
public DateTime Birthdate{get; set; };
}
To access the profile properties, simply use the Profile property within the
page. The Profile property is an instance of the Profile Common class synthesized by
ASP.NET. Just access the members of the Profile, like so:
protected void Page_Load(object sender, EventArgs e)
{
if (Profile.Name != null)
{
Introduction to ASP .NET 2.0 / 47
Response.Write("Hello " + Profile.Name);
Response.Write("Your birthday is " +
Profile.Birthdate);
}
}
Profile information is associated with the current user based upon the identity
of the user. By default, ASP.NET uses the User.Identity.Name within the current
HttpContext as the key to store data. By default, profiles are available only for
authenticated users.
ASP.NET supports anonymous profiles as well. Turn this on within
Web.Config. The default tracking mechanism for anonymous profiles is to use cookies.
However, as with tracking session state, you may tell ASP.NET to use a mangled
URL.
The following exercise illustrates using personalization profiles based on the
user's login ID.
Using Profiles
1. Create a new project. Name the project MakeItPersonal.
2. Add a Web.Config file to the project. Update Web.Config to include some
profile properties. The example here includes a user name, a Theme, and a
birth date. Be sure to turn anonymous Identification to true. The following
example shows that you may group and nest profile structures using the
<group> element.
<system.web>
<profile>
<properties >
<add name="Theme" type="System.String"/>
<add name="Name" type="String"/>
<add name="Birthdate"" type="System.DateTime"/>
<group name="Address">
<add name="StreetAddress"/>
<add name="City"/>
<add name="State"/>
<add name="ZipCode"/>
</group>
</properties>
</profile>
</system.web>
1. Borrow the Default and SeeingRed Themes from the MasterPagesSite project.
This will let the user pick the Theme.
2. Borrow the UseThemes.aspx and .cs files from the MasterPagesSite project.
3. Borrow the Banner.ascx file from the MasterPagesSite.
ASP .NET / 48
4. Now update the Default.aspx page. This will be where users type profile
information. Add text boxes for the name, address, city, state, and zip code.
Add a drop-down list box populated with Default and SeeingRed items. This
will be used for selecting the Theme. Also add a calendar control to pick the
birthdate.
5. Add a button the user may click to submit profile information. Add a handler to
input these values into the profile. Double-click on the button to add the
handler.
The input screen should look something like this:
6. Update Page_Load to display profile information (if it's there). Grab the profile
object and set each of the text boxes and the calendar control.
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
{
ProfileCommon pc = this.Profile.GetProfile(Profile.UserName);
if (pc != null)
{
this.TextBoxName.Text = pc.Name;
this.TextBoxAddress.Text = pc.Address.StreetAddress;
this.TextBoxCity.Text = pc.Address.City;
this.TextBoxState.Text = pc.Address.State;
this.TextBoxZipCode.Text = pc.Address.ZipCode;
this.DropDownList1.SelectedValue = pc.Theme;
this.Calendar1.SelectedDate = pc.Birthdate;
}
}
}
// …
}
ProfileCommon pc = this.Profile.GetProfile(Profile.UserName);
if (pc != null)
{
pc.Name = this.TextBoxName.Text;
pc.Address.StreetAddress = this.TextBoxAddress.Text;
pc.Address.City = this.TextBoxCity.Text;
pc.Address.State = this.TextBoxState.Text;
pc.Address.ZipCode = this.TextBoxZipCode.Text;
pc.Theme = this.DropDownList1.SelectedValue;
pc.Birthdate = this.Calendar1.SelectedDate;
pc.Save();
}
}
8. Finally, update the UseThemes.aspx page to use the Theme. Override the
page's OnPreInit method. Have the code apply the Theme as specified by the
profile.
9. When you surf to the page, you should be able to enter the profile information
and submit it. Following your initial visit, the profile will be available whenever
you hit the site.
ASP maintains session state by providing the client with a unique key
assigned to the user when the session begins. This key is stored in an HTTP cookie
that the client sends to the server on each request. The server can then read the key
from the cookie and re-inflate the server session state.
Config.web
There are two types of configuration files: a machine configuration file and an
application configuration file, both named config.web. The two are identical, except
that the machine configuration file applies settings to all applications but the
application configuration files are either restrictive or expansive on an application-by-
application basis.
The machine config.web file is in the WinNT\Microsoft.NET\Framework\v1.0.2204
directory, while the optional application configuration files exist in the application's
directory. Application config.web files are optional in the sense that if an application
config.web file doesn't exist, the machine config.web settings are used instead.
ASP.NET session state settings can be made in the machine config.web file and
overridden in a particular application's config.web file.
Session configuration
Below is a sample config.web file used to configure the session state settings for an
ASP.NET application:
<configuration>
<sessionstate
mode="inproc"
cookieless="false"
timeout="20"
sqlconnectionstring="data source=127.0.0.1;user id=<user
id>;password=<password>"
server="127.0.0.1"
port="42424"
/>
</configuration>
<form runat=server>
<input id=text1 type=text runat=server>
<input type=submit runat=server
OnServerClick="Session_Add" Value="Add to Session State">
<input type=submit runat=server
OnServerClick="CheckSession" Value="View Session State">
</form>
<hr size=1>
<font size=6><span id=span1 runat=server/></font>
This simple page wires up two server-side events for the Add and View buttons, and
simply sets the session state to the value in the text box.
3.12 SUMMARY
Web Forms Page Life Cycle for a Web Forms page is similar to that of any Web
process that runs on the server. Certain characteristics of Web
processing information is passed through HTTP protocol, the stateless nature of
Web pages, the ASP.NET page framework performs many Web application
services for us. It is important to understand the sequence of events that occur
when a Web Forms page is processed.
ASP.NET server controls are objects and have their own properties, methods
and event handlers. HTML elements in ASP.NET files are, by default, treated as
text. To make these elements programmable, add a runat ="server" attribute to
the HTML element. This attribute indicates that the element should be treated as
a server control.
The support ASP.NET provides for personalization service greatly simplifies the
whole management and storage of personal information. Defining a Web site's
personalization facilities begins with defining User Profiles.
A session is defined as the period of time that a unique user interacts with a
Web application. Session state is a collection of objects, tied to a session are
stored on a server.
ASP .NET / 54
NOTES
ASP .NET / 56
Chapter 4
4.0 Objectives
4.1 Introduction
4.2 Assignment and Initialization of variable
4.3 Arrays
4.4 Enumerations
4.5 Variable Operations
4.5.1 Advance & Math Operations
4.5.2 Type Conversions
4.6 Object Based Manipulation
4.6.1 The string object
4.6.2 Date Time object and Time span
types object
4.6.3 The Array Object
4.7 Conditional Structures
4.8 Loop Structures
4.9 Functions & Subroutines
4.10 Summary
4.11 Check your Progress – Answers
4.12 Questions for Self – Study
4.13 Suggested Readings
4.0 OBJECTIVES
After studying this chapter you will be able to –
explain various data types
explain Arrays and Enumerations
discuss various conditional structures and examples.
describe the variable operations
explain Function and its use.
4.1 INTRODUCTION
As with all programming languages, you keep track of data in C# using
variables. Variables can store numbers, text, dates, and times, and they can even
point to full-fledged objects.
When you declare a variable, you give it a name, and you specify the type of
data it will store. To declare a local variable, you start the line with the data type,
followed by the name you want to use. A final semicolon ends the statement:
Every .NET languages use the same variable data types. Different languages
may provide slightly different names (for example, a VB Integer is the same as in C#
int), but the CLR make no distinction, in fact, they are just two different names for the
same base data type. This design allows for deep language integration. Because
languages share the same core data types, you can easily use objects written in
one.NET language in an application written in another .Net language. No data type
conversions are required.
To create this common data type system, Microsoft needed to iron out many of
the inconsistencies that existed between VBScript, VB6, C++, and other languages.
The solution was to create a set of basic data types, which are provided in the .NET
Class library.
C# VB .NET Type
Contains
Name Name Name
byte Byte Byte An integer from 0 to 255.
short Short Int16 An integer from-32,768 to 32,767
int Integer Int32 An integer from -2,147,483,648 to 2,147,483,647.
long Long Int64 An integer from about -9.2e18 to 9.2e18.
A single-precision floating point number from
float Single Single approximately -3.4e38 to 3.4e38 (for big numbers) or -
1.5e-45 to 1.5e-45 (for small fractional numbers).
A double-precision floating point number from
double Double Double approximately -1.8e308 to 1.8e308 (for big numbers)or
-5.0e-3245 to 5.0e-324 (for small fractional numbers).
A 128-bit fixed-point fractional number that supports up
decimal Decimal Decimal
to 28 significant digits.
char Char Char A single 16-bit Unicode character.
string String String A variable-length series of Unicode characters.
bool Boolean Boolean A true or false value.
Represents any date and time from 12.00.00 AM,
January 1 of the year 1 in the Gregorian calendar, to
11.59.59 PM, December 31 of the year 9999.Times
* Date DateTime
values can resolve values to 100 nano-second
increments. Internally, this data type is stored as a 64-
bit integer.
Represents a period of time, as in ten seconds or three
* * Timespan days. The smallest possible interval is 1 tick (100
nanoseconds).
The ultimate base class of all .NET types. Can contain
object Object Object
any data type or object.
You can also declare a variable by using the type name from the .NET class
library. This approach produces identical variables. It's also a requirement when the
data type doesn't have an alias built into the language. For example, you can rewrite
the earlier example that used C# data type name with this code snippet that uses the
class library names:
System.Int32 errorCode ;
System.String myName ;
This code snippet uses fully qualified type names that indicate that the Int32
type and the String type are found in the System namespace (along with all the most
fundamental types). In Chapter 3, you'll learn about types and namespaces in more
detail.
ASP .NET / 58
4.2 ASSIGNMENT AND INITILIZATION OF VARIABLE
Once you've declared your variable, you can freely assign values to them, as
long as these values have the correct data type.
Here's the code that shows this two-steps process:
// Declare variables.
int errorCode ;
string myName ;
//Assign Values.
errorCode = 10 ;
myName = "Matthew";
You can also assign a value to a variable in the same line that you declare it.
This example compresses four lines of code in two:
int errorCode = 10 ;
string myName = "Matthew";
C# safeguards you from errors by restricting you from uninitialized variables. This
means the following code will not succeed:
Interestingly, if you're using code like this to declare and initialize variable in
one step, and if the C# compiler can determine the right data type based on the value
you're using, you don't need to specify the data type. Instead, you can use the all-
purpose var keyword in place of the data type.
That means the previous line of code is equivalent to this:
Here the compiler realizes that a decimal data type is the most appropriate
choice for the myDecimal variable, and uses that data type automatically. There is no
performance difference. The myDecimal variable that you create using an inferred data
type behaves in exactly the same way as a myDecimal variable created with an explicit
data type. In fact, the low-level code that the compiler generates is identical. The only
difference is that the var keyword saves some typing.
Many C# programmers feel uneasy with the var keyword because it makes code less
clear. However, the var keyword is a more useful shortcut when creating objects, as
you'll see in the next chapter.
You can also insert a special character based on its hex code using the syntax
\x123. This inserts a single character with hex value 123
Note that in order to specify the actual backslash character (for example, in a
directory name), you require two slashes.
Example:
4.3 ARRAYS
Arrays allow you to store a series of values that have the same data type.
Each individual value in the array is accessed using one or more index numbers. It's
often convenient to picture arrays as list of data (if the array has more than one
dimension) or grids of data (if the array has two dimensions). Typically, arrays are laid
out contiguously in memory.
All arrays start at a fixed lower bound. This rule has no exceptions. When you
create an array in C#, you specify the numbers of elements. Because counting starts
at 0, the highest index is actually one fewer than the number of elements.
// create an array with four strings (from index 0 to index 3).
// You need to initialize the array with the new keyword in order to use it:
string [ ] vStringArray1 = new string [4] ;
By default, if your array includes simple data types, they are all initialized to
default values (0 or false), depending on whether you are using some type of number
or a Boolean variable. You can also fill in an array with data at the same time that you
create it. In this case, you don't need to explicitly specify the number of elements,
because .NET can determine it automatically
// Create an array with four strings, one for each number from 1 to 4.
ASP .NET / 60
string [ ] vStringArray2 = { "1" , "2" , "3" , "4" } ;
The same technique works for multidimensional arrays, except that two sets of curly
brackets are required:
// Create a 4x2 array (a grid with four rows and two columns).
int [ , ] vIntArray2 ={{1, 2},{3, 4},{5, 6},{7, 8}} ;
The ArrayList
C# arrays do not support redimensioning. This means that once you create an
array, you can't change its size. Instead, you would need to create a new array with
the new size and copy values from the old array to the new, which would be a tedious
process. However, if you need a dynamic-library array-like list, you can use one of the
collection classes provided to all.NET languages trough the .NET class library. One of
the simplest collection classes that .NET offers is the ArrayList, which always allows
dynamic resizing.
4.4 ENUMERATIONS
An enumeration is a group of related constants; each of which is given a
descriptive name. Each value in an enumeration corresponds to a preset integer. In
your code, however, you can refer to an enumerated value by name, which makes
your code clearer and helps prevent errors. For example, it's much more
straightforward to set the border of a label to the enumerated value
BorderStyle.Dashed rather than the obscure numeric constant 3. In this case, Dashed
is a value in the BorderStyle enumeration, and it represents the number 3.
Here's an example of an enumeration that defines different types of users:
enum ErrorCode
{
NoResponse = 166 ,
TooBusy = 167 ,
Pass = 0
}
Now you can use the ErrorCode enumeration with a function that returns an
integer representing an Error Condition as show here:
ErrorCode vError ;
vError = Dosomething() ;
if (vError == ErrorCode .Pass )
{
// Operation Succeeded.
}
Clearly, enumerations create more readable code. They also simplify coding, because
once you type in the enumerations type name (ErrorCode) and add the dot (.), Visual
Studio will pop up a list of possible values using IntelliSense.
Examples :
The following sample will demonstrate arrays. Drag a button and a textbox
control on to the Web Forms page. Open the code designer window and paste the
following code.
ASP .NET / 62
Private void Button1_Click ( System.Object Sender, System.EventArgs e) {
String [ ] Sports = new String [6];
Sports[0]="Tennis"
Sports[1] = "Cricket"
Sports[2] = "Rubgy"
Sports[3] = "Aussie Rules"
Sports[4] = "Soccer"
Sports[5] = "Hockey"
Label1.Text = "The sport in the location you entered is" + " " +
Sports(Convert.toInt32(TextBox1.Text));
}
Output Result
Enter a number between 0 and 5 to get the Sport stored in that location
The above sample code creates a Sports array with six elements, asks the
user to enter a number between 0 and 5 and displays the sport that is stored in the
location (number) the user entered on a label when the button is clicked.
Strings
Strings are supported by the .NET String class. The String data type can
represent a series of characters and can contain approximately up to 2 billion Unicode
characters. There are many built-in functions in the String class. Some .NET
Framework functions are also built into the String class. Some common String
functions are discussed below:
Sample Application
The following is a simple and interesting sample. It asks the user to enter
some information and generates a username and password based on the information
entered and displays the newly generated login information to the user. To start,
drag six labels, four textboxes and a button control on to the Web Forms page.
TextBox1 accepts first name, TextBox2 accepts last name, TextBox3 accepts age and
TextBox4 accepts country. Look at the sample below for the user interface. Open the
code designer window and paste the following code.
Output Result
ASP .NET / 64
Operator Description Example
+ Addiction 1+1=2
- Subtration 5-2=3
* Multiplication 2 * 5 = 10
/ Division 5.0 / 2 = 2.5
Gets the remainder left after integer 7 % 3 = 1 (7 % 3 = ( 3 + 3 = 6 ) leaves
%
division 1 as result)
Divisions can sometimes cause confusion in C#. If you divide one integer by
another integer, C# performs integer division. That means it automatically discards the
fractional part of the answer and returns the whole part as an integer. For example, if
you divide 5 by 2, you'll end up with 2 instead of 2.5.
The solution is to explicitly indicate that one of your numbers is a fractional
value. For example, if you replace 5 with 5M, C# will treat the 5 as a decimal. If you
replace 5 with 5.0, C# will treat it as a double. Either way, the division will return the
excepted value of 2.5. Of course, this problem doesn't occur very often in real-world
code, because then you're usually dividing one variable by other variable.
The operators in Table are designed for manipulating number. However, C#
also allows you to use the addition operator (+) to join two strings:
Here is an example:
int vMySmallValue;
long vMyLargeValue;
// Get the largest value possible value that can be stored as a 32-bit integer.
// .NET provides a constant named Int32.MaxValue that provides this number.
vMySmallValue = Int32.MaxValue ;
// This always succeeds. No matter how large vMySmallValue is,
// it can be contained in vMyLargeValue.
vMyLargeValue = vMySmallValue ;
The following code shows how to change a 32-bit integer to a 16-bit integer:
int vCount32 = 1000 ;
short vCount16;
// Convert the 32-bit integer to a 16-bit integer.
// If vCount32 is too large to fit, .NET will discard some of the
// information you need, and the resulting number will be incorrect.
vCount16 = ( short )vCount32 ;
If you don't use an explicit cast when you attempt to perform a narrowing
conversion, you'll receive an error when you try to compile your code. However, even if
you perform an explicit conversion, you could still end up with a problem.
For example, consider the code shown here, which causes an overflow:
int vMySmallValue;
long vMyLargeValue;
vMyLargeValue = Int64.MaxValue ;
// This will appear to succeed (there won't be an error at runtime),
// but your data will be incorrect because vMySmallValue cannot
// hold a value this large.
vMySmallValue = ( int )vMyLargeValue ;
The .Net languages differ in how they handle this problem. In VB, you'll always
receive a runtime error that you must intercept and respond to. In C#, however, you'll
simply bind with incorrect data in vMySmallValue. To avoid this problem, you should
either check that your data is not to large before you attempt a narrowing conversion
(which is always a good idea) or use a checked block. The checked block enables
overflow checking for a portion of code.
ASP .NET / 66
If an overflow occurs, you'll automatically receive an error, just like you would in VB:
checked
{
// This will cause an exception to be thrown.
vMySmallValue = ( int )vMyLargeValue ;
}
In C#, you can't use casting to convert numbers to strings, or vice versa. In this case,
the data isn't just being moved from one variable to another, it needs to be translated
to a completely different format. Thankfully, .NET has a number of solutions for
performing advanced conversions. One option is to use the static methods of the
Convert class, which support many common data types such as strings, dates, and
numbers.
The second step (turning a number into a string) will always work. The first
step (turning a string into a number) won't work if the string contains letters or non-
numeric characters, in which case an error will occur. Chapter 8 describes how you
can use error handling to detect and neutralize this sort of problem.
The Convert class is a good all-purpose solution, but you'll also find other
static methods that can do the work, if you dig around in the .NET library.
The following code uses the static Int32.Parse( ) method to perform the same task:
int vCountString = "10" ;
// Convert the string "10" to the numeric value 10.
vCount = Int32.Parse(vCountString) ;
You'll also find that you can use objects to perform some conversions a little
more elegantly. The next section demonstrates this approach with the ToString( )
method.
4.6 OBJECT-BASED MANIPULATION
.NET is object-oriented to the core. In fact, even ordinary variables are really
full-fledged objects in disguise. This means that common data types have the built-in
smarts to handle basic operations (such as counting the number of characters in a
string). Even better, it means you can manipulate strings, dates, and numbers in the
same way in C# or VB language.
As an example, every type in the .NET class library includes a ToString( )
method. The default implantation of this method returns the class name. In simple
variables, a more useful result is returned: the string representation of the given
variable.
The following code snippet demonstrates how to use the ToString( ) method
with an integer:
string vMyString;
int vMyInteger = 100 ;
To understand this example, you need to remember that all int variables are
based on the Int32 type in the .NET Class library. The ToString( ) method is built in the
Int32 Class, so it's available when you use an integer in any language.
The next few sections explore the object-oriented underpinnings of the .NET data
types in more detail.
The first few statements use built-in methods, such as Trim( ), SubString( ),
ToUpper( ), and Replace( ). These methods generate new strings, and each of these
statements replaces the current vMyString with the new string object. The final
statement uses a built-in Length property; which returns an integer that represents the
number of characters in the string.
Note that the SubString( ) method requires a starting offset and a character
length. Strings use zero-based counting. This means that the first letter is in position0,
the second letter is in position 1, and so on. You'll find this standard of zero-based
counting throughout the .NET Framework for the sake of consistency. You've already
seen it at work with arrays.
You can even use the string methods in succession in a single (rather ugly) line:
string vMyString = "This is a test string ";
vMyString = vMystring.Trim( ).Substring(0, 4).ToUpper( ).Replace("IS", "AT") ;
Or, to make life more interesting, you can use the string methods on strings literals just
as easily as string variables:
vMyString = "hello".ToUpper(); // Sets vMystring to "HELLO"
Member Description
Length Returns the numbers of characters in the string (as an integer).
ToUpper( ) and Returns a copy of the string with all the characters changed to
ToLower( ) uppercase or lowercase characters.
Trim( ),
Removes spaces or some other characters from either (or both) ends
TrimEnd( ), and
of a string
TrimStart( )
Adds the specified character to the appropriate side of a string, as
PadLeft( ) and many times as necessary to make the total length of the string equal
PadRight( ) to number you specify. For example, "Hi".PadLeft(5, '@') returns the
string "@@@Hi"
Puts another string inside a string at a specified (zero-based) index
Insert( ) position. For example, Insert(1, "pre") adds the string pre after the
first character of the current string
Removes a specified number of string from a position. For example,
Remove( )
Remove (0, 1) removes the first character.
Replaces a specified substring with another string. For example,
Replace( )
Remove(0, 1) removes the first character.
Extracts a portion of a string of the specified length at the specified
Substring( ) location (as a new string). For example, Substring(0, 2) retrieves the
first two characters.
StartsWith( ) Determines whether a string starts or ends with a specified substring.
and EndsWith( ) For example, StartsWith("pre") will return either true of false,
ASP .NET / 68
depending on whether the strings begins with the letters pre in
lowercase
Finds the zero-based position of a substring in a string. This returns
IndexOf( ) and only the first match and can start at the end or beginning. You can
LastIndex( ) also use overloaded versions of these methods that accept a
parameter that specifies the position to start the search.
Divides a string into an array of substrings delimited by a specific
Split( ) substring. For example, with Split(".") you could chop a paragraph
into an array of sentence strings.
Fuses an array of strings into a new string. You can also specify a
Join( )
separator that will be inserted between each element.
The next example shows how you can use a TimeSpan object to find the total number
of minutes between two DateTime objects:
TimeSpan vDifference ;
vDifference = vMyDate2.Substract(vMyDate1) ;
double vNumberOfMinutes ;
vNumberOfMinutes = vDifference.TotalMinutes ;
The DateTime and TimeSpan Classes also support the + and - arithmetic operators,
which do the same work as build-in methods. That means you can rewrite the example
show earlier like this:
// Adding a TimeSpan to a DateTime creates a new DateTime.
Tables 4.6.3 Lists some of the more useful built-in features of the TimeSpan
object.
Member Description
Returns one component of the current TimeSpan. For
Days, Hours, Minutes,
example, the Hours property can return an integer from -
Seconds, MilliSeconds
23 to 23.
Returns the total value of the current TimeSpan as a
ToTalDays, TotalHours,
number of days, hours, minutes, and so on. The value is
TotalMinutes,
returned as a double, which may include a fractional
TotalSeconds,
value. For example, the TotalDays property might return a
TotalMilliseconds
number like 234.324.
Add( ) and Subtract( ) ; Combines TimeSpan objects together.
FromDays( ), FromHours(
Allows you to quickly create a new TimeSpan. For
), FromMinutes( ),
example, you can use TimeSpan.FromHours(24) to
FromSeconds( ),
create a TimeSpan object exactly 24 hours long.
FromMilliseconds( )
Returns a string representation of the current TimeSpan
object. You can also use an overloaded version of this
ToString( )
method that allows you to specify a parameter with a
format string
ASP .NET / 70
4.6.3 The Array Object
Arrays also behave like objects in the new world of .NET. For example, if you
want to find out the size of a one-dimensional array, you can use the Length property
or the GetLength( ) method, both of which return the total number of elements in an
array.
Member Description
Returns an integer that represents the total number of
Length elements in all dimensions of an array. For example, an
array 3 x 3 array has a length of 9.
Determines the dimensions of an array. As with just about
GetLowerBound( ) and
everything in .NET, you start counting at zero (which
GetUpperBound( )
represents the first dimension).
Empties part of all of an array's contents, depending on the
Clear( ) index values that you supply. The elements revert to their
initial empty values (such as 0 for numbers).
Searches a one-dimensional array for a specified value and
IndexOf( ) and
returns the index number. You cannot use this with
LastIndexOf( )
Multidimensional arrays.
Sorts a one -dimensional array made up of comparable data
Sort( )
such as strings or numbers.
Reverses a one-dimensional array so that its elements are
Reverse( )
backwards, from last to first.
In many ways, conditional logic (deciding which action to take based on user
input, external conditions, or other information), is the heart of programming. All
conditional logic starts with a condition: a simple expression that can be evaluated to
true or false. Your code can them make a decision to execute different logic depending
on the outcome of the condition. To build a condition, you can use any combination of
literal values or variables along with logical operators. Table lists the basic logical
operators.
Operator Description
== Equal to...
!= Not Equal to...
< Less then...
> Greater then...
<= Less than or equal to...
> Greater than or equal to...
Logical and (evaluates to true only if both expressions are true). If the first
&&
expression is false, the second expression is not evaluated.
Logical and (evaluates to true only if both expressions are true). If the first
||
expression is true, the second expression is not evaluated.
You can use all the comparison operators with any numeric types. With string
data types, you can use only the equality operators (== and !=). C# doesn't support
other types of string comparison operators. Instead, you need to use the
String.Compare( ) method. The String.Compare( ) method deems that a string is "less
then" another string if it occurs earlier in an alphabetic sort. Thus, apple is less then
attach. The return value from String.Compare is 0 if the strings match, 1 if the first
supplied string is greater than the second, and -1 if the first string is less than the
second. Here's an example:
int vResult ;
vResult = String.Compare("apple", "attach") ; // Result = -1
vResult = String.Compare("apple", "all") ; // Result = 1
vResult = String.Compare("apple", "apple") ; // Result = 0
For loop is a basic ingredient in many programs. It allows you to repeat a block
of code a set number of times, using a built-in counter. To create For loop, you need to
specify a starting value, an ending value, and the amount to increment with each pass.
Here's one example:
You'll notice that the for loop starts with brackets that indicate three important
pieces of information. The first portion, (int v = 0 ), creates the counter variable (v) and
sets its initial value (0). The third portion, (v + +), increments the counter variable (v).
In this example, the counter is incremented by 1 after each pass. That means v will be
equal to 0 for the first pass, equal to 1 for the second pass, equal to 2 for the third
pass, and so on. However, you could adjust this statement so that it decrements the
counter (or performs any other operation you want). The middle portion, (v < 10),
specifies the condition that must be met for the loop to continue. This condition is
tested at the start of every pass through the block. If v is greater than or equal to 10,
the condition will evaluate to false, and the loop will end.
If you run this code using a tool such as Visual Studio, it will write the following
numbers in the Debug window:
0123456789
It often makes sense to set the counter variable based on the number of times
you're processing. For example, you can use for loop to step trough the elements in an
array by checking the size of the array before you begin. Here's the code you would
use:
string[ ] vStringArray = {"one", "two", "three"};
Sample Output
one two three
BLOCK-LEVEL SCOPE
ASP .NET / 74
If you define a variable inside some sort of block structure (such as a loop or
conditional block), the variable is automatically released when your code exits the
block. That means you will no longer be able to access it.
int vTempVariableA ;
for (int v = 0 ; v < 10 ; v + +)
{
int vTempVariableB ;
vTempVariableA = 1 ;
vTempVariableB = 1 ;
}
This change won't affect many programs. It's really designed to catch a few
more accidental errors. If you do need to access a variable inside and outside of some
type of block structure, just define the variable before the block starts.
C# also provides a foreach loop that allows you to loop through the items in a
set of data. With a foreach loop, you don't need to create an explicit counter variable.
Instead, you create a variable that represents the type of data for which you're looking.
Your code will then loop until you've had a change to process each piece of data set.
The foreach loop is particularly useful for traversing the data in collections and arrays.
For example, the next code segment loops trough the items in an array using foreach.
This code has exactly the same effect as the previous example nut is a little simpler:
string[ ] vStringArray = {"one", "two", "three"} ;
In this case, the foreach loop examines each item in the array and tries to
convert it to a string. Thus, the foreach loop defines a string variable named element. If
you used a different data type, you'd receive an error.
The foreach loop has one key limitation: it's read only. For example, if you
wanted to loop through an array and change the values in that array at the same time,
foreach code wouldn't work. Here's an example of some flawed code:
int[ ] vIntArray = {1, 2, 3} ;
do
{ v += 1 ;
// This code executes ten times.
}
while ( v < 10) ;
Both of these examples are equivalent, unless the condition you're testing is
false to start. In that case, the while loop will skip the code entirely. They do...while
loop, on the other hand, will always execute the code at least once, because it doesn't
test the condition until the end.
4.9 FUNCTIONS & SUBROUTINES
Methods are the most basic building block you can use to organize your code.
Essentially, a method is a named grouping of one or more lines of code. Ideally, each
method will perform a distinct, logical task. By breaking your code down into methods,
you not only simplify your life, but you also make it easier to organize your code into
classes and step into the world of object-oriented programming.
The first decision you need to make when declaring a method is whether you
want to return any information. For example, a method named GetStartTime( ) might
return a DateTime object that represents the time an application was first started. A
method can return, at most, one piece of data.
When you declare a method in C#, the first part of the declaration specifies the
data type of the return value, and the second part indicates the method name. If your
method doesn't return any information, you should use the void keyword instead of a
data type at the beginning of the declaration.
Here are two examples, one method that doesn't return anything, and one that
does:
// This method doesn't return any information.
void MyMethodNoReturnData()
{
// Code goes here.
}
// This method returns an integer.
int MyMethodReturnsData( )
{
// As example, return the number 10.
return 10 ;
}
Notice that the method name is always followed by parentheses. This allows
the compiler to recognize that it's a method.
In this example, the methods don't specify their accessibility. This is just
common C# convention. You're free to add an accessibility keyword (such as public or
private) as show here:
The accessibility determines how different classes in your code can interact.
Private methods are hidden from view and are available only locally, whereas public
methods can be called by all the other classes in your application. To really
ASP .NET / 76
understand what this means, you'll need to read the next chapter, which discusses
accessibility in more detail.
Invoking your methods is straightforward; you simply type the name of the
method, followed by parentheses. If your method returns data, you have the option of
using the data it returns or just ignoring it:
// This call is allowed.
MyMethodNoReturnedData( ) ;
// This call is allowed.
MyMethodReturnsData( ) ;
// This call is allowed.
int vMyNumber ;
vMyNumber = MyMethodReturnsData( ) ;
// This call isn't allowed.
// MyMethodNoReturnedData( ) does not return any information.
vMyNumber = MyMethodNoReturnedData( ) ;
4.9.1 Parameters
Methods can also accept information through parameters. Parameters are
declared in a similar way to variables. By convention, parameter names always begin
with a lowercase latter in any language.
Here's how you might create a function that accepts two parameters and
returns their sum:
private int AddNumber(int pNumber1, int pNumber2)
{
return pNumber1 + pNumber2 ;
}
When calling a method, you specify any required parameters in parentheses
or use an empty set of parentheses if no parameters are required:
// Call a method with no parameters.
MyMethodNoReturnedData( ) ;
// Call a method that requires two integer parameters.
MyMethodNoReturnedData(10, 20) ;
// Call a method with two integer parameters and an integer value.
int vReturnValue = AddNumber(10, 20) ;
You cannot overload a method with versions that have the same signature,
that is, the same number of parameters and parameters data types, because the CLR
will not able to distinguish them from each other. When you call an overloaded
method, the version that matches the parameter list you supply is used. If no version
matches, an error occurs.
4.9.3 Delegates
Delegates allow you to create a variable that "points" to a method. You can
use this variable at any time to invoke the method. Delegates help you write flexible
code that can be reused in many situations.
The first step when using a delegate is to define its signature. The signature is
a combination of several pieces of information about a method: its return type, the
number of parameters it has, and the data type of each parameter.
A delegate variable can point only to a method that matches its specific
signature. In other words, the methods must have the same return type, the same
number of parameters, and the same data type for each parameter as the delegate.
For example, if you have a method that accepts a single string parameter and another
method that accepts two string parameters, you'll need to use a separate delegate
type for each method.
To consider how this works in practice, assume your program has the
following method:
Private string TransLateEnglishToFrench(string English)
{
// Code goes here.
}
This method accepts a single string argument and returns a string. With those
two details in mind, you can define a delegate that matches this signature. Here's how
you would do it:
Private delegate string StringFunction(string InputString) ;
Notice that the name you choose for the parameters and the name of the
delegate don’t matter. The only requirement is that the data types for the return value
and parameters match exactly.
Once you've defined a type of delegate, you can create and assign a delegate
variable like this:
StringFunction vFunctionReference ;
Once you have a delegate variable, the funs begin. Using your delegate
variable, you can point to any method that has the matching signature. In this example,
the StringFunction delegate type requires one string parameter and returns a string.
Thus, you can use the functionreference variable to store a reference to the
TranslateEnglishToFrench( ) method you saw earlier. Here's how to do it:
vFunctionReference = TransLateEnglishToFrench;
Now that you have a delegate variable that references a method, you can
invoke the method through the delegate. To do this, you just use the delegate name as
though it were the method name:
string frenchString ;
frenchString = functionreference("Hello") ;
In the previous code example, the method that the functionReference delegate
points to will be invoked with the parameter value "Hello", and return value will be
stored in the frechString variable.
The following code shows all these steps, creating a delegate variable,
assigning a method, and calling the method, from start to finish:
ASP .NET / 78
// Create a delegate variable.
StringFunction functionReference ;
// Store a reference to a matching method in the delegate.
functionReference = TransLateToEnglishToFrench ;
// Run the method that functionReference points to.
// In this case, it will be TransLateEnglishToFrench( ) .
string frenchString = functionReference("Hello") ;
The value of delegates is in the extra layer of flexibility they add. It's not
apparent in this example, because the same piece of code creates the delegate
variable, and another method would use it. The benefit in this scenario is that the
second method doesn't need to know where the delegate points. Instead, it's flexible
enough to use any method that has the right signature. In the current example,
imagine a translation library that could translate between English and a variety of
different languages, depending on whether the delegate it uses points to
TranslateEnglishToFrench( ), TranslateEnglishToSpanish( ),
TranslateEnglishToGerman( ), and so on.
4.10 SUMMARY
Variables can store numbers, text, dates, and times, and they can even point to
full-fledged objects.
Arrays allow you to store a series of values that have the same data type.
An enumeration is a group of related constants; each of which is given a
descriptive name. Each value in an enumeration corresponds to a preset integer.
Converting information from one data type to another is a fairly common
programming task.
Loops allow you to repeat a segment of code multiple times.
4.11 CHECK YOUR PROGRESS - ANSWERS
4.2
1. Byte, int, float double etc
2. String is a collection of character, you can say that character array. Escape
characters are defined with a special meaning and it start with ‘ \ ’ slash.
4.3 – 4.4
1. Collection of data having similar data types.
2. It is a group or collection of related constant.
4.5 – 4.6
1. Operation on any variable like addition, subtraction etc.
2. If we temporary change the data type of any variable then it is called type
conversion.
Declaring variables in ASP.NET / 79
3. C# and ASP are the object base language that means if we create a variable of
int then it means that variable is a member of class integer.
4.7 – 4.9
1. Delegate are the type safe function pointer, means they can invoke a function
indirectly by using referencing to the function, it is helpful reuse of our single
function in many classes / program.
2. Conditional structure comprises of if else and switch etc, they get run on the
basis of condition, whether is it true or false.
3. Method overloading designed to give a common name to method but, it have
restriction i.e. signature of function will be different using overloading we less the
work of programmer.
4.12 QUESTIONS FOR SELF - STUDY
1. What is Array? Explain with examples.
2. Explain Enumeration with program.
3. Explain Variable operation.
4. Explain Loop structure.
5. What is function? Explain it.
ASP .NET / 80
NOTES
ASP .NET / 82
Chapter 5
ASP.NET Applications
5.0 Objectives
5.1 Introduction
5.2 ASP.NET File Types
5.3 The Application/ Bin Directory
5.4 Code-Behinds in ASP .NET
5.5 The Global.asax
5.6 ASP .NET Configuration
5.7 Summary
5.8 Check your Progress - Answers
5.9 Questions for Self – Study
5.10 Suggested readings
5.0 OBJECTIVES
5.1 INTRODUCTION
Web site applications can contain a number of file types, some supported and
managed by ASP.NET, and others supported and managed by the IIS server. Most of
the ASP.NET file types can be automatically generated using the Add New Item menu
item in Visual Web Developer.
5.2 ASP.NET FILE TYPES
File types are mapped to applications using application mappings. For
example, if you use double-click a .txt file in Windows Explorer, Notepad will probably
open, because in Windows, .txt file types are mapped by default to Notepad.exe. In
Web applications, file types are mapped to application extensions in IIS.
Application root or a
.ascx A Web user control file that
subdirectory.
ASP.NET Applications / 83
defines a custom, reusable
control.
Application root or a
.cd A class diagram file.
subdirectory.
Source : http://msdn.microsoft.com/en-IN/library/2wawkw1c(v=vs.80).aspx
ASP.NET Applications / 85
Application root or a An Internet Database Connector file mapped to
.idc
subdirectory. httpodbc.dll.
.shtm,
Application root or a
.shtml, Mapped to ssinc.dll.
subdirectory.
.stm
IIS serves static files only if their file-name extensions are registered in the MIME types
list. This list is stored in the MimeMap IIS metabase property for an application. If a file
type is mapped to an application extension, it does not need to be included in the
MIME types list unless you want the file to be treated like a static file. Typically,
ASP.NET source code file types should not be in the MIME types list because that
might allow browsers to view the source code.
The following table lists only a few of the registered file types.
File
Location Description
type
ASP .NET / 86
automatically picked up by the runtime. When a change is detected, ASP.NET allows
currently executing requests to complete, and directs all new incoming requests to the
application that uses the new component or components.
5.4 CODE BEHINDS IN ASP.NET
Even though ASP.NET is the next version of ASP, it is more than just a next
version. ASP.NET is completely re-designed from the ground up and it provides a neat
object oriented programming model. An ASP.NET page is an object derived from the
.NET Page class. We all know that ASP.NET provides several new features and one
of the important features is the separation of code and content.
In today's ASP application, we have a mix of HTML and Scripts making the
code difficult to read, debug and maintain. ASP.NET relieves us from this problem by
promoting the separation of code and content. That is, the user interface and the user
interface programming logic need not necessarily be written in a single page. There
are two ways in which you can separate the code and content:
1) By using Code-behind files that are pre-compiled modules written in any of the
Microsoft .NET runtime compliant languages.
2.) By developing the frequently used page logic in to separate files called Pagelets
(also known as page controls) and by using them several times in your ASP.NET
pages.
As the title of the article indicates, I will explain the first mechanism that is
used to neatly encapsulate the UI functionality in to a separate pre-compiled module.
You will typically follow the steps below to develop an ASP.NET page that uses code-
behind pages:
1) Create the User Interface using the HTML and/or Web controls and store them
in an ASP.NET page with extension ".aspx".
2) Create the code-behind file using the .NET runtime classes that mimic the entire
ASP.NET page with the member variables that correspond to the HTML and/or
Web controls used in the ASP.NET page. The extension of code behind files will
vary depending on the language you use. Typical extensions will be .cs for C#,
.vb for VB7 and .js for JScript .NET
Now, we know that there are two separate files: one for the UI and the other
for the UI logic. But, how do we relate these two files so that the ASP.NET page
compiler will locate the code-behind file for the ASP.NET page. The glue between
these two files is provided through the Page Directives, which are used to specify
optional settings at the page level.
<HTML><BODY>
<form action="CodeBehind.aspx" method=post runat="server">
<h5>Sign-In Form</h5>
Login: <asp:TextBox id=txtLogin Width=200 Runat=server />
<asp:RequiredFieldValidator ControlToValidate="txtLogin"
Display="Static" Font-Name="verdana,arial,sans-serif"
Font-Size="9pt" ErrorMessage="You must enter a Login."
runat="server" ID="RFVLogin" />
ASP.NET Applications / 87
<P>
Password: <asp:TextBox id=txtPassword Width=200 Runat=server
TextMode="Password" />
<asp:RequiredFieldValidator ControlToValidate="txtPassword"
Display="Static" Font-Name="verdana,arial,sans-serif"
Font-Size="9pt" ErrorMessage="You must enter a password."
runat=server ID="RFVPassword"> </asp:RequiredFieldValidator>
<P>
<asp:Button id=btnSignIn Runat="server"
Text="Sign In" onClick="btnSignIn_Click" />
</FORM>
</body></html>
The first line of the ASP.NET page is the page directive that specifies the name of the
code behind file and the actual class name inside that file. In our example, the file
name is CodeBehind.cs and the class name is ASPPlus.CodeBehind.
The namespace that I used for this code behind page is ASPPlus. Namespaces
provide the naming scope for the classes and is very convenient way to represent
hierarchy of classes. The rest of the code consists of HTML tags and Web Control
declaration tags. The main thing to note down in this page is the ID properties of the
controls. I will explain the importance of these IDs when we discuss the code-behind
file.
Configuration information is stored in XML-based text files. You can use any
standard text editor or XML parser to create and edit ASP.NET configuration
files.
ASP .NET / 90
Check your progress 5.5-5.6
Answer the following questions in 1-2 sentences.
a) What is Global.asax?
………………………………………………………………………………………………
………………………………………………………………………………………………
b) Explain asp.net configuration.
………………………………………………………………………………………………
………………………………………………………………………………………………
5.7 SUMMARY
Web site applications can contain a number of file types, some supported and
managed by ASP.NET, and others supported and managed by the IIS server.
Most of the ASP.NET file types can be automatically generated using the Add
New Item menu item in Visual Web Developer.
In asp.net directory is always named /bin, and is located immediately under the
root directory for the application (a virtual directory defined by Internet
Information Services (IIS)).
The Global.asax file (also known as the ASP.NET application file) is an optional
file that is located in the application's root directory and is the ASP.NET
counterpart of the Global.asax of ASP.
5.8 CHECK YOUR PROGRESS – ANSWERS
5.2
1. .asax, .ascx
2. If the file name, extensions are register in the MIME File types.
5.3-5.4
1. To solve the traditional problem of com object, Microsoft create a well known \
bin directory to store application file at run time.
2. Meaning of it means that your page designee is distinct from your coding.
5.5 – 5.6
1. It is a file used to declare and handle application / session level events, object
for ASP .NET website running on IIS web server.
2. ASP .NET configuration means now your website will work in term of – Role,
Authentication, and Authorization. These all are customizable and we find them
in web.config file>system.web.
ASP .NET configuration gives us easy way to manage our web page and other
type of administration. We can do it by code also.
ASP.NET Applications / 91
NOTES
ASP .NET / 92
Chapter 6
Overview of ADO.NET
6.0 Objectives
6.1 Introduction
6.2 ADO.NET architecture
6.3 Accessing Data using data adapters
and datasets
6.4 Binding data to data bind controls
6.5 Displaying data in data grid
6.6 Summary
6.7 Check your Progress - Answers
6.8 Questions for Self – Study
6.9 Suggested Readings
6.0 OBJECTIVES
After studying in this chapter you will be able to –
explain the ADO.NE T architecture
discuss the use of data adapters and datasets
explain how to bind data to data bind control
explain how to display the data in data grid
6.1 INTRODUCTION
Most applications handle data, whether in the form of a database, text file,
spreadsheet, whatever the majority of modern day programs need access to an
information store.
Today, people are taking advantage of the latest data access technologies to
improve scalability and boost interoperability.
ADO.NET advantages:
Interoperability - All data in ADO.NET is transported in XML format, meaning it's
simply a structured text document that can be read by anyone on any platform.
Scalability - The client/server model is out. ADO.NET promotes the use of
disconnected datasets, with automatic connection pooling bundled as part of the
package.
Productivity - You can't just pick it up and run, but ADO.NET can certainly
improve your overall development time. For example, "Typed DataSets" help you
work quicker and produce more bug-free code.
Performance - Because ADO.NET is mainly about disconnected datasets, the
database server is no longer a bottleneck and hence applications should incur a
performance boost.
In ADO.NET, functionality is split into two key class groups — content
components and managed-provider components. The content components essentially
hold actual data and include the DataSet, DataTable, DataView, DataRow,
DataColumn and DataRelation classes.
We also have the managed-provider components, which actually talk to the
database to assist in data retrievals and updates. Such objects include the connection,
command and data reader.
Overview of ADO.NET / 93
Also, the managed-provider components are split into two key groups — one
designed for regular data sources, with another finely tuned specifically for SQL
Server.
Overview of ADO.NET / 95
which were designed for Client Server architectures but soon ADO took over RDO.
ADO was a good architecture but as the language changes so is the technology. With
ADO, all the data is contained in a recordset object which had problems when
implemented on the network and penetrating firewalls. ADO was a connected data
access, which means that when a connection to the database is established the
connection remains open until the application is closed. Leaving the connection open
for the lifetime of the application raises concerns about database security and network
traffic. Also, as databases are becoming increasingly important and as they are
serving more people, a connected data access model makes us think about its
productivity.
Why ADO.NET?
ADO.NET addresses the above mentioned problems by maintaining a
disconnected database access model which means, when an application interacts with
the database, the connection is opened to serve the request of the application and is
closed as soon as the request is completed. Likewise, if a database is updated, the
connection is opened long enough to complete the Update operation and is closed. By
keeping connections open for only a minimum period of time, ADO .NET conserves
system resources and provides maximum security for databases and also has less
impact on system performance. Also, ADO.NET when interacting with the database
uses XML and converts all the data into XML format for database related operations
making them more efficient.
The ADO.NET Data Architecture
ASP .NET / 96
Component classes that make up the Data Providers
The Connection Object
The Connection object creates the connection to the database. Microsoft
Visual Studio .NET provides two types of Connection classes: the SqlConnection
object, which is designed specifically to connect to Microsoft SQL Server 7.0 or later,
and the OleDbConnection object, which can provide connections to a wide range of
database types like Microsoft Access and Oracle. The Connection object contains all
of the information required to open a connection to the database.
The Command Object
The Command object is represented by two corresponding classes:
SqlCommand and OleDbCommand. Command objects are used to execute
commands to a database across a data connection. The Command objects can be
used to execute stored procedures on the database, SQL commands, or return
complete tables directly. Command objects provide three methods that are used to
execute commands on the database:
ExecuteNonQuery: Executes commands that have no return values such as
INSERT, UPDATE or DELETE
ExecuteScalar: Returns a single value from a database query
ExecuteReader: Returns a result set by way of a DataReader object
The DataReader Object
The DataReader object provides a forward-only, read-only, connected stream
recordset from a database. Unlike other components of the Data Provider, DataReader
objects cannot be directly instantiated. Rather, the DataReader is returned as the
result of the Command object's ExecuteReader method. The
SqlCommand.ExecuteReader method returns a SqlDataReader object, and the
OleDbCommand.ExecuteReader method returns an OleDbDataReader object. The
DataReader can provide rows of data directly to application logic when you do not
need to keep the data cached in memory. Because only one row is in memory at a
time, the DataReader provides the lowest overhead in terms of system performance
but requires the exclusive use of an open Connection object for the lifetime of the
DataReader.
The DataAdapter Object
The DataAdapter is the class at the core of ADO .NET's disconnected data
access. It is essentially the middleman facilitating all communication between the
database and a DataSet. The DataAdapter is used either to fill a DataTable or DataSet
with data from the database with its Fill method. After the memory-resident data has
been manipulated, the DataAdapter can commit the changes to the database by
calling the Update method. The DataAdapter provides four properties that represent
database commands:
Overview of ADO.NET / 97
Select Command
InsertCommand
DeleteCommand
UpdateCommand
When the Update method is called, changes in the DataSet are copied back to
the database and the appropriate InsertCommand, DeleteCommand, or
UpdateCommand is executed.
ASP .NET / 98
DataSet myDataSet = new DataSet ("Northwind");
Since the name of source database is Northwind, we have passed the same name in
the constructor.
3) The DataSet has been created but as we said before, this DataSet object
cannot directly interact with Database. We need to create a DataAdapter object which
would refer to the connection already created. The following line would declare a
DataAdapter object:
OleDbAdapter myDataAdapter = new OleDbAdapter (CommandObject, con);
The above line demonstrates one of many constructors of OleDbAdapter class. This
constructor takes a command object and a database connection object. The purpose
of command object is to retrieve suitable data needed for populating DataSet. As we
know SQL commands directly interacting with database tables, a similar command can
be assigned to CommandObject.
OleDbCommand CommandObject = new OleDbCommand ("Select * from
employee");
Whatever data you need for your Dataset should be retrieved by using suitable
command here. The second argument of OleDbAdapter constructor is connection
object con.
Alternative approach for initializing DataAdapter object:
Place a null instead of CommandObject while you initialize the OleDbAdapter object:
OleDbAdapter myDataAdapter = new OleDbAdapter (null, con);
Then you assign your query to the CommandObject and write:
myDataAdapter.SelectCommand = CommandObject;
4) Now, the bridge between the DataSet and Database has been created. You can
populate dataset by using the Fill command:
myDataAdapter.Fill (myDataSet, "EmployeeData");
The first argument to Fill function is the DataSet name which we want to
populate. The second argument is the name of DataTable. The results of SQL queries
go into DataTable. In this example, we have created a DataTable named
EmployeeData and the values in this table would be the results of SQL query: "Select *
from employee". In this way, we can use a dataset for storing data from many
database tables.
5) DataTables within a Dataset can be accessed using Tables. To access
EmployeeData, we need to write:
myDataSet.Tables["EmployeeData"].
To access rows in each Data Table, you need to write:
myDataSet.Tables["EmployeeData].Rows
Listing 1.1 would combine all the steps we have elaborated so far.
<table border=2>
<tr>
<td><b> Employee ID </b></td>
<td><b> Employee Name </b></td>
</tr>
foreach(DataRow dr in myDataSet.Tables["EmployeeData"].Rows)
{
Response.write ("<tr>");
for (int j = 0; j <2 ; j++)
{
Response.write ( "<td>" + dr[j].ToString() + "</td"> );
}
Response.write ("</tr>");
%>
</table>
</body>
</html>
The Code above would iterate in all rows of Employee table and display ID and name
of every employee.
Data Binding
Since Web Forms are stateless (all the information displayed on a Web Form
gets *lost* between postbacks), data binding in Web Forms in somehow different from
binding data in traditional Windows applications. We've all used to, for example,
connect a TDBGrid control to a TDataSource control to display (and edit) data from
some TDataSet control - in (Windows) Delphi database applications.
Although data binding, as a term, is often related to displaying data from a
database (using ADO.NET and/or BDP.NET), we'll first explore binding Web control
using data not coming from some database. This way we'll focus on the core issues
with ASP.NET data binding - working with databases will be covered in some future
chapters.
The Nature of ASP.NET data binding
In Web Form applications, most of the data displayed to the user (visitor of the
Web Site), is provided as read-only. For example, a search result page, in some online
store, will display information about the searched products with optional links to a page
with product details. The (search results) data can be retrieved from a database, with
no need to enable users to enter data to be saved back to the database.
With the above discussion in mind, here are some of the notes on Web Forms data
binding:
Data binding often requires using binding expressions directly in the aspx file.
We'll discuss binding expressions in the next chapter.
While data biding provides control over what data is used for binding, when it
is used and in what format, ASP.NET has the final word.
The simplest form of ASP.NET data binding is the automatic population of web
controls, such as the ListBox, RadioButtonList, CheckBoxList, etc. Each of these
controls inherits from a base ListControl class. The ListControl class defines a set of
properties (and methods) used when doing data binding.
What's more, any Web Control can be bound to some data source - since the
overall ancestor of every Web Control is the Control class, and the Control class has
the DataBind method. Data binding is in the heart of ASP.NET development.
Here's the set of common members of the ListControl class, related to data
binding:
The DataSource property defines the source of data for the control. While
DataSource is of the System.Object (TObject) type, an object must implement
either the IEnumerable or IList interface to be used as the source of data for
binding.
When a control is "armed" with the IEnumerable interface, it provides iteration
over a collection. Many of the classes in the .NET framework implement the
IEnumerable interface: Array, ArraList, HashTable, DataReader, DataView,
etc. Many of these classes implement the IList interface, too. The IList
interface allows for a collection to be accessed by an index.
With the above in mind, it is quite clear that data binding in ASP.NET is all but
NOT strictly related to retrieving the information from some kind of database. A
simple array of string values can be used as the DataSource.
When DataBind is executed for a control, it will call DataBind for all its child
controls. What this means is that if you have several controls on a Web Forms
page, you can call Page.DataBind for the Page! This will call DataBind for all
the controls that have their DataSource property set.
The following example, displays all the records from the Employees database
table in a DataGrid
Example : ExpertDataGrid.aspx
<asp:DataGrid
GridLines="None"
Runat="Server" />
The cell spacing and cell padding of the cells in a DataGrid can be controlled
by modifying the DataGrid control's CellSpacing and CellPadding properties like this:
<asp:DataGrid
CellSpacing="10"
CellPadding="10"
Runat="Server">
Finally, headers and footers can be displayed and hidden for the columns in a
DataGrid by enabling or disabling the ShowHeader and ShowFooter properties. By
default the ShowHeader property has the value True, and the ShowFooter property
has the value False. To prevent column headers from being displayed, a DataGrid
would be like this:
<asp:DataGrid
ShowHeader="False"
Runat="Server" />
Allows specifying which data source field to display and specifies the
Bound column format of that field, using a .NET formatting expression. For details
see Adding Bound Columns to a DataGrid Web Server Control.
Allows adding a button for each item in the grid and defining custom
functionality for that button. For example, you might create a button
Button column labeled "Add to Shopping Cart" that runs your custom logic when a
user clicks it. You can also add predefined buttons for Select, Edit,
Update, Cancel, and Delete functions.
Edit, Update, Allows creating in-place editing. For more details, see "Editing Items"
Cancel column below.
When the user clicks one of the buttons (labeled by default Edit, Delete,
Update, or Cancel, respectively), the corresponding event is raised.
The DataGrid control also supports the ItemCommand event that is raised
when a user clicks a button that is not one of the predefined buttons above. This event
can be used for custom functions by setting a button's CommandName property to a
value needed, and then testing for it in the ItemCommand event handler.
(For example, you could use this approach when selecting an item, as
documented in allowing Users to Select Items in a DataList Web Server Control.) By
default, a DataGrid simply displays all the columns from its data source. However, if
False value is assigned to the DataGrid control's AutoGenerateColumns property,
columns can be created individually to have more control over the formatting.
Adding a BoundColumn to a DataGrid
The default column used in a DataGrid is a BoundColumn. If only limited
columns are to be displayed and controlled from a data source, declaration of one or
The above example, displays only the FirstName and LastName columns from
the Employees table.
Note that the DataGrid control's AutoGenerateColumns property is set to the
value False so that, all the columns from the Employees table are displayed, and the
FirstName and LastName columns are displayed twice as shown below: -