5bca - ASP Dot Net
5bca - ASP Dot Net
What is .NET?
The .NET Framework introduces a completely new model for the programming and deployment of
applications. .NET is Microsoft's vision of "software as a service", a development environment in which
you can build, create, and deploy your applications and the next generation of components, the ability to
use the Web rather than your own computer for various services.
Microsoft introduced great technologies like COM, DCOM, COM+ etc. to enable reuse of Software.
Although these technologies are very powerful to reuse Software, they required a huge learning curve.
According to this aspect, Microsoft realized that its time to come up with a new Technology, a better one,
an easier one, a new Framework, within which each Programming Task is easy accomplished.
Microsoft changed all complex tasks with the new .NET Framework. That was a huge advantage for all
developers. Most of the Win32 API was now accessible through a very simple Object Model. Most of the
features and functions of C++ were added to Visual Basic. A new Programming Language C# was
introduced, which offered flexibility and productivity. ASP.NET also called ASP+ replaced ASP.
It provides the easiest and most scalable way to build, deploy and run web services. ASP.NET
server controls enable an HTML-like style of declarative programming that let you build great pages with
far less code than with classic ASP. VB, C++ and C# Code can be used in other languages f.e.
code written in VB can be easily used in C# or in VC++. Also an another benefit is that the you can
step between the languages in the debugger.
The Code written in .NET isn't compiled directly to the executable, instead .NET uses two steps
to compile the code. First, the code is compiled to an Intermediate Language called
Microsoft Intermediate Language (MSIL). Second, the compiled code will be recompiled with the
Common Language Runtime ( CLR ), which C# Codeconverts
(.vb) Filethe code to the machine code. The basic Idea of this
two stages was to make the code language independence.
The .NET Framework (pronounced dot net) is a software framework developed by Microsoft that runs
primarily on Microsoft Windows. It includes a large library and provides language interoperability (each
language can use code written in other languages) across several programming languages. Programs
written for the .NET Framework execute in a software environment (as contrasted to hardware
environment), known as the Common Language Runtime (CLR), an application virtual machine that
provides important services such as security, memory management, and exception handling. The class
library and the CLR together constitute the .NET Framework.
The .NET Framework's Base Class Library provides user interface, data access, database
connectivity, cryptography, web application development, numeric algorithms, and network
communications. Programmers produce software by combining their own source code with the .NET
Framework and other libraries. The .NET Framework is intended to be used by most new applications
created for the Windows platform. Microsoft also produces a popular integrated development
environment largely for .NET software called Visual Studio.
Microsoft started the development on the .NET Framework in the late 1990s originally under the name of
Next Generation Web Services (NGWS). By late 2000 the first beta versions of .NET 1.0 were released.
Windows XP (including service packs) does not come with any version of the .NET Framework installed.
Version 3.0 of the .NET Framework is included with Windows Server 2008 and Windows Vista. Version
3.5 is included with Windows 7, and can also be installed on Windows XP and the Windows Server
2003 family of operating systems
On 12 April 2010, .NET Framework 4 was released alongside Visual Studio 2010.
The .NET Framework family also includes two versions for mobile or embedded device use. A reduced
version of the framework, the .NET Compact Framework, is available on Windows CE platforms,
including Windows Mobile devices such as smart phones. Additionally, the .NET Micro Framework is
targeted at severely resource-constrained devices.
Version
Version Release Date Visual Studio Default in Windows
Number
Interoperability
Because computer systems commonly require interaction between newer and older applications, the .NET
Framework provides means to access functionality implemented in newer and older programs that execute outside
the .NET environment. Access to COM components is provided in the System.Runtime.InteropServices and
System.EnterpriseServices namespaces of the framework; access to other functionality is achieved using
the feature.
Language independence
The .NET Framework introduces a Common Type System, or CTS. The CTS specification defines all
possible data types and programming constructs supported by the CLR and how they may or may not
interact with each other conforming to the Common Language Infrastructure (CLI) specification.
Because of this feature, the .NET Framework supports the exchange of types and object instances
between libraries and applications written using any conforming .NET language.
Simplified deployment
The .NET Framework includes design features and tools which help manage the installation of computer
software to ensure it does not interfere with previously installed software, and it conforms to security
requirements.
Security
The design addresses some of the vulnerabilities, such as buffer overflows, which have been exploited by
malicious software. Additionally, .NET provides a common security model for all applications.
Portability
While Microsoft has never implemented the full framework on any system except Microsoft Windows, it
has engineered the framework to be platform-agnostic, and cross-platform implementations are available
for other operating systems (see Silver light and the Alternative implementations section below).
Microsoft submitted the specifications for the Common Language Infrastructure (which includes the core
class libraries, Common Type System, and the Common Intermediate Language), the C# language, and
the C++/CLI language to both ECMA and the ISO, making them available as official standards. This
makes it possible for third parties to create compatible implementations of the framework and its
languages on other platforms.
The .NET Framework has two components: the .NET Framework class library and the
CommonLanguageRuntime.
The .NET Framework class library facilitates types (CTS) that are common to all .NET languages.
The common language runtime consists of (class loader) that load the IL code of a program into the
runtime, which compiles the IL code into native code, and executes and manage the code to enforce
security and type safety, and provide thread support.
.NET Framework Architecture has languages at the top such as VB .NET C#, VJ#, VC++ .NET;
developers can develop (using any of above languages) applications such as Windows Forms, Web Form,
Windows Services and XML Web Services. Bottom two layers consist of .NET Framework class library
and Common Language Runtime.
The CLR is Microsoft's implementation of the Common Language Infrastructure (CLI) standard.
Features of the Common Language Runtime
Manages memory,
Allocation of Memory
De-Allocation of Memory (garbage collation)
Code Security based on Trust (granted permission to execute code. Code level, Folder level, and Machine
level). These features are intrinsic to the managed code that runs on the common language runtime
The specification for the CTS is contained in Ecma standard 335, "Common Language Infrastructure
(CLI) Partitions I to VI." The CLI and the CTS were created by Microsoft, and the Microsoft .NET
framework is an implementation of the standard.
To establish a framework that helps enable cross-language integration, type safety, and high
performance code execution .
To provide an object-oriented model that supports the complete implementation of many
programming languages.
To define rules that languages must follow, which helps ensure that objects written in different
languages can interact with each other.
The CTS also defines the rules that ensures that the data types of objects written in various languages
are able to interact with each other.
The CTS also specifies the rules for type visibility and access to the members of a type, i.e. the CTS
establishes the rules by which assemblies form scope for a type, and the Common Language Runtime
enforces the visibility rules.
The CTS defines the rules governing type inheritance, virtual methods and object lifetime.
Languages supported by .NET can implement all or some common data types....
When rounding fractional values, the halfway-to-even ("banker's") method is used by default, throughout
the Framework. Since version 2, "Symmetric Arithmetic Rounding" (round halves away from zero) is also
available by programmer's option.
Type categories
When compiling to managed code, the compiler translates your source code into Microsoft intermediate
language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to
native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects,
as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception
handling, and other operations. Before code can be run, MSIL must be converted to CPU-specific code,
usually by a just-in-time (JIT) compiler. Because the common language runtime supplies one or more JIT
compilers for each computer architecture it supports, the same set of MSIL can be JIT-compiled and run
on any supported architecture.
When a compiler produces MSIL, it also produces metadata. Metadata describes the types in your code,
including the definition of each type, the signatures of each type's members, the members that your code
references, and other data that the runtime uses at execution time. The MSIL and metadata are contained
in a portable executable (PE) file that is based on and extends the published Microsoft PE and common
object file format (COFF) used historically for executable content. This file format, which accommodates
MSIL or native code as well as metadata, enables the operating system to recognize common language
runtime images. The presence of metadata in the file along with the MSIL enables your code to describe
itself, which means that there is no need for type libraries or Interface Definition Language (IDL). The
runtime locates and extracts the metadata from the file as needed during execution.
JIT compiler compiles is the integral part of CLR. the MSIL code to Native code and executes the batch
of code Just in time which will be cached and next time when the code gets executed from cache in stud
of compiling again.
CLR class loader lodes MSIL code and metadata are loaded into memory; the code manager calls the
entry point method which is Win Main or DLL Main method. The JIT compiler compiles the method to
before its execution of the entry point method. The code manager places the objects in memory and
controls the execution of the code. The garbage collector performs periodic checks on the managed heap
to identify the objects which is not in use for the application.
At the time of program execution the type checker ensures that all objects and values, and the references
of objects and values has its valid type. The type checker also makes sure that only valid operations are
performed on the code other wise the exception will be thrown. The code is controlled by CLR at run
time. CLR enforces security in following manner.
Every Assembly you create contains one or more program files and a Manifest. There are two types
program files : Process Assemblies (EXE) and Library Assemblies (DLL). Each Assembly can have only
one entry point (that is, DllMain, Win Main, or Main). We can create two types of Assembly, private
Assembly and shared Assembly.
Shared: A shared assembly can be used by all applications located on the same server.(also
called strong named assemblies) are copied to a single location (usually the Global assembly
cache) GAC.
Before we can use a class contained in an assembly in our application, we must add a
reference to the assembly.
mscorlib.dll
System.dll
System.Configuration.dll
System.Web.dll
System.Data.dll
System.Web.Services.dll
System.Xml.dll
An Assembly Manifest is a file that containing Metadata about .NET Assemblies. Assembly Manifest
contains a collection of data that describes how the elements in the assembly relate to each other. It
describes the relationship and dependencies of the components in the Assembly, versioning information,
scope information and the security permissions required by the Assembly.
The Assembly Manifest can be stored in Portable Executable (PE) file with Microsoft Intermediate
Language (MSIL) code. You can add or change some information in the Assembly Manifest by using
assembly attributes in your code. The Assembly Manifest can be stored in either a PE file (an .exe or .dll)
with Microsoft Intermediate Language (MSIL) code or in a standalone PE file that contains only assembly
manifest information. Using ILDasm, you can view the manifest information for any managed DLL.
.Net Namespaces
Namespaces are the way to organize .NET Framework Class Library into a logical grouping according
to their functionality, usability as well as category they should belong to, or we can say Namespaces
are logical grouping of types for the purpose of identification.
The .NET Framework Class Library (FCL ) is a large collection of thousands of Classes. These Classes
are organized in a hierarchical tree. The System Namespaces is the root for types in the .NET
Framework. We can uniquely identify any Class in the .NET Framework Class Library (FCL ) by using
the full Namespaces of the class .In .Net languages every program is created with a default
Namespaces . Programmers can also create their own Namespaces in .Net language
Namespaces in the
BCL[12]
Class library
The .NET Framework includes a set of standard class libraries. The class library is
System
organized in a hierarchy of namespaces. Most of the built-in APIs are part of
eitherSystem.* or Microsoft.* namespaces. These class libraries implement a large
System.
number of common functions, such as file reading and writing, graphic rendering, database
interaction, and XML document manipulation, among others. The .NET class libraries are
available to all CLI compliant languages. The .NET Framework class library is divided System. Diagnostics
into two parts: the Base Class Library and the Framework Class Library
System. Globalization
1-Base Class Library
The Base Class Library (BC) includes a small subset of the entire class library and is the
System
core set of classes that serve as the basic API of the Common Language Runtime. The
classes in mscorlib.dll and some of the classes
in System.dll and System.core.dll are considered to be a part of the BCL. The BCL System. Resources
classes are available in both .NET Framework as well as its alternative implementations
including .NET Compact Framework, Microsoft Silver light and Mono. System. Text
The Framework Class Library (FCL) is a superset of the BCL classes and refers to the
entire class library that ships with .NET Framework. It includes an expanded set of libraries,
including Windows Forms, ADO.NET, ASP.NET, Language Integrated Query, Windows Presentation
Foundation, Foundation among others. The FCL is much larger in scope than standard libraries for
languages like C++, and comparable in scope to the standard libraries of Java.
The .Net Framework class library (FCL) provides the core functionality of .Net Framework architecture .
The .Net Framework Class Library (FCL) includes a huge collection of reusable classes , interfaces, and
value types that expedite and optimize the development process and provide access to system
functionality.
The .Net Framework class library (FCL) organized in a hierarchical tree structure and it is divided into
Namespaces. Namespaces is a logical grouping of types for the purpose of identification. Framework class
library (FCL) provides the consistent base types that are used across all .NET enabled languages. The
Classes are accessed by namespaces, which reside within Assemblies. The System Namespace is the root
for types in the .NET Framework. The .Net Framework class library (FCL) classes are managed classes
that provide access to System Services . The .Net Framework class library (FCL) classes are object
oriented and easy to use in program developments. Moreover, third-party components can integrate with
the classes in the .NET Framework.
There have been numerous versions of Visual Studio since its inception. Visual Studio 6 coincided with
the release of Visual Basic 6; Visual Studio.NET 2002 was released along with the 1.0 version of the
.NET framework, and was again revised with the 1.1 version of the .NET framework, at which point it
was dubbed Visual Studio .NET 2003. The next version of Visual Studio, named Visual Studio 2005, is
slated for release in November of this year and will coincide with the release of the 2.0 version of the
.NET framework.
What can you really do with Visual Studio? Following are some of the various applications that can be
built using Visual Studio.
Console applications: These applications run from the command line and do not include a
graphical interface, but are great for small tools or anything that will be run by another application.
Windows forms applications: These are Windows desktop applications written using the .NET
framework; since they are .NET applications, they require that the .NET framework be on any
computer that will run the application.
Windows services: Services are applications that run in the background while your computer is
running. These are usually applications that will have to perform scheduled tasks or handle
continuous network requests.
ASP.NET applications: ASP.NET is a powerful technology that is used to create dynamic web
applications, often driven by a database. Many popular websites are written using ASP.NET,
including those of e-commerce giants like Dell.
ASP.NET web services: ASP.NET provides a complete web services model that allows you to
quickly and easily create web services.
Windows Mobile applications: Windows Mobile applications can run on devices that include the
Compact framework; these include Pocket PC devices, as well as cell phones running the
Microsoft Smartphone platform.
MFC/ATL/Win32 applications: You can also still create traditional MFC, ATL, or Win32
applications using C++. These applications do not need the .NET runtime to run, but also don't
include many of the benefits of working with the .NET framework.
Visual Studio add-ins: That's right, you can use Visual Studio to write new functionality to be
added into Visual Studio.
And more: Visual Studio also includes projects to deploy your application, work with databases,
create reports, and more.
Visual Studio provides an extensible model for adding new projects to Visual Studio; many other
Microsoft applications now integrate directly into the IDE. Some of the most common include SQL Server
Reporting Services and Visual Studio Tools for Office.
Features
All of the above applications could be written using another IDE or some combination of freely available
SDKs and your favorite text editor, so why would you pay for Visual Studio? Visual Studio is dedicated to
making your development life easier through time-saving and convenient features; here are some of the
most compelling of those features.
IntelliSense: IntelliSense is the trademark feature of Visual Studio. IntelliSense simply helps you
while programming by showing you the available classes and the methods and properties available
on those classes. Can't remember what the name of that class, method, or property is? No worries,
IntelliSense will help out.
Designers: Visual Studio includes visual WSYIWYG designers for Windows applications,
ASP.NET applications, and Windows Mobile applications. These designers make it much easier to
get your application looking just right.
Debugging: One of the most important features of Visual Studio is the ability to step through your
application line by line as it is executing. Not sure why you are getting an error? Simply walk
through and see exactly what is going wrong.
Organization: Visual Studio is built for developing applications, so it provides intuitive methods
for organizing your various code files into projects and your various projects into solutions.
The IDE, shown in below Figure, has become more complex than in previous versions of Visual Basic,
and being able to use it, or at least knowing what the various parts are called, is a skill we'll need in the
coming chapters. Part of the reasons it's become more complex is that the same IDE is now shared by all
Visual Studio languages, such as VB and C# (something Microsoft has promised for many years, but only
implemented now). We've already seen the IDE at work, of course, but now it's time to take a more
systematic look.
There are so many independent windows in the IDE that it's easy to misplace or rearrange them
inadvertently. The IDE windows are docking windows, which means you can use the mouse to move
windows around as you like; when the windows are near an edge, they'll "dock"-adhere-to that edge, so
you can reconfigure the IDE windows as you like. If you move IDE windows inadvertently, don't panic;
just use the mouse to move them back.
What is Asp.net
ASP.NET is a part of the Microsoft .NET Framework, so all .NET Framework features are available to
ASP.NET applications.
ASP.NET web pages are simply pure text, like HTML files. ASP.NET web pages are the main building
block for application development. You can develop your applications in any language compatible with
the common language runtime, including Microsoft Visual Basic and C#. These languages enable you to
develop ASP.NET applications that benefit from the common language runtime, type safety, inheritance,
and so on. ASP.NET incorporates all the important standards of our time, such as XML and SOAP, plus
with ADO.NET and the foundation class libraries.
ASP.NET is built on the Common Language Runtime (CLR), allowing programmers to write ASP.NET
code using any supported .NET languages like VB.NET and C#. Unlike the ASP runtime, ASP.NET uses
the Common Language Runtime (CLR) provided by the .NET Framework. The Microsoft .NET Platform
provides all of the tools and technologies that are needed to build distributed Web applications. ASP.NET
is integrated with Visual Studio .NET, which provides a GUI designer, a rich toolbox, and a fully
integrated debugger. In ASP.NET, you can write the HTML code in the .aspx file and the code for
programming logic in the code-behind file (.aspx.vb or .aspx.cs ). Also ASP.NET introduces two sets of
controls, the HTML controls and the Web controls, which are collectively known as "server controls."
Visual Studio .NET is an excellent development tool for constructing ASP.NET web applications. It
provides all of the necessary tools and support for creating ASP.NET web applications. ASP.NET web
applications are hosted by Internet Information Server (IIS), which accepts requests from clients and
optionally authenticates them before passing the requests on to the Web application. From the following
chapters you can learn more about ASP.NET technology in detail.
ASP.NET is integrated with Visual Studio .NET, which provides a GUI designer, a rich
toolbox, and a fully integrated debugger. In ASP.NET, you can write the HTML code in the
.aspx file and the code for programming logic in the code behind file (.aspx.vb or .aspx.cs )
depends on which .Net language you are selected. Web Forms allow you to apply Rapid
Application Development techniques to building web applications. Simply drag and drop
controls onto your form, double-click on a control, and write the code respond to the
associated event. You can program ASP.NET in any language that supports the .NET CLS.
Select Visual Studio from Start->All Programs . Select New Web Site from File menu of
Visual Studio.
After click the OK button you will get a blank form. You can select controls from the Toolbox
which is located left side to the blank form.
Click on the Label control and drag it to the design surface. It will automatically go to the
upper-left corner of the design surface and contain the word Label.
Select the label control and change the Text property of label control to "This is my first
asp.net program". The property window is placed right side down of your Visual Studio
Environment.
After the coding, press F5 to run the web application. When either the C# or VB.NET version
is run, it will look like the browser shown.
Understanding ASP.NET Controls
ASP.NET controls are the heart of ASP.NET Framework. An ASP.NET control is a .NET class that executes on the server
and renders certain content to the browser. For example, in the first ASP.NET page created at the beginning of this
chapter, a Label control was used to display the current date and time. The ASP.NET framework includes more than 90
controls, which enable you to do everything from displaying a list of database records to displaying a randomly rotating
banner advertisement.
This section provides an overview of the controls included in ASP.NET Framework. You also learn how to handle events
raised by controls and how to take advantage of View State.
The ASP.NET Framework contains more than 90 controls. These controls can be divided into seven groups:
Standard Controls— Enable you to render standard form elements such as buttons, input fields, and labels.
We examine these controls in detail in Chapter 2, “Using the Standard Controls.”
Validation Controls— Enable you to validate form data before you submit the data to the server. For
example, you can use a RequiredFieldValidator control to check whether a user entered a value for a
required input field. These controls are discussed in Chapter 3, “Using the Validation Controls.”
Rich Controls— Enable you to render things such as calendars, file upload buttons, rotating banner
advertisements, and multistep wizards. Chapter 4, “Using the Rich Controls,” discusses these controls.
Data Controls— Enable you to work with data such as database data. For example, you can use these
controls to submit new records to a database table or display a list of database records. Navigation
Controls— Enable you to display standard navigation elements such as menus, tree views, and bread crumb
trails.
Login Controls— Enables you to display login, change password, and registration forms.
HTML Controls— Enable you to convert any HTML tag into a server-side control.
What is Web Forms
ASP.NET Web Forms is a part of the ASP.NET web application framework. It is one of the three different
programming models you can use to create ASP.NET web applications, the others being ASP.NET MVC
and ASP.NET Web Pages.
Web Forms are pages that your users request through their browser and that form the user interface (UI)
that give your web applications their look and feel. These pages are written using a combination of
HTML, server controls, and server code. When users request a page, it is compiled and executed on the
server, and then it generates the HTML markup that the browser can render.
Using Visual Studio, you can create ASP.NET Web Forms using a powerful IDE. For example, this lets
you drag and drop server controls to lay out your Web Forms page. You can then easily set properties,
methods, and events for controls or for the page in order to define the page's behavior, look and feel, and
so on. To write server code to handle the logic for the page, you can use a .NET language like Visual
Basic or C#.
ASP.NET Web Forms offer:
Separation of HTML and other UI code from application logic.
A rich suite of server controls for common tasks, including data access.
Powerful data binding, with great tool support.
Support for using Ajax, even if you don't know JavaScript.
Web servers
Web servers are computers that deliver (serves up) Web pages. Every Web server has an IP address and
possibly a domain name. For example, if you enter the URL http://www.pcwebopedia.com/index.html in
your browser, this sends a request to the Web server whose domain name ispcwebopedia.com. The server
then fetches the page named index.html and sends it to your browser.
Any computer can be turned into a Web server by installing server softwareand connecting the machine to
the Internet. There are many Web server software applications, including public domain software from
NCSA and Apache, and commercial packages from Microsoft, Netscape and others.
Web Forms
Web Forms are the heart and soul of ASP.NET. Web Forms are the User Interface (UI) elements that give
your Web applications their look and feel. Web Forms are similar to Windows Forms in that they provide
properties, methods, and events for the controls that are placed onto them. However, these UI elements
render themselves in the appropriate markup language required by the request, e.g. HTML. If you use
Microsoft Visual Studio® .NET, you will also get the familiar drag-and-drop interface used to create your
UI for your Web application.
Web Forms are made up of two components: the visual portion (the ASPX file), and the code behind the
form, which resides in a separate class file.
Figure 1. Web Forms are a part of ASP.NET
Web Forms and ASP.NET were created to overcome some of the limitations of ASP. These new strengths
include:
On the surface, Web Forms seem just like a workspace where you draw controls. In reality, they can do a whole lot
more. But normally you will just place any of the various controls onto the Web Form to create your UI. The
controls you use determine which properties, events, and methods you will get for each control. There are two types
of controls that you can use to create your user interface: HTML controls and Web Form controls.
Let's look at the different types of controls that you can use in Web Forms and the ASP.NET Framework.
HTML Controls
HTML controls mimic the actual HTML elements that you would use if you were using Front Page or any other
HTML editor to draw your UI. You can use standard HTML elements in Web Forms, too. For example, if you
wanted to create a text box, you would write:
If you are using Visual Studio .NET, you choose a TextField control from the HTML Toolbox tab and draw the
control where you want it on the HTML page.
Any HTML element can be marked to also run as an HTML control when the Web Form is processed on the server
by adding "runat=server" to the tag:
<input type="text" id=txtFirstName size=25 runat=server>
If you are using Visual Studio .NET, you can right-click the HTML element in Design View and select Run as
Server Control from the context menu.
HTML controls allow you to handle server events associated with the tag (a button click, for example), and
manipulate the HTML tag programmatically in the Web Form code. When the control is rendered to the browser,
the tag is rendered just as it is saved in the Web Form, minus the "runat=server". This gives you precise control over
the HTML that is sent to the browser.
Reset Button Resets all other HTML form <input type=reset runat=server>
elements on a form to a default
value
Text Field Gives the user an input area on <input type=text runat=server>
an HTML form
CheckBox Gives the user a check box that <input type=checkbox runat=server>
they can select or clear
All of these controls write standard HTML into the Web Form. You may optionally assign an ID attribute to each
control, allowing you to write client-side JavaScript code for any of the events that are common for this particular
type of control. Below is a partial list of some of the more common client-side events.
Control Description
Web Form controls are created and run on the Server just like the HTML controls. After performing whatever
operation they are designed to do, they render the appropriate HTML and send that HTML into the output stream.
For example, a DropDownList control will allow you to bind to a data source, yet the output that is rendered is
standard<SELECT> and <OPTION> tags when sent to a browser. However, the same DropDownList control
might render WML if the target is a portable phone. That is why these controls do not necessarily map to any one
markup language, but have the flexibility to target the appropriate markup language.
All Web Form controls inherit from a common base class, namely the System.Web.UI.WebControls class. This
base class implements a set of common properties that all of these controls will have. Some of these common
properties are:
BackColor
Enabled
Font
ForeColor
Modifiers
TabIndex
Visible
Width
There are a few different categories of controls that are supplied by the Microsoft .NET Framework. Some controls
have an almost one-to-one correspondence with their HTML counterparts. Some controls provide additional
information when posted back to the server, and some controls allow you to display data in tabular or list-type
format. Table 2 shows a list of Web Form server-side controls and the server-side events that you can respond to
with each control.
Asp.NET Controls
The Label control used to display text in a set location on a Web page, also it can customize the displayed
text through the Text property.
C#
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Button control
Button control displays a push button control on the Web page. By default, a Button control is
a Submit button. You can provide an event handler for the Click event to programmatically
control the actions performed when the Submit button is clicked.
C#
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Button Clicked !!";
The following ASP.NET program display a text in the label when the Button click event is
performed.
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
The TextBox server control is an input control which can be used to accept user input.
By default Texboxes comes with a single line of text , you can also use the TextBox control to
display a multiline text box or a text box that masks user input by changing the value of the
TextMode property to TextBoxMode.MultiLine
TextBox1.TextMode = System.Web.UI.WebControls.TextBoxMode.MultiLine;
If you want to limit the user input to a specified number of characters, set the MaxLength
property.
TextBox1.MaxLength = 5;
The following ASP.NET program retrieve user input from a TextBox control and display it to
a Label control.
Defaul.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
The drop-down list can contain any number of items and allows the user to select a single item
from the drop-down list.
The following ASP.NET program add seven days in a week to the DropDownList in the form
load event and display the selected item in the button click event.
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
CheckBoxes:-
CheckBoxes allow the user to make multiple selections from a number of options and
CheckBoxes comes with a caption, which you can set in the Text property.
CheckBox1.Text = "CheckBox";
We can decide whether the checkbox is clicked or not by its checked property.
if (CheckBox1.Checked == true)
{
Label2.Text = "Checkbox Clicked";
}
The following ASP.Net program detect whether the Checkbox is clicked or not and display the
message on Label control.
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBox ID="CheckBox1" runat="server" Text="CheckBox"
AutoPostBack="True"
oncheckedchanged="CheckBox1_CheckedChanged" />
<br />
<asp:Label ID="Label2" runat="server" Text="Label2"></asp:Label>
</div>
</form>
</body>
</html>
Radio button
Radio button allows the user to choose only one of a predefined set of options. When a user
clicks on a radio button, it becomes checked, and all other radio buttons with same group
become unchecked. The buttons are grouped logically if they all share the same GroupName
property.
C#
RadioButton1.Checked = true;
Use a radio button when you want the user to choose only one option. When you want the user
to choose all appropriate options, use a check box.
The following ASP.NET program gives three option button to select. When the user select any
option button , the label control displays the which option button is selected.
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" GroupName="language" runat="server"
Text="ASP.NET" /><br />
<asp:RadioButton ID="RadioButton2" GroupName="language" runat="server"
Text="VB.NET" /><br />
<asp:RadioButton ID="RadioButton3" GroupName="language" runat="server"
Text="C#" /><br />
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" /><br />
<asp:Label ID="Label1" runat="server" Text="Label1"></asp:Label>
</div>
</form>
</body>
</html>
You can use the Add or Insert method to add items to a list box. Use the Rows property to
specify the height of the control.
C#
ListBox1.Items.Add("Sunday");
The Add method adds new items at the end of an unsorted list box. The Insert method allows
you to specify where to insert the item you are adding.
Listbox control that allows single or multiple item selection.To enable multiple item selection,
set the SelectionMode property to ListSelectionMode.Multiple.
C#
ListBox1.SelectionMode = System.Web.UI.WebControls.ListSelectionMode.Multiple;
The following ASP.NET program add seven days in a week to the ListBox in the load event
and display the selected item in the label.
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
UNIT-2 http://asp.net-informations.com/
What is Form Validation
Validation is basically the act of comparing something to a given set of rules and determining if it satisfies
the criteria those rules represent. In this case, the something that we are tring to validate is the input that a
visitor to our site has entered into a web form.
There are a number of reasons why we'd want to do this. Some basic examples are:
No data or incomplete data was entered
The value of the data entered is not within the appropriate range
The format of the entered data is not as expected
There are any number of explanations why one of the above might occur. Perhaps a spider or web-bot has
come across our form and tried to submit it without entering any data, maybe the user entered a item that
doesn't really exist (ie. Feb. 29, 2002), or maybe they simply made a typo (ie. forgot to enter one of the
digits in their phone number). Whatever the reason, the best course of action is usually easiest to
determine if you know there is a problem while the user is still available to fix it.
Types of Validation
Example:-
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Name</td><td><asp:TextBox ID="txtName" runat ="server" ></asp:TextBox></td>
</tr>
<tr>
<td>Email</td><td><asp:TextBox ID="txtEmail" runat ="server" ></asp:TextBox></td>
</tr>
<tr>
<td>WebUrl</td><td><asp:TextBox ID="txtWebURL" runat ="server" ></asp:TextBox></td>
</tr>
<tr>
<td>Zip</td><td><asp:TextBox ID="txtZIP" runat ="server" ></asp:TextBox>
<br />
<br />
<br />
<asp:Button ID="btnSubmit" OnClientClick=" return validate()" runat="server"
Text="Submit" onclick="btnSubmit_Click" /></td>
</tr>
</table>
</div>
</form>
</body>
Server side validation is done by writing our custom logic for validating all the input. ASP.NET also
provides us some controls which will facilitate the server side validation and provides a framework for the
developers to do the same.
NOTE: Web developer may choose to go with any one type of validation but usually it is a good idea to
have client side validation and same validation on server side too. It sure takes some resources of server to
validate the already validated data (on client side) but it ensures security and that is always good.
ASP.NET provides five validator controls, which are described in Table 10-1. Four are targeted at specific
types of validation, while the fifth allows you to apply custom validation routines.
You‘ll also see a Validation Summary control in the Toolbox, which gives you another option for showing
a list of validation error messages in one place. You‘ll learn about the Validation Summary later in this
chapter (see the ―Other Display Options‖ section).
The Base Validator class
The validation controls are found in the System.Web.UI.WebControls namespace and inherit
from the BaseValidator class. This class defines the basic functionality for a validation control.
Table 10-2 describes its key properties.
Validator-Specific Properties
The RequiredFieldValidator Control
The simplest available control is RequiredFieldValidator, whose only work is to ensure that the associated
control is not empty. For example, the control will fail validation if a linked text box doesn‘t contain any
content (or just contains spaces). Alternatively, instead of checking for blank values you can specify a
default value using the InitialValue property. In this case, validation fails if the content in the control
matches this InitialValue (indicating that the user hasn‘t changed it in any way).
Here is an example of a typical RequiredFieldValidator:
The RangeValidator control verifies that an input value falls within a predetermined range. It has
three specific properties: MinimumValue, MaximumValue, and Type. The MinimumValue and
MaximumValue properties define an inclusive range of valid values. The Type property defines the type
of the data that will be typed into the input control and validated. The supported values are Currency,
Date, Double, Integer, and String.
The following example checks that the date entered falls within the range of August 5 to August 20
(encoded in the form mm/dd/yyyy, so if your web server uses different regional settings, you‘ll have to
change the date format):
The next example compares the input values in two password text boxes to ensure that their value is
the same:
The expression .*@.{2,}\..{2,} specifies that the string that it‘s validating must begin with a
number of characters (.*) and must contain an @ character, at least two more characters (the
domain name), a period (escaped as \.), and, finally, at least two more characters for the domain
extension. For example, marco@apress.com is a valid e-mail address, while marco@apress or
marco.apress.com would fail validation. The proposed expression is quite simple in reality. Using a more
complex regular expression, you could check that the domain name is valid,
that the extension is not made up (see http://www.icann.org for a list of allowed domain name extensions),
and so on. However, regular expressions obviously don‘t provide any way to check that a domain actually
exists or is online.
The CustomValidator Control
If the validation controls described so far are not flexible or powerful enough for you, and if you need
more advanced or customized validation, then the CustomValidator control is what you need. The
CustomValidator allows you to execute your custom client-side and server-side validation routines. You
can associate these routines with the control so that validation is performed automatically. If the validation
fails, the Page.IsValid property is set to false, as occurs with any other validation control.
The client-side and server-side validation routines for the CustomValidator are declared similarly. They
both take two parameters: a reference to the validator and a custom argument object. The custom argument
object provides a Value property that contains the current value of the associated input control (the value
you have to validate) and an IsValid property through which you specify whether the input value is valid.
If you want to check that a number is a multiple of five, for example, you could use a client-side
JavaScript validation routine like this:
<script type="text/javascript">
function EmpIDClientValidate(ctl, args)
{
// the value is a multiple of 5 if the modulus by 5 is 0
args.IsValid=(args.Value%5 == 0);
}
</script>
To associate this code with the control so that client-side validation is performed automatically,
you simply need to set the ClientValidationFunction to the name of the function (in this case,
EmpIDClientValidate).Next, when the page is posted back, ASP.NET fires the
CustomValidator.ServerValidate event.You handle this event to perform the same task using C# code.
And although the JavaScript logic is optional, you must make sure you include a server-side validation
routine to ensure the validation is performed even if the client is using a down-level browser (or tampers
with the web-page HTML).
Here‘s the event handler for the ServerValidate event. It performs the C# equivalent of the
client-side validation routine shown earlier:
The ValidationSummary control doesn‘t perform any validation. Instead, it allows you to show
a summary of all the errors in the page. This summary displays the ErrorMessage value of each
failed validator. The summary can be shown in a client-side JavaScript message box (if the
ShowMessageBox property is true) or on the page (if the ShowSummary property is true). You can set
both ShowMessageBox and ShowSummary to true to show both types of summaries, since they are not
exclusive. If you choose to display the summary on the page, you can choose a style with the
DisplayMode property (possible values are SingleParagraph, List, and BulletList). Finally, you can set a
title for the summary with the HeaderText property.
The control declaration is straightforward:
<asp:ValidationSummary runat="server" ID="Summary"
ShowSummary="true" DisplayMode="BulletList"
HeaderText="<b>Please review the following errors:</b>"/>
Figure 4-13 shows an example with a validation summary that displays a bulleted summary on
the page and in a message box.
Ad Rotator:
This control is a banner ad that displays one out of a set of images based on a predefined
schedule that‘s saved in an XML file.
The AdRotator randomly selects banner graphics from a list that‘s specified in an external XML
schedule file.Before creating the control, it makes sense to define the XML schedule file. Here‘s an
example:
Write the following g code in a XML file on your project
<Advertisements>
<Ad>
<ImageUrl>hdr_logo.gif</ImageUrl>
<NavigateUrl>http://www.apress.com</NavigateUrl>
<AlternateText>Apress - The Author's Press</AlternateText>
<Impressions>20</Impressions>
<Keyword>books</Keyword>
</Ad>
<Ad>
<ImageUrl>techEd.jpg</ImageUrl>
<NavigateUrl> http://www.microsoft.com/events/teched2008</NavigateUrl>
<AlternateText>TechEd from Microsoft</AlternateText>
<Impressions>20</Impressions>
<Keyword>Java</Keyword>
</Ad>
<!-- More ads can go here. -->
</Advertisements>
This control creates a functionally rich and good-looking calendar box that shows one month at a
time. The user can move from month to month, select a date, and even select a range of days (if
multiple selection is allowed). The Calendar control has many properties that, taken together,
allow you to change almost every part of this control. For example, you can fine-tune the foreground and
background colors, the font, the title, the format of the date, the currently selected date, and so on. The
Calendar also provides events that enable you to react when the user changes the current month
(VisibleMonthChanged), when the user selects a date (SelectionChanged), and when the Calendar is about
to render a day (DayRender).
The following Calendar tag sets a few basic properties:
<asp:Calendar runat="server" ID="Calendar1"ForeColor="red" BackColor="lightyellow" />
The most important Calendar event is SelectionChanged, which fires every time a user clicks a
date. Here‘s a basic event handler that responds to the SelectionChanged event and displays the
selected date:
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
lblDates.Text = "You selected: " + Calendar1.SelectedDate.ToLongDateString();
}
ASP.NET includes a variety of options for state management. You choose the right option depending on
the data you need to store, the length of time you want to store it, the scope of your data (whether it‘s
limited to individual users or shared across multiple requests), and additional security and performance
considerations. The different state management options in ASP.NET are complementary, which means
you‘ll almost always use a combination of them in the same web application (and often the same page).
View state should be your first choice for storing information within the bounds of a single page. View
state is used natively by the ASP.NET web controls. It allows them to retain their properties between
postbacks. You can add your own data to the view state collection using a built-in page property called
ViewState. The type of information you can store includes simple data types and your own custom objects.
Like most types of state management in ASP.NET, view state relies on a dictionary collection,
where each item is indexed with a unique string name. For example, consider this code:
ViewState["Counter"] = 1;
This places the value 1 (or rather, an integer that contains the value 1) into the ViewState
collection and gives it the descriptive name Counter. If there is currently no item with the name
Counter, a new item will be added automatically. If there is already an item indexed under the
name Counter, it will be replaced. When retrieving a value, you use the key name. You also need to cast
the retrieved value to the appropriate data type. This extra step is required because the ViewState
collection casts all items to the base Object type, which allows it to handle any type of data.
Here‘s the code that retrieves the counter from view state and converts it to an integer:
int counter;
if (ViewState["Counter"] != null)
{
counter = (int)ViewState["Counter"];
}
If you attempt to look up a value that isn‘t present in the collection, you‘ll receive a
NullReferenceException. To defend against this possibility, you should check for a null value
before you attempt to retrieve and cast data that may not be present.
One of the most significant limitations with view state is that it‘s tightly bound to a specific page.
If the user navigates to another page, this information is lost. This problem has several solutions,
and the best approach depends on your requirements. In the following sections, you‘ll see how to
pass information from one page to the next using the query string and cross-page posting. If neither of
these techniques is right for your scenario, you‘ll need to use a form of state management that has a
broader scope, such as cookies, session state, or application state, all of which are discussed later in this
chapter.
One common approach is to pass information using a query string in the URL. You will commonly find
this approach in search engines. For example, if you perform a search on the Google website, you‘ll be
redirected to a new URL that incorporates your search parameters. Here‘s an example:
http://www.google.ca/search?q=organic+gardening
The query string is the portion of the URL after the question mark. In this case, it defines a single
variable named q, which contains the ―organic+gardening‖ string.
The advantage of the query string is that it‘s lightweight and doesn‘t exert any kind of burden on
the server. Unlike cross-page posting, the query string can easily transport the same information
from page to page. It has some limitations, however:
The receiving page has an easier time working with the query string. It can receive the values
from the QueryString dictionary collection exposed by the built-in Request object, as shown here:
string ID = Request.QueryString["recordID"];
If the query string doesn‘t contain the recordID parameter, or if the query string contains the
recordID parameter but doesn‘t supply a value, the ID string will be set to null.
Note that information is always retrieved as a string, which can then be converted to another
simple data type. Values in the QueryString collection are indexed by the variable name.
Session State
Session state is the heavyweight of state management. It allows information to be stored in one pageand
accessed in another, and it supports any type of object, including your own custom data types. Best of all,
session state uses the same collection syntax as view state. The only difference is the name of the built-in
page property, which is Session. Every client that accesses the application has a different session and a
distinct collection of information. Session state is ideal for storing information such as the items in the
current user‘s shopping basket when the user browses from one page to another. But session state doesn‘t
come for free. Though it solves many of the problems associated with other forms of state management, it
forces the web server to store additional information in memory. This extra memory requirement, even if it
is small, can quickly grow to performance-destroying levels as thousands of clients access
the site.
Example
5:-Open the Web.config file from the Solution Explorer window and write the following
code on<System.web> tag.
6:- Add a New web application form again . The form name is session2.aspx.
7:- Add a Label Control on the session2.aspx form.
8:- Write the Following Code on Form_Load ( ) event.
Session2_Load ( )
{
If (Session[“id”] != null)
{
Label1.Text=Session[“id”].toString( );
}
Else
{
Response.Redirect(“ session.aspx”);
}
}
Application State
Application state allows you to store global objects that can be accessed by any client. Application state is
based on the System.Web.HttpApplicationState class, which is provided in all web pages through the
built-in Application object.
Application state is similar to session state. It supports the same types of objects, retains
information on the server, and uses the same dictionary-based syntax. A common example with
application state is a global counter that tracks how many times an operation has been performed
by all of the web application‘s clients.
For example, you could create a global.asax event handler that tracks how many sessions have
been created or how many requests have been received into the application. Or you can use similar logic in
the Page.Load event handler to track how many times a given page has been requested by various clients.
Here‘s an example of the latter:
Application state isn‘t often used, because it‘s generally inefficient. In the previous example, the
counter would probably not keep an accurate count, particularly in times of heavy traffic. For example,
if two clients requested the page at the same time, you could have a sequence of events like this:
In other words, one request isn‘t counted because two clients access the counter at the same
time. To prevent this problem, you need to use the Lock() and UnLock() methods, which explicitly
allow only one client to access the Application state collection at a time, as follows:
UNIT III
ADO .NET
Most applications need data access at one point of time making it a crucial component when working
with applications. Data access is making the application interact with a database, want the user to be able
to choose multiple options, use a check box.
where all the data is stored. Different applications have different requirements for database access. VB
.NET uses ADO .NET (Active X Data Object) as it's data access and manipulation protocol which also
enables us to work with data on the Internet. Let's take a look why ADO .NET came into picture replacing
ADO.
Evolution of ADO.NET
The first data access model, DAO (data access model) was created for local databases with the built-in Jet
engine which had performance and functionality issues. Next came RDO(Remote Data Object)
and ADO (Active Data Object) 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 aconnected 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. For example, an application with connected data
access may do well when connected to two clients, the same may do poorly when connected to 10 and
might be unusable when connected to 100 or more. Also, open database connections use system
resources to a maximum extent making the system performance less effective.
Why ADO.NET?
To cope up with some of the problems mentioned above, ADO .NET came into existence. 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.
ADO.NET uses a multilayered architecture that revolves around a few key concepts, such as Connection,
Command, and DataSet objects.
One of the key differences between ADO.NET and some other database technologies is how it
deals with the challenge of different data sources. In many previous database technologies, such as classic
ADO, programmers use a generic set of objects no matter what the underlying data source is.
For example, if you want to retrieve a record from an Oracle database using ADO code, you use
the same Connection class you would use to tackle the task with SQL Server. This isn‘t the case in
ADO.NET, which uses a data provider model.
The ADO.NET Object Model
A data provider is a set of ADO.NET classes that allows you to access a specific database, execute SQL
commands, and retrieve data. Essentially, a data provider is a bridge between your application and a data
source.
The ADO.NET classes are grouped into several namespaces. Each provider has its own
namespace, and generic classes such as the DataSet are stored in the System.Data namespaces.
Connected And disconnected Database
The architecture of ADO.net, in which connection must be opened to access the data retrieved from
database is called as connected architecture. Connected architecture was built on the classes connection,
command, datareader and transaction.
Connected architecture is when you constantly make trips to the database for any CRUD (Create, Read,
Update and Delete) operation you wish to do. This creates more traffic to the database but is normally
much faster as you should be doing smaller transactions.
The architecture of ADO.net in which data retrieved from database can be accessed even when connection
to database was closed is called as disconnected architecture. Disconnected architecture of ADO.net was
built on classes connection, dataadapter, commandbuilder and dataset and dataview.
Disconnected architecture is a method of retrieving a record set from the database and storing it giving you
the ability to do many CRUD (Create, Read, Update and Delete) operations on the data in memory, then it
can be re-synchronized with the database when reconnecting. A method of using disconnected architecture
is using a Dataset.
DataReader
DataReader is Connected Architecture since it keeps the connection open until all
rows are fetched one by one
DataSet
Dataset is DisConnected Architecture since all the records are brought at once and
there is no need to keep the connection alive
Connected Disconnected
It is connection oriented. It is dis_connection oriented.
Datareader DataSet
Connected methods gives faster performance Disconnected get low in speed and performance.
connected can hold the data of single table disconnected can hold multiple tables of data
connected you need to use a read only forward only disconnected you cannot
data reader
Data Reader can't persist the data Data Set can persist the data
It is Read only, we can't update the data. We can update data
Example
(
[ID] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL,
[Name] [varchar](255) NULL,
[Age] [int] NULL,
[Address] [varchar](255) NULL
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Pagetitle>
</head>
<body>
</form>
</body>
</html>
Code Behind
{
StrSQL = "SELECT * FROM Student";
StrConnection = "Data Source=ServerName;Initial Catalog=Database;User
ID=Username;Password=password";
{
using (SqlConnection objConn = new SqlConnection(StrConnection))
{
SqlCommand objCmd = new SqlCommand(StrSQL, objConn);
objCmd.CommandType = CommandType.Text;
objConn.Open();
SqlDataReader objDr = objCmd.ExecuteReader();
GridView1.DataSource = objDr;
GridView1.DataBind();
objConn.Close();
}
{
SqlDataAdapter objDa = new SqlDataAdapter();
DataSet objDs = new DataSet();
using (SqlConnection objConn = new SqlConnection(StrConnection))
{
SqlCommand objCmd = new SqlCommand(StrSQL, objConn);
objCmd.CommandType = CommandType.Text;
objDa.SelectCommand = objCmd;
objDa.Fill(objDs, "Student");
GridView1.DataSource = objDs.Tables[0];
GridView1.DataBind();
}
Connected Database
Protected void Page _Load (object sender, EventArgs e)
{
String StrSQL = "SELECT * FROM Student";
String StrConnection = "Data Source=ServerName ; Initial
Catalog=Database ; Integrated Security=True‖ ;
}
protected void Connected_Click(object sender, EventArgs e)
{
SqlConnection objConn = new SqlConnection(StrConnection))
{
SqlCommand objCmd = new SqlCommand(StrSQL, objConn);
objCmd.CommandType = CommandType.Text;
objConn.Open();
SqlDataReader objDr = objCmd.ExecuteReader();
GridView1.DataSource = objDr;
GridView1.DataBind();
objConn.Close();
}
}
DisConnected Database
{
SqlDataAdapter objDa = new SqlDataAdapter();
DataSet objDs = new DataSet();
using (SqlConnection objConn = new SqlConnection(StrConnection))
{
SqlCommand objCmd = new SqlCommand(StrSQL, objConn);
objCmd.CommandType = CommandType.Text;
objDa.SelectCommand = objCmd;
objDa.Fill(objDs, "Student");
GridView1.DataSource = objDs.Tables[0];
GridView1.DataBind();
}
}
The Connection Class
The Connection class allows you to establish a connection to the data source that you want to interact
with. Before you can do anything else (including retrieving, deleting, inserting, or updating data), you
need to establish a connection. The core Connection properties and methods are specified by the
IDbConnection interface, which all Connection classes implement.
Connection Strings
When you create a Connection object, you need to supply a connection string. The connection string is a
series of name/value settings separated by semicolons (;). The order of these settings is unimportant, as is
the capitalization. Taken together, they specify the basic information needed to create a connection.
NOTE:-
If you‘re using the OLE DB provider, your connection string will still be similar, with the addition of a
provider setting that identifies the OLE DB driver. For example, you can use the following connection
string to connect to an Oracle database through the MSDAORA OLE DB provider:
<connectionStrings>
strings. Here‘s an example:
<configuration>
<connectionStrings>
<add name="Northwind" connectionString="Data Source=localhost; Initial Catalog=Northwind;
Integrated Security=SSPI"/>
</connectionStrings>
...
</configuration>
You can then retrieve your connection string by name from the
The following examples assume you‘ve added this connection string to your web.config file.
Testing a Connection
Once you‘ve chosen your connection string, managing the connection is easy—you simply use the Open()
and Close() methods.
You can use the following code in the Page. Load event handler to test a connection and write
System.Data.SqlClient // namespace.
string connectionString
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
try
{
con.Open();
lblInfo.Text = "<b>Server Version:</b> " + con.ServerVersion;
lblInfo.Text += "<br /><b>Connection Is:</b> " + con.State.ToString();
}
catch (Exception err)
{
lblInfo.Text = "Error reading the database. " + err.Message;
}
finally
{
con.Close();
lblInfo.Text += "<br /><b>Now Connection Is:</b> " +
con.State.ToString();
}
The Command and DataReader Classes
The Command class allows you to execute any type of SQL statement. Although you can use a
Command class to perform data definition tasks (such as creating and altering databases, tables,
and indexes), you‘re much more likely to perform data manipulation tasks (such as retrieving and
updating the records in a table).
The provider-specific Command classes implement standard functionality, just like the Connection
classes. In this case, the IDbCommand interface defines a few key properties and
the core set of methods that are used to execute a command over an open connection.
Command Basics
Before you can use a command, you need to choose the command type, set the command text, and bind
the command to a connection. You can perform this work by setting the corresponding properties
(CommandType, CommandText, and Connection), or you can pass the information you need as
constructor arguments. The command text can be a SQL statement, a stored procedure, or the name of a
table. It all depends on the type of command you‘re using. Three types of commands exist, as listed in
Table 7-3.
For example, here’s how you would create a Command object that represents a query:
Alternatively, to use a stored procedure, you would use code like this:
These examples simply define a Command object; they don‘t actually execute it. The Command
object provides three methods that you can use to perform the command, depending on whether
you want to retrieve a full result set, retrieve a single value, or just execute a nonquery command.
Command Methods:-
A DataReader allows you to read the data returned by a SELECT command one record at a time, in a
forward-only, read-only stream. This is sometimes called a firehose cursor. Using a DataReader is the
simplest way to get to your data, but it lacks the sorting and relational abilities of the disconnected DataSet
described in Chapter 8. However, the DataReader provides the quickest possible no-nonsense access to
data.
DataReader Methods:-
The ExecuteReader() Method and the DataReader
The following example creates a simple query command to return all the records from the Employees table
in the Northwind database. The command is created when the page is loaded.
The following procedure shows how you can get (and write on the page) the number of records
in the Employees table with this approach:
The code is fairly straightforward, but it‘s worth noting that you must cast the returned value to
the proper type because ExecuteScalar() returns an object.
The ExecuteNonQuery() method executes commands that don‘t return a result set, such as INSERT,
DELETE, and UPDATE. The ExecuteNonQuery() method returns a single piece of information—the
number of affected records (or –1 if your command isn‘t an INSERT, DELETE, or UPDATE statement).
Here’s an example that uses a DELETE command by dynamically building a SQL string:
DataSet provides a disconnected representation of result sets from the Data Source, and it is
completely independent from the Data Source. DataSet provides much greater flexibility when
dealing with related Result Sets.
DataSet contains rows, columns,primary keys, constraints, and relations with other DataTable
objects. It consists of a collection of DataTable objects that you can relate to each other with
DataRelation objects. The DataAdapter Object provides a bridge between the DataSet and the
Data Source.
ASP.NET DataAdapter:-
DataAdapter serves as a bridge between a DataSet and SQL Server for retrieving and saving
data. We can use SqlDataAdapter Object in combination with Dataset Object. DataAdapter
provides this combination by mapping Fill method, which changes the data in the DataSet to
match the data in the data source, and Update, which changes the data in the data source to
match the data in the DataSet.
da.Fill(ds);
The SqlDataAdapter Object and DataSet objects are combine to perform both data access and data
manipulation operations in the SQL Server Database. When the user perform the SQL operations like
Select , Insert etc. in the data containing in the Dataset Object , it wont directly affect the Database, until
the user invoke the Update method in the SqlDataAdapter.
The DataAdapter can perform Select , Insert , Update and Delete SQL operations in the Data Source. The
SelectCommand property of the DataAdapter is a Command Object that retrieves data from the data
source. Other command properties of the DataAdapter are Command objects that manage updates to the
data in the data source according to modifications made to the data in the DataSet.
DataAdapter Methods:-
Example
default.aspx.cs
using System;
using System.Data ;
using System.Data.SqlClient ;
using System.Configuration;
ListBox1.Items.Add(ds.Tables[0].Rows[i].ItemArray[0].ToString ());
}
connection.Close();
}
catch (Exception ex)
{
Label1.Text = "Error in execution " + ex.ToString();
}
}
}
Data Bound Controls
Data Bound controls are controls that are bound to data sources. Traditionally the DataGrid is the principal
data bound control in ASP.NET 1.x. Though DataGrid is still supported, ASP.NET 2.0 introduces three
new controls—GridView, FormView and DetailsView.
Unlike in ASP.NET 1.x, all controls descend from the BaseDataBoundControl class. It has two basic child
classes DataBoundControl and HierarchicalDataBoundControl. While TreeView and Menu are examples
of the latter, AdRotator, ListControls such as BulletedList, CheckboxList, DropDownList, ListBox and
RadioButtonList, and CompositeDataBoundControls such as DetailsView, FormsView and GridView are
examples of the former.
All Data bound controls can be classified into Simple, composite and hierarchical controls. The
DataBoundControl Base class defines the common characteristics of non-hierarchical controls which share
the same base class. It is inherited from the WebControl and has all the visual and style properties of the
base class. Additionally it has infrastructural properties such as Context, Page and AccessKey.
DataMember property of the control selects the list of data that the control has to bind to when the
DataSource contains more than one list. DataSource indicates the source of the data it has to bind to. It is
imperative that the DataSource must be an object (unlike ASP.NET 1.x) that implements the IEnumerable
or the IListSource interface. DataSourceId is the ID of the data source object used to retrieve data.
The DataBoundControl class has only one method—the DataBind method. This method is called when
data has to be pumped out of the data source. The internal implementation of this method has been
tweaked and modified to enhance performance. It takes into account the implementation of the
IEnumerable based data sources but is more sophisticated in execution as it implements the new interfaces
and new data source controls also.
The GridView :-
The GridView is an extremely flexible grid control for showing data in a basic grid consisting of
rows and columns. It includes a wide range of hard-wired features, including selection, paging, sorting,
and editing, and it is extensible through templates. The great advantage of the GridView over the DataGrid
is its support for code-free scenarios. Using the GridView, you can accomplish many common tasks, such
as paging and selection, without writing any code. With the DataGrid, you were forced to handle events to
implement the same features.
Column Types
Example Of GridView Control
The ListView
The ListView is the only new data control in ASP.NET 3.5. It‘s designed to be a replacement for the no-
frills Repeater control that‘s been a part of ASP.NET since .NET 1.0. Essentially, the ListView is an
extremely flexible data-bound control that renders its content based on the templates you define. Unlike
the Repeater, the ListView adds higher-level features such as selection and editing, which work in the
same way as those in the GridView. But unlike the GridView, the ListView doesn‘t support a field-based
model for creating quick-and-easy grids with aminimum of markup. Depending on your perspective, the
ListView is either a more flexible version of the GridView that requires more work or a more feature-
filled version of the simple Repeater.
DetailsView
The GridView control shows all of the records from its data source control at once, but the
DetailsView control displays one row from a data source at a time by rendering an HTML
table. The DetailsView control is also often used in a master-details scenario where the
selected record of the master control determines the record to display in the detail view. The
DetailsView supports both declarative and programmatic databinding. From the following
chapters you can see some important usage of DetailsView control.
Example:-
Update detailsView
<body>
<form id="form1" runat="server">
<div>
<asp:DetailsView id="DetailsView1" DataSourceID="SqlDataSource1"
DataKeyNames="stor_id"
AllowPaging ="true" Runat="server" AutoGenerateEditButton="true" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SQLDbConnection %>"
SelectCommand="select * from [stores]"
UpdateCommand="UPDATE [stores] SET
stor_name=@stor_name,stor_address=@stor_address,city=@city,
state=@state, zip=@zip WHERE stor_id=@stor_id" />
</div>
</form>
</body>
The Repeater control that render HTML to display the contents of a list or data source to which they are
bound. If the Repeater controls data source is set but no data is returned, the control renders with no items.
If the data source is Nothing, the Repeater is not rendered. The following ASP.NET program shows how
to display data using a Repeater Control.
Example:-
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater id="repeater1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "stor_id")%>
<%# DataBinder.Eval(Container.DataItem, "stor_name")%> <br />
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SQLDbConnection %>"
SelectCommand="select [stor_id],[stor_name] from stores" />
</div>
</form>
</body>
Example
How to bind multiple DropDownlist
This article shows how to create three DropDownList to display countries, states and cities. When you
select a country then its automatically shows the states name of that country in next DropDownList.
Then when you select a state, the cities DropDownList will fetch the related cities for that state.
Country Table
Countrystate Table
StateCity Table
Countrytable
Statetable
Now drag and drop three DropDownList to display countries, states and cities and three update panel
control on the page.
Figure1
.aspx code
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="countrypanel" runat="server">
<ContentTemplate >
<span class="style1"><strong>Select Country:</strong></span>
<asp:DropDownList ID="ddlcountry" AutoPostBack ="true" AppendDataBoundItems
="true" runat="server" Height="20px" Width="156px"
onselectedindexchanged="ddlcountry_SelectedIndexChanged" BackColor="#3399FF"
ForeColor="#FF9999">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID ="ddlcountry" />
</Triggers>
</asp:UpdatePanel>
<br />
.CS code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace CountryStateCity
{
public partial class WebForm1 : System.Web.UI.Page
{
private SqlConnection conn = new SqlConnection("Data source=.; uid=sa;
pwd=Password$2; database=CountryStateCity");
SqlDataReader dr = cmd.ExecuteReader();
ddlstate.DataSource = dr;
ddlstate.Items.Clear();
ddlstate.Items.Add("--Please Select state--");
ddlstate.DataTextField = "State";
ddlstate.DataValueField = "StateID";
ddlstate.DataBind();
conn.Close();
}
public void Bind_ddlCity()
{
conn.Open();
SqlCommand cmd = new SqlCommand("select * from stateCity where StateId ='" +
ddlstate.SelectedValue + "'", conn);
SqlDataReader dr = cmd.ExecuteReader();
ddlcity.DataSource = dr;
ddlcity.Items.Clear();
ddlcity.Items.Add("--Please Select city--");
ddlcity.DataTextField = "City";
ddlcity.DataValueField = "CityID";
ddlcity.DataBind();
conn.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind_ddlCountry();
}
}
protected void ddlcountry_SelectedIndexChanged(object sender, EventArgs e)
{
Bind_ddlState();
}
protected void ddlstate_SelectedIndexChanged(object sender, EventArgs e)
{
Bind_ddlCity();
}
}
}
Figure2
Now select a country, then its automatically shows the states name of that country in next
DropDownList. For example we select USA.
Figure3
Now select a State, then its automatically shows the cities name of that state in next DropDownList.
For example we select Punjab.
Example-2
Creating data Grid with bind;-
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using System.Data.SqlClient;
Now when User will run the project then the window will look like as:
Click the ok button and we can show the data at the same page.
UNIT-4
An Introduction to XML
In its simplest form, the XML specification is a set of guidelines, defined by the W3C (World Wide Web
Consortium), for describing structured data in plain text. Like HTML, XML is a markup language based
on tags within angled brackets. As with HTML, the textual nature of XML makes the data highly portable
and broadly deployable. In addition, you can create and edit XML documents in any standard text editor.
Unlike HTML, XML does not have a fixed set of tags. Instead, XML is a metalanguage that allows for the
creation of other markup languages. In other words, XML sets out a few simple rules for naming and
ordering elements, and you create your own data format with your own custom elements.
For example, the following document shows a custom XML format that stores a product catalog.
It starts with some generic product catalog information, followed by a product list with itemized
information about two products.
But if anything, XML is much more useful today than it ever was before. The benefits of using XML in a
modern application include the following:
• Adoption: XML is ubiquitous. Many companies are using XML to store data or are actively considering
it. Whenever data needs to be shared, XML is automatically the first (and often the only) choice that‘s
examined.
• Extensibility and flexibility: XML imposes no rules about data semantics and does not tie companies
into proprietary networks, unlike EDI (Electronic Data Interchange). As a result, XML can fit any type of
data and is cheaper to implement.
• Related standards and tools: Another reason for XML‘s success is the tools (such as parsers) and the
surrounding standards (such as XML Schema, XPath, and XSLT) that help in creating and processing
XML documents. As a result, programmers in nearly any language have readymade components for
reading XML, verifying that XML is valid, verifying XML against a set of rules (known as a schema),
searching XML, and transforming one format of XML into another.
XML acts like the glue that allows different systems to work together. It helps standardize business
processes and transactions between organizations. But XML is not just suited for data exchange between
companies. Many programming tasks today are all about pplication integration—web applications
integrate multiple web services, e-commerce sites integrate legacy inventory and pricing systems, and
intranet applications integrate existing business applications. All these applications are held together by
the exchange of XML ocuments.
Well-Formed XML
XML is a fairly strict standard. This strictness is designed to preserve broad compatibility. If the rules of
XML weren‘t as strict, it would be difficult to distinguish between a harmless variance and a serious error.
Even worse, some mistakes might be dealt with differently by different XML parsers, leading to
inconsistencies in the way that is processed (or even whether it can be processed at all).
These are the sort of quirks that affected one notorious language that isn‘t based on XML—HTML. To
prevent this sort of problem, all XML parsers perform a few basic quality checks. If an XML document
does not meet these standards, it‘s rejected outright. If the XML document does follow these rules, it‘s
deemed to be well formed. Well-formed XML isn‘t necessarily correct XML—for example, it could still
contain incorrect data—but an XML processor can parse it.
To be considered well formed, an XML document must meet these criteria:
• Elements and attributes must use consistent case. For example, the tags <FirstName> </firstName> do
not comprise a valid element because they have different case.
• An element cannot have two attributes with the same name because there will be no way to distinguish
them from each other. However, an element can contain two nested elements with the same name.
• A document can have only one root element. (The root element is the top-level element that
starts the document and contains all its content.)
• Comments can‘t be placed inside tags. (XML comments have the same format as HTML commentsand
are bracketed with <!-- and --> markers.)
XML Namespaces
As the XML standard gained ground, dozens of XML markup languages (often called XML grammars)
were created, and many of them are specific to certain industries, processes, and types of information. In
many cases, it becomes important to extend one type of markup with additional company-specific
elements, or even create XML documents that combine several different XML grammars. This poses a
problem. What happens if you need to combine two XML grammars that use elements with the same
names? How do you tell them apart? A related, but more typical, problem occurs when an application
needs to distinguish between XML grammars in a document. For example, consider an XML document
that has order-specific information using a standard called OrderML and client-specific information using
a standard called ClientML. This document is sent to an order-fulfillment application that‘s interested only
in the OrderML details. How can it quickly filter out the information that it needs and ignore the unrelated
details? The solution is the XML Namespaces standard. The core idea behind this standard is that every
XML markup language has its own namespace that uniquely identifies all related elements. Technically,
namespaces disambiguate elements by making it clear to which markup language they belong. All XML
namespaces use URIs (universal resource identifiers). Typically, these URIs look like a web-page URL.
For example, http://www.mycompany.com/mystandard is a typical name for a namespace. Though the
namespace looks like it points to a valid location on the Web, this isn‘t required (and shouldn‘t be
assumed). URIs are used for XML namespaces because they are more likely to be unique. Usually, if you
create a new XML language, you‘ll use a URI that points to adomain or website you control. That way,
you can be sure that no one else is likely to use that URI. However, the namespace doesn‘t need to be a
URI—any sequence of text is acceptable.
It would be cumbersome if you needed to type in the full namespace URI every time you wrote
an element in an XML document. Fortunately, when you assign a namespace in this fashion, it
becomes the default namespace for all child elements. For example, in the XML document shown here,
the <order> and <orderItem> elements are both placed in the http://mycompany/OrderML namespace:
<?xml version="1.0"?>
<order xmlns="http://mycompany/OrderML">
<orderItem>...</orderItem>
<orderItem>...</orderItem>
</order>
• The XmlDataSource extracts information from an XML file, rather than a database or data
access class. It provides other controls with an XmlDocument object for data binding.
• XML content is hierarchical and can have an unlimited number of levels. By contrast, the Sql-
DataSource and ObjectDataSource return flat tables of data.
The XmlDataSource also provides a few features in common with the other data source controls,
including caching and rich design support that shows the schema of your data in bound controls.
In the following sections, you‘ll see how to use the XmlDataSource in simple and complex
scenarios.
Nonhierarchical Binding
The simplest way to deal with the hierarchical nature of XML data is to ignore it. In other words, you can
bind the XML data source directly to an ordinary grid control such as the GridView.
The first step is to define the XML data source and point it to the file that has the content you
want to use:
Now you can bind the GridView with automatically generated columns, in the same way you bind it to any
other data source:
In other words, if you don‘t customize the XML data binding process, you can bind only to the
top-level of nodes, and you can display text only from the attributes of that node. Furthermore, if
there is more than one type of top-level node, the bound control uses the schema of the first node. In other
words, if you have a document like this:
<DvdList>
<Retailer ID="..." Name="...">...</Retailer>
<Retailer ID="..." Name="...">...</Retailer>
<DVD ID="..." Category="...">...</DVD>
<DVD ID="..." Category="...">...</DVD>
<DVD ID="..." Category="...">...</DVD>
</DvdList>
the GridView will inspect the first node and create an ID and Name column. It will then attempt to display
ID and name information for each node. If no matching attribute is found (for example, the <DVD>
specifies a name), then that value will be left blank. Similarly, the Category attribute won‘t be used, unless
you explicitly define it as a column.
All of this raises an obvious question—how do you display other information from deeper down
in the XML document? You have a few options:
Now that you‘ve taken an exhaustive look at general-purpose XML and .NET, it‘s worth taking a look at a
related topic—the XML support that‘s built into ADO.NET. ADO.NET supports XML through the
disconnected DataSet and DataTable objects. Both have the built-in intelligence to convert their collection
rows into an XML document. You might use this functionality for several reasons. For example, you
might want to share data with another application on another platform. Or you might simply use the XML
format to serialize to disk so you can retrieve it later. In this case, you still use the same methods, although
the actual data format isn‘t important.
Table 14-3 lists all the XML methods of the DataSet.
The Web Services Description Language (WSDL) is the description of a Web service generated for all
Web services. If you are using the .NET platform to create a client, use WSDL.EXE to create a proxy
class from the WSDL of the Web service (more about WSDL.EXE in a moment). If you are consuming
the Web service over .aspx pages, you need to import the proxy file <%@ Import
namespace="AnyService" %>, which should reside in the folder C:\inetpub\wwwroot\Services\bin\.
Once you have the Proxy class code, compile it into a library and use the Proxy class library in your
clients to call methods on a Web service. A proxy is a component that acts on behalf of the remote Web
service; it allows access to the remote Web service via SOAP and takes care of all the plumbing beneath.
The Web service client can use the proxy as a real object and access its properties and methods. When we
access a Web service via a proxy, the proxy will convert our Web service call into a SOAP message and
send the SOAP request to the Web service. When it receives the raw SOAP-based XML response back
from the Web service, it converts the XML response to an object accessible by the client and returns the
object to the client.
For the client to use the Web service it should have knowledge of how the Web service is implemented
and how to call it. But you can talk to a Web service without knowing how it is implemented. The client
cannot know automatically about the Web service. Hence all Web services automatically generate an
XML document with WSDL grammar to describe themselves. If you have installed the Web service under
a virtual directory called "myservice," you can get the WSDL of the service by calling the following URL
in your browser: http://localhost/myservice/service.asmx?WSDL. This will generate an XML file and
display it in your browser. The displayed file is the WSDL of the Web service.
A number of Web services technologies, such as SOAP, WSDL, and HTTP, are now used to pass
messages between machines. ASP.NET provides support for Web services with the .asmx file. An .asmx
file is a text file similar to an .aspx file. The .asmx files can be part of an ASP.NET application that
includes .aspx files. They are then URI addressable, just as .aspx files are. Listing 23.22 shows the file for
a "Hello" ASP.NET Web service.
using System;
using System.Web.Services;
This file starts with an ASP.NET directive, WebService, and sets the language to C#. Next, the class
Hello is declared. This class is derived from the base class WebService. Finally, any methods that will
be accessible as part of the service have the custom attribute [WebMethod] in front of their
signatures. To make this service available, we might name the file HelloWorld.asmx and place it on a
server called XXX.com in a virtual directory called YYY. With virtually any HTML 3.2 or later browser,
you could then enter the URL http://XXX.com/YYY/Hello.asmx, and the resulting page would show
the public methods for this Web service (those marked with the WebMethod attribute), as well as
which protocols (such as SOAP or HTTP GET) you can use to invoke these methods. Entering
http://XXX.com/YYY/Hello.asmx?WSDL into the Internet Explorer address bar produces the same
information as an XML file, based on the WSDL grammar. This WSDL file is used by clients that
access the service and is very important. The WSDL.EXE tool in the .NET SDK (or in the Visual Studio
.NET integrated development environment, "Add Web Reference" on the Project menu) can be used
to download the WSDL description of a Web service and create a proxy class that addresses the
service.
using Hello;
Hello myHello = new Hello();
Console.WriteLine(myHello.SayHello());
A Web service allows a site to expose programmatic functionality via the Internet. Web services can
accept messages and have the option to return replies to those messages. Today's sites already
expose functionality that allows you to do such things as query a database, book an airline
reservation, check the status of an order, and so on, but no consistent model exists for allowing you
to program against these sites. Web services can be invoked via HTTP POST, HTTP GET, and SOAP is
a remote procedure call protocol and specification developed by a group of companies including
Microsoft and DevelopMentor. It is based on broadly adopted Internet standards such as XML and
typically runs over HTTP.
Visual Studio .NET is the formal shipping vehicle for creating rich Web services on the .NET platform.
With the release of Visual Studio .NET (http://msdn.microsoft.com/vstudio/nextgen/default.asp) we
are able to create Web services by using ASP+.NET and any language that targets the common
language runtime or ATL Server and unmanaged C++. ATL Server is a collection of Active Template
Library classes that aid the C++ developer in writing native, unmanaged Internet Server Application
Program Interface (ISAPI) extensions and filters. Instead of the .aspx file extension of an ASP Web
page, Web services are saved in files with the extension .asmx.
Whenever the ASP runtime receives a request for a file with an .asmx extension, the runtime
dispatches the call to the Web service handler. This mapping is established in the <httphandlers>
section of the config.web files for the machine and individual applications. Config.web files are
human-readable XML files used to configure almost every aspect of your Web applications. Handlers
are instances of classes that implement the System.Web.IHTTPHandler interface. The IHTTPHandler
interface defines two methods, IsReusable and ProcessRequest. The IsReusable property allows an
instance of IHTTPHandler to indicate whether it can be recycled and used for another request. The
ProcessRequest method takes an HttpContext object as a parameter and is where the developer of
an HTTP handler begins to do his work. A particular handler ultimately services inbound requests that
are received by the ASP+ runtime. After a handler is developed, it is configured in the config.web file
of the application. A typical config.web file for a machine will have code similar to that shown in
Listing 23.24.
<httphandlers>
< add verb="*" path="*.asmx"
type="System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services"
validate="false" />
</httphandlers>
In Listing 23.24 the <httphandlers> section states that for all requests (HTTP verbs such as GET,
POST, or PUT), if the file being requested has an .asmx extension, create an instance of the
WebServiceHandlerFactory, which lives in the System.Web.Services.dll assembly. If the administrator
wanted this handler to accept only the GET verb, he or she would change the verb property to
verb="Get". Handlers accept requests and produce a response. When the HTTP runtime sees a
request for a file with the .aspx extension, the handler that is registered to handle .aspx files is
called. In the case of the default ASP installation, this handler will be
System.Web.UI.PageHandlerFactory. This is equivalent to how .asmx files are handled. For the
default ASP+ installation, Web services are handled by
System.Web.Services.Protocols.WebServiceHandlerFactory.
The custom handler enables ASP to use reflection and dynamically create an HTML page describing
the service's capabilities and methods. The generated HTML page also provides the user a way to
test the Web methods in the service. Another advantage of ASP is seen in publishing Web Service
Definition Language contracts. As noted previously, WSDL is an XML-based grammar for describing
the capabilities of Web services. WSDL allows a Web service to be queried by potential consumers of
your service, you can think of it as an XML-based type library made available via the Web. For output
to be generated, one must only make an HTTP request to the Web service file passing in Service
Description Language (SDL) in the query string (e.g.,
http://localhost/services/myservice.asmx?WSDL ). Another nice aspect of the Web service handler is
that it creates a simple test Web page for your services. This test page allows you to confirm that
everything in your Web service is working without having to write your own test client.
In the next example, we create a Web service that returns the date and time from the server. We
could just return the date and time within a string type and force the caller to parse the string, but
that would not be ideal. Instead, we are going to create a LocalTime struct that will be returned to
the caller. For those of you unfamiliar with structs, they are synonymous with Visual Basic's
userdefined types (UDTs). A walkthrough of the code shows us defining a LocalTime struct that
contains all the date and time information to be returned to the client. Our LocalTime struct holds
eight values: Day, Month, Year, Hour, Minute, Seconds, Milliseconds, and Timezone. The struct's
definition is shown in Listing 23.25.
using System;
using System.Web.Services;
.NET includes a console application that takes care of requesting the WSDL contract of a remote Web
service and generating a proxy to use the service. For you to use a remote Web service a few things
need to happen. You need to know where the Web service resides (e.g.,
http://www.servername.com/wstest.asmx). Then you need to create a local proxy for the remote
service. The proxy allows the developer to work with the remote service as though it were local to
the machine. When instantiated, the proxy accepts method calls from your code as though it were
the remote service object. Calls are packaged into SOAP methods and shipped via HTTP to the
remote Web service. If the remote object is created via the specified channel, the remote service
receives the request, unwraps the envelope, does the work that you asked, then returns the result in
a result envelope. Once the proxy receives this returned envelope, it is unwrapped and delivered to
your code as a native method call.
The WSDL.EXE utility takes care of requesting a WSDL contract from a remote Web service via HTTP
and generating a proxy class for you. Although the Web services utility uses C# as its default proxy-
generation language, any language (including VB and JScript) that implements the ICodeGenerator
interface will work (e.g., just change the language parameter to CS for C#.NET, VB for VB.NET, or JS
for JS.NET).
Running this command generates the TimeServiceProxy.cs file. An instance of this object is what
takes care of accepting method calls, packaging up calls for SOAP, invoking via HTTP, and returning
the results, if any, to the caller. Now that you have a proxy, you need to compile it using the
appropriate compiler (which depends on the language you have chosen). The following command
assumes that the C# compiler (csc.exe) is in the system's path and that you are working in the
directory where your Web service's .asmx file resides.
This command creates a DLL named TimeServiceProxy.dll. Now we will use a Web time service via a
.NET application, a simple console application in C# that prints out the time from the remote service.
This application is compiled into an executable (.exe) file as opposed to a library (.dll). The
TimeTestApp.exe first creates a new instance of our TimeService class that lives in the
bin/TimeServiceProxy.dll assembly. Then a call is made to the GetTime method of the TimeService
class (ts). The returned value is stored in a local variable named lt. The lt variable is of the type
LocalTime. In case it isn't obvious, we should point out that the LocalTime object that we are now
using is originally defined in our remote .asmx file. The WSDL utility is able to create a local
definition of the LocalTime struct based on the SDL contract that is generated and returned from the
Web service handler. Next in our code, we call GetTime and then begin simply to construct a couple
of local strings that contain our formatted time and date. Then we output the results using
Console.WriteLine. See Listing 23.26.
using System;
using TimeService;
class MyClass
{
static void Main()
{
TimeService ts = new TimeService();
LocalTime lt = ts.GetTime();
string stime = lt.Hour + ":" + lt.Minute + ":" + lt.Seconds + "." +
lt.Milliseconds + " " + lt.Timezone;
string sdate = lt.Month + "/" + lt.Day + "/" + lt.Year;
Console.WriteLine("The remote date is: " + sdate);
Console.WriteLine("The remote time is: " + stime);
}
}
This command creates an executable file named TimeTestApp.exe in the local directory. We could
have explicitly told the C# compiler that we wanted an executable, but the compiler creates
executables (/target:exe) by default. We assume you have copied TimeServiceProxy.dll to the
C:\inetpub\wwwroot\Services\bin\ directory (the Web services directory under the default IIS
installation directory). Thus, a simple draft .aspx Web page file that uses our service can be
developed as in Listing 23.27 (note that the code shown is simple; please enhance it depending on
your implementations).
<html>
<head>
</head>
<body>
<script language="C#" runat="server">
public void getDateTime()
{
//Create a Instance of the Proxy Class
TimeService tm = new TimeService();
LocalTime LT = ts.GetTime();
// now "LT" contains the time web service returned DateTime value
}
</script>
</body>
</html>
• Copy all required application files to the target machine. You don‘t need to do anything else.
But if you are using global assemblies accessed through the GAC, you have to verify whether
these assemblies are in place. If not, you have to install them using the gacutil.exe commandline
utility of the .NET Framework.
• Create and configure the database for the application. It‘s important to not only create the
database and its tables but to configure the database server logins and database users.Don‘t forget that if
you are using integrated authentication for connecting to a SQL Server database, you must configure the
account under which ASP.NET is executed (the application pool account or aspnet_wp.exe account) as a
user for the application‘s database.
• Configure IIS as required for the application. Therefore, create necessary application pools
and share the application directory as a virtual directory and configure the virtual directory
appropriately.
• Set up Windows account permissions for the worker process user. The user that is used for
running the worker process (either aspnet_wp.exe or w3wp.exe in IIS 6.0/7.0) needs to have
file system-based read access to the application directories. If your application accesses other resources
such as the registry or event log, you have to configure the permission for the worker process account to
access these resources.
• Add IIS file mappings if you want to process any URLs with filename extensions that are different from
the extensions registered on a default ASP.NET installation.
• Configure ASP.NET (and IIS 7.0 application-specific configuration settings) through the
web.config file for production environments. That means add (or modify) any connection
strings and application settings as well as security and authorization settings, session state
settings, and globalization settings appropriately.
• In some cases it is also required to modify machine.config. For example, if you are in a web
hosting environment and your application runs on multiple web servers for load balancing, you have to
synchronize any encryption keys used for encrypting forms authentication tickets or view state on all those
machines. These keys are stored in machine.config and need to be equal on every machine in the web farm
so that one machine is able to decrypt information encrypted by another machine that previously processed
the request. When it comes to deployment, you should know about a couple of useful things. First, before
running
ASP.NET applications the first time on a server, it might be useful to verify whether ASP.NET has been
installed appropriately. Then you have to decide which version of ASP.NET your application requires.
Actually, as with every other .NET Framework application, you can run as many ASP.NET runtimes side
by side as you want. And of course, don‘t forget to turn off the debug configuration option in the
<compilation> section of web.config.
<configuration>
<system.web>
<!-- Other settings omitted. -->
<compilation defaultLanguage="cs" debug="false" />
</system.web>
<configuration>
UNIT-5
Introduction Of C#
The Goal of C#
The goal of C# is to provide a simple, safe, modern, object-oriented, Internet-
centric, High-performance language for .NET development
.
What Is The C#:-
C# (pronounced "C-sharp") is an pour object-oriented programming language, developed
by Microsoft that aims to combine the computing power of C++ with the programming ease of Visual Basic. C# is
based on C++ and contains features similar to those of Java. Like Java, C# also does not allow multiple inheritance
or the use of pointers (in safe/managed code), but does provide garbage memory collection at runtime, type and
memory access checking.
Evolution of C# :-
The first release of C# (C# 1.0) was all about building a new language for managed code that appealed, mostly,
to C++ and Java programmers.
The second release (C# 2.0) was mostly about adding what wasn’t time to built into the 1.0release. The main
feature for this release was Generics.
The third release (C# 3.0) was all about reducing the impedance mismatch between general purpose
programming languages and databases. To achieve this goal, several functional programming features were added
to the language and LINQ was born.
Most of these features require or are built on top of features of the .NET Framework and, the focus for C#
4.0 was on dynamic programming. Not just dynamic types but being able to talk with anything that isn’t
a .NET class.
Characteristics Of C#:-
1. C# is a simple, modern, object oriented language derived from
C++ and Java.
2. It aims to combine the high productivity of Visual Basic and the raw power of C++.
3. It is a part of Microsoft Visual Studio series like the 2005, 2008,2010.
4. Visual studio supports Vb, VC++, C++, Vbscript, Jscript. All of these languages provide access to
the Microsoft.NET platform.
5. .NET includes a Common Execution engine and a rich class library.
6. Microsoft's JVM equiv. is Common language run time (CLR).
7. CLR accommodates more than one language such as C#, VB.NET, Jscript, ASP.NET, C++.
8. Source code --->Intermediate Language code (IL) ---> (JIT Compiler) Native code.
9. The classes and data types are common to all of the .NET languages.
10. We may develop Console application, Windows application, and Web application using C#.
11. In C# Microsoft has taken care of C++ problems such as Memory management, pointers etc.
12.It supports garbage collection, automatic memory management and a lot.
Application of C#:-
C # is a new language developed by MICROSOFT which are run on the .Net
platform.
It can be used for the variety of application that is supported by the .net platforms.
Console application.
Windows application.
Developing Windows Control.
Developing ASP.NET project.
Creating Web Control.
Providing Web services.
Developing .NET Component Library.
C# KEYWORDS;-
Namespaces:-
A Namespace is simply a logical collection of related classes in C#. We bundle our related
classes (like those related with database activity) in some named collection calling it a namespace (e.g., Data
Activity). As C# does not allow two classes with the same name to be used in a program, the sole purpose of using
namespaces is to prevent name conflicts. This may happen when you have a large number of classes, as is the case
in the Framework Class Library (FCL). It is very much possible that our Connection Class in Data Activity conflicts
with the Connection Class of Internet Activity.
Namespace is the collection of the class.System.Console.ReadLine ( ) in this line system is the
namespace which the Console class is located.
Comments:-
Comments are the programmer’s text to explain the code, are ignored by the compiler
and are not included in the final executable code. C# uses syntax for comments that is similar to Java
and C++. The text following double slash marks (// any comment) are line comments. The comment ends
with the end of the line:
// This is my main method of program
static void Main()
{
...
Comment is the non- executable program. In C# permits the two types of Comments.
1:- Single Line. //
2:- Multiple Line. /*---------------------------------*/
using System;
class Exercise
{
static int Main()
{
return 244006;
}
}
// Namespace:
Using a = System. Console; //A is alias for System.
Console
Class Sample
{
Public static void Main()
{
D.WriteLine()”Hello”;
}
}
// Namespace Declaration
using System;
A namespace declaration, a class, a Main method, and a program statement. It can be compiled with
the following command line:
csc.Welcome.cs
This produces a file named Welcome.exe, which can then be executed. Other programs can be compiled
similarly by substituting their file name instead of Welcome. Cs. For more help about command line
options, type "csc -help" on the command line. The file name and the class name can be totally different.
You‘ll notice an entry in the Main method's parameter list. The parameter name is args, which you'll use
to refer to the parameter later in your program. The string [] expression defines the type of parameter that
args is. The string type holds characters. These characters could form a single word, or multiple words.
The "[ ]", square brackets denote an Array, which is like a list. Therefore, the type of the args parameter is
a list of words from the command-line. Anytime you add string [] args to the parameter list of the Main
method, the C# compiler emits code that parses command-line arguments and loads the command-line
arguments into args. By reading args, you have access to all arguments, minus the application name, that
were typed on the command-line.
You'll also notice an additional Console.WriteLine (...) statement within the Main method. The argument
list within this statement is different than before. It has a formatted string with a "{0}" parameter
embedded in it. The first parameter in a formatted string begins at number 0, the second is 1, and so on.
The "{0}" parameter means that the next argument following the end quote will determine what goes in
that position. Hold that thought, and now we'll look at the next argument following the end quote.
The args [0] argument refers to the first string in the args array. The first element of an Array is number 0,
the second is number 1, and so on. For example, if I typed NamedWelcome Joe on the command-line, the
value of args [0] would be "Joe". This is a little tricky because you know that you typed
NamedWelcome.exe on the command-line, but C# doesn't include the executable application name in the
args list - only the first parameter after the executable application.
The first statement simply writes "What is your name?: " to the console.
The second statement doesn't write anything until its arguments are properly evaluated. The first argument after the
formatted string is Console.ReadLine (). This causes the program to wait for user input at the console. After the user
types input, their name in this case, they must press the Enter key. The return value from this method replaces the
"{0}" parameter of the formatted string and is written to the console. This line could have also been written like this:
The last statement writes to the console as described earlier. Upon execution of the command-line with
"Interactive Welcome", the output will be as follows:
Public static void Main (string [] args) . This line contains a number of keywords:
public, static and void .This is very similar to c++ and Java.
Public-public is an access modifier that tells the c# compilers that the main method accessible by anyone.
Static – the keyword static declared that the Main () Method is a global one and can be called without
creating an instance of the class.
Void – Void is a return type that means, the Main method does not return the any value.
LAB
using System;
namespace ConsoleApplication2
{
class Test
{
Console.ReadLine();
}
}
}
NOTE-
1- Console.WriteLine( )- method is used for print the text or value.
2- Console.ReadLine( )- method are used for accept the value which are input by user or programmer. And
it is always accept the only string type value, if u enter the int type value in the Console.ReadLine ( ) than you will
convert the string to integer type.
3 - Convert.ToInt32( ) -is used for the convert the string type to integer type value ,
Type Conversion:-
7. If Program. Cs is not open in the Code Editor, right-click Program‘s in Solution Explorer and then
click View Code.
8. Replace the contents of Program. Cs with the following code.
9. Press F5 to run the project. A Command Prompt window appears that contains the line Hello
World!
1:- Write a program code on the notepad and save the file as a text file. Name the file Hello. Cs. C#
source code files use the extension .cs.
Open a Visual Studio--Select VS Tools ---/ Select VS 2008 Command prompt. VS-2008
command prompt will open/--- For Run type on the command prompt window . Csc
<filenames>.cs For compile your code.
Enter the following command to compile Hello. Cs. If your program has no compilation errors, an
executable file that is named Hello.exe is created.
Csc Hello. Cs
Let us see the simple program with two classes in below program.
using System;
namespace ConsoleApplication2
{
class Test
{
public void fun()
{
Console.WriteLine(" C# is sharper then C++");
}
class sample
{
static void Main(string[] args)
{
Test t = new Test();
t.fun(); // Calling fun() function
}
}
}
In this program has two class declaration, one for the Test class and another for the Main method .
Test class contains only one method to print a string “C# is sharper then C++”. The Main
method in sample class create an object of class Test and uses it to method fun() contained in Test
class.
The Statement: - y = Math.Sqrt(x); // Invokes the method Sqrt( ) of math Class which Multiple
using System;
namespace ConsoleApplication2
{
class Test
{
} }
Output:- Y= 2.23606
main Method:-
LAB
using System;
namespace ConsoleApplication2
{
class Test
{
}
}
class second
{
public static void main(string[] args)
{
int a = 5;
int b = 12;
int c = a + b;
Console.WriteLine(c);
}
}
In the above example we can declare the two Main ( ) Function in a C# Program but declare in the
different class. In this example first Main () function declare in the Class Test and another Main ()
function is declared in the class second, which are print the different output.
NOTE: - You can also declare the multiple main methods within one program in c#. But you cannot
declare the same class
Data Type:-
The Data type represents the Kind of Data that will be stored in the variable. There are two
kinds of data types in C#.
Value Types (implicit data types, struts and enumeration)
Reference Types (objects, delegates)
Value Type:- They directly contain the data in the variable called value type. Some Example of value type
are char, int, float, double, string which can be used for storing alphabets, integers, and floating point number.
Num
5
int Num ;
Num = 5;
Memory allocation
Variable declaration
Reference Type:- The reference type do not maintain data but they contain the reference to the
variable s, which are stored in the memory. Using more than one variable, you can use the reference types to refer to
a memory location. This means that if the value in the memory location is modified by one of the variable, the other
variable automatically reflect the changed the value. The example of a reference type is string data type.
Str
Address
H E L L O
0 1 2 3 4
Example : int i ;
Assign the value in variable i.
Initialization : i = 123 ;
The above line will reserve an area of 4 bytes in memory to store an integer type values, which will be
referred to in the rest of program by the identifier ‘i‘. You can initialize the variable as you declare it (on
the fly) and can also declare/initialize multiple variables of the same type in a single statement.
Initializing and assigning a value to a variable
LAB
Class Values
{
Static void Main( )
{
int myInt = 7;
System. Console.WriteLine ("Initialized, myInt: {0}",MyInt);
myInt = 5;
System. Console.WriteLine ("After assignment, myInt: {0}",myInt);
}
}
Output:
Initialized, myInt: 7
After assignment, myInt: 5
Here we initialize the variable myInt to the value 7, display that value, reassign the variable
With the value 5, and display it again.
C# allows us to convert a Value Type to a Reference Type, and back again to Value Types .
The operation of Converting a Value Type to a Reference Type is called Boxing and the
reverse operation is called Unboxing.
Boxing
1: int Val = 1;
The first line we created a Value Type Val and assigned a value to Val. The second line , we
created an instance of Object Obj and assign the value of Val to Obj. From the above operation
(Object Obj = i ) we saw converting a value of a Value Type into a value of a corresponding
Reference Type . These types of operation is called Boxing.
UnBoxing
1: int Val = 1;
2: Object Obj = Val; //Boxing
Operators
An operator is a symbol that causes C# to take an action. The C# primitive types (e.g., int)
support a number of operators such as assignment, increment, and so forth. Their use is highly intuitive,
with the possible exception of the assignment operator (=) and the equality operator(==), which are often
confused.
Arithmetic Operators:- C# uses five mathematical operators, four for standard calculations and a
fifth to return the remainder in integer division. The following sections consider the use of these operators.
Operand Description
+ Add
- Subtract
* Multiply
/ Divide
% Remainder or modulo
++ Increment by 1
-- Decrement by 1
Program of addiction,subtraction,multiply,division and modular
using System;
namespace ConsoleApplication2
{
class Test
{
int add = a + b;
Console.WriteLine(add);
int sub = a - b;
Console.WriteLine(sub);
int mul = a * b;
Console.WriteLine(mul);
int div = a / b;
Console.WriteLine(div);
int mod = a % b;
Console.WriteLine(mod);
Console.ReadLine();
}
}
Relational Operators
Relational operators are used to compare two values, and then return a
Boolean ( true or false). The greater-than operator (>), for example, returns true if the value on the left of
the operator is greater than the value on the right. Thus, 5 > 2 returns the value true, while 2 > 5 returns the
value false. tests for equality between the objects on either side of the
Operand Description
== Equality check
!= Un-equality check
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Example:
int a =5; , int b=12;
If (a = = b) //return false
Operand Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
! Bitwise NOT
&& ―Logical‖ or ―short circuit‖ AND
|| ―Logical‖ or ―short circuit‖ OR
Assignment Operators
Assignment operators are used to assign values to variables. Common assignment operators in C# are:
using System;
namespace ConsoleApplication2
{
class Test
{
static void Main(string[] args)
{
int m = 10, n = 20;
Console.WriteLine("m=" + m);
Console.WriteLine("n=" + n);
Console.WriteLine("++m=" + ++m);
Console.WriteLine("n++=" + n++);
Console.WriteLine("m=" + m);
Console.WriteLine("n=" + n);
Console.ReadLine();
}
}
}
Outputs:
M=10
N=20
++m =11
N++ = 20
M=11
N=21
36
Conditional Operator
The Character Pair ? : is a ternary operator available in c# . This operator
is used to construct conditional expression of the form.
Syntex:
exp1 ? exp2 : exp3
example :-
a=12;
b=15;
x= (a>b) ? a:b
In this example x will be assign the value of b.
Bitwise Operator:-
C# supports that may be used for manipulation of data at bit level. These
operators may be used for testing bits of shifting them to the right or left . Bitwise operators may not be
applied to floating point data.
is Relational operators
as Relational operators
typeof Type operators
sizeof Size operators
new object creator
.(dot) Member access
checked Overflow checking
unchecked Prevention of overflow
checking
Type Conversions
Often, you need to convert data from one type to another. Consider the following code:
byte b1=50;
byte b2 = 40;
byte b3 = b1+b2;
When you attempt to compile these lines, you get the error message:
Cannot implicitly convert type 'int' to 'byte'
The problem here is that when you add 2 bytes together, the result will be returned as an int, not as another
byte. This is because a byte can only contain 8 bits of data, so adding 2 bytes together could very easily
result in a value that can‘t be stored in a single byte. If you do want to store this result in a byte variable,
you‘re going to have to convert it back to a byte. The following sections discuss two conversion
mechanisms supported by C# -
Implicit
Explicit.
Implicit conversions
Conversion between types can normally be achieved automatically (implicitly)
only if you can guarantee that the value is not changed in any way. This is why the previous code failed; by
attempting a conversion from an int to a byte, you were potentially losing 3 bytes of data. The compiler
isn‘t going to let you do that unless you explicitly tell it that that‘s what you want to do. If you store the
result in a long instead of a byte, however, you‘ll have no problems:
The following table shows the implicit type conversions supported in C#.
Explicit Conversions
Many conversions cannot be implicitly made between types, and the compiler will give you an error if any
are attempted. These are some of the conversions that cannot be made implicitly:
However, you can explicitly carry out such conversions using casts. When you cast one type to another,
you deliberately force the compiler to make the conversion. A cast looks like this:
Statements
In C# a complete program instruction is called a statement. Programs consist of
sequences of C# statements. Each statement must end with a semicolon (;). For example:
int x; // a statement
x = 23; // another statement
int y = x; // yet another statement
39
C# statements are evaluated in order. The compiler starts at the beginning of a statement list
and makes its way to the bottom. This would be entirely straightforward, and terribly limiting,
were it not for branching. There are two types of branches in a C# program: unconditional
branching and conditional branching.
Program flow is also affected by looping and iteration statements,
which are signaled by the keywords for, while, do, in, and for each. Iteration is discussed later in this
chapter. For now, let's consider some of the more basic methods of conditional and unconditional
branching.
LAB-
Example 3-6. Calling a static method
using System;
namespace ConsoleApplication2
{
class Test
{
static void SomeMethod( )
{
int a = 12, b = 12;
int sum = a + b;
Console.WriteLine("Sum of a+b =" +sum);
}
static void Main( )
{
Console.WriteLine ("In Main! Calling SomeMethod ( )...");
SomeMethod( );
Console.WriteLine (" The above somemethod () n is the static. so uyou can not use
with object.. It is direct call in Main () method....");
Console.ReadLine();
}
}
}
LAB
40
using System;
namespace ConsoleApplication2
{
class Test
{
void SomeMethod( )
{
int a = 12, b = 12;
int sum = a + b;
Console.WriteLine("Sum of a+b =" +sum);
}
static void Main( )
{
Console.WriteLine ("In Main! Calling SomeMethod ( )...");
Test objectTest = new Test();
ObjectTest. SomeMethod( );
Console.ReadLine();
}
}
}
//1- Here Test is a class name and objectTest is the class object.
//2- new is a keyword that is a object creator, used for the create the class object.
Entry
Expression False
True
Type of If Statements
a. Simple If
41
b. If…..else statements
c. Nested if statements
Simple IF Statements
The general form of a simple if statement is…….
if ( Boolean-expression)
{
Statement-block
}
using System;
namespace ConsoleApplication2
{
class Test
{
int a, b, c;
Console.WriteLine("enter the value of a");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter the value of b");
b= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter the value of c");
c = Convert.ToInt32(Console.ReadLine());
if (a > b)
{
c = c + 1;
Console.WriteLine(―true‖ +c);
}
Console. Write(c);
Console.ReadLine();
}
}
}
42
If...else statements
If...else statements branch based on a condition. The condition
is an expression, tested in the head of the if statement. If the condition evaluates true, the
statement (or block of statements) in the body of the if statement is executed. If statements may
contain an optional else statement. The else statement is executed only if the expression in the
head of the if statement evaluates false:
if (expression )
statement1
[else
statement2 ]
Write a program to find the largest number between three number a,b,c .
using System;
namespace ConsoleApplication2
{
class Test
{
int a, b, c;
Console.WriteLine("enter the value of a");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter the value of b");
b= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter the value of c");
c = Convert.ToInt32(Console.ReadLine());
if (a > b)
{
43
Nested if…else statements
When a series of decisions are involved, we may have to
use more than one if….elase statement in the nested form called the nested if statement. It is
possible, and not uncommon, to nest if statements to handle complex conditions.
For example, suppose you need to write a program to evaluate the temperature, and specifically
to return the following types of information:
• If the temperature is 32 degrees or lower, the program should warn you about ice on
the road.
• If the temperature is exactly 32 degrees, the program should tell you that there may be ice
patches.
• If the temperature is higher than 32 degrees, the program should assure you that there is no ice.
LAB of Nested if
using System;
class Values
{
static void Main()
{
int temp = 32;
if (temp <= 32)
{
Console.WriteLine ("Warning! Ice on road!");
if (temp == 32)
{
Console.WriteLine(
"Temp exactly freezing, beware of water.");
}
else
{
Console.WriteLine ("Watch for black ice! Temp: {0}", temp);
}
Console.ReadLine();
}
}
}
44
EXAMPLE:- Lab of Nested if…else
using System;
namespace ConsoleApplication2
{
class Test
{
int year, b, c;
Console.WriteLine("enter the value of a");
y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter the value of b");
b= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter the value of c");
c = Convert.ToInt32(Console.ReadLine());
if (a > b)
{
if (a > c)
{
else
{
Console.WriteLine("c is greater than a & b");
}
}
else if (c>b)
{
Console. Write("c is greater than a & b");
}
else
{
Console. Write("b is greater than c & b");
}
Console.ReadLine();
}
}
}
45
Switch statements:
Nested if statements are hard to read, hard to get right, and hard to
debug. When you have a complex set of choices to make, the switch statement is a more powerful
alternative. The logic of a switch statement is "pick a matching value and act accordingly."
switch (expression )
{
case constant-expression :
statement
jump-statement
[default: statement ]
}
As you can see, like an if statement, the expression is put in parentheses in the head of the
Switch statement. Each case statement then requires a constant expression; that is, a literal or
Symbolic constant or an enumeration. If a case is matched, the statement (or block of statements)
associated with that case is executed.
LAB
Calculator Program Using Switch Case
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Calculator_With_switch_case
{
class Program
{
int num1, num2, result;
char option;
46
Console.WriteLine(" Enter the operation you want to perform");
option= Convert.ToChar(Console.ReadLine());
switch (option)
{
case '1':
result = num1 + num2;
Console.WriteLine(" sum of a+b={0}", result);
break;
case '2':
result = num1 - num2;
Console.WriteLine(" Subtraction of a-b={0}", result);
break;
case '3':
result = num1 * num2;
Console.WriteLine(" Multiplication of a*b={0}", result);
break;
case '4':
result = num1 / num2;
Console.WriteLine(" Division of a/b={0}", result);
break;
default:
Console.WriteLine("Invalid Option");
break;
}
Console.ReadLine();
}
}
class classMain
{
static void Main(string[] args)
{
47
LAB
namespace Calculator_With_switch_case
{
class Program
{
char vowel;
public void number()
{
Console.WriteLine(" Enter the operation you want to perform");
vowel= Convert.ToChar(Console.ReadLine());
switch (vowel)
{
case 'a':
Console.WriteLine( " : is vowel");
break;
case 'e':
Console.WriteLine(" : is vowel");
break;
case 'i':
Console.WriteLine(" : is vowel");
break;
case 'o':
Console.WriteLine(" : is vowel");
break;
case 'u':
Console.WriteLine(" : is vowel");
break;
default:
Console.WriteLine(" Constent");
break;
}
Console.ReadLine();
}
}
class classMain
{
static void Main(string[] args)
{
Program p = new Program();
p.number();
}
}
}
48
Using goto
using System;
public class Tester
{
public static int Main( )
{
int i = 0;
repeat: // the label
Console.WriteLine("i: {0}",i);
i++;
if (i < 10)
goto repeat; // the dastardly deed
return 0;
}
}
LOOP
Sometimes the user may require repeating the set of instruction according to condition. The set
of instruction are repeated by using loop. C# provides different types of loop such as follows.
A looping process, In general would include the following four step.
1- While Loop-
While loop is a top tested loop. In top tested loop firstly the condition is
satisfied after that the statement given in the body of the loop will executed until the condition is
satisfied.
49
}
Syntax:-
Initialization
while (test condition)
{
// body of the loop
}
using System;
class WhileLoop
{
public static void Main()
{
int myInt = 1;
while(left>0)
{
int r = left % 10;
rev = rev * 10 + r;
left = left / 10; //left = Math.floor(left / 10);
}
Console.WriteLine(rev);
50
2- Do- While –
This is bottom tested loop. In bottom tested loop the statement given in the body
of the loop will executed at least once after that the condition will tested. If the condition is
satisfied than repeat the statement otherwise not.
Syntax:-
Initialization
do
{
// body of the loop
}
while (test condition)
temp = a;
a = b;
b = temp + b;
Console.WriteLine(temp);
i++;
}
while (i <= 15);
Console.ReadLine();
}
}
}
51
The for Loop
A for loop works like a while loop, except that the syntax of the for loop includes initialization
and condition modification. for loops are appropriate when you know exactly how many times
you want to perform the statements within the loop. The contents within the for loop parentheses
hold three sections separated by semicolons
using System;
class ForLoop
{
public static void Main()
{
for (int i = 0; i < 20; i++)
{
if (i == 10)
break;
if (i % 2 == 0)
continue;
52
The foreach loop
The last loop we will look at, is the foreach loop. It operates on collections of items, for
instance arrays or other built-in list types. In our example we will use one of the simple
lists, called an ArrayList. It works much like an array, but don't worry, we will look into
it in a later chapter.
LAB
using System;
class ForEachLoop
{
public static void Main()
{
string[] names = { "Cheryl", "Joe", "Matt", "Robert" };
53