ASPNET

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 54

Microsoft.

NET
Microsoft.NET is Microsoft ‘s new Internet strategy .
.NET was originally called NGWS-Next Generation Windows Services.
The Microsoft .NET strategy was presented by Microsoft in June 2000
.NET is Microsoft ‘s new Internet and Web strategy
.NET is NOT a new operating system
.NET is a new Internet and Web Based infrastructure
.NET delivers software as Web Services
.NET is a framework for universal services
.NET is a server centric computing model
.NET will run in any browser on any platform
.NET is based on the newest Web standards
Microsoft .NET is product suite that enables organizations to build smart, enterprise class web services.
.NET Standards
.NET is built on the following Internet standards
1.HTTP, the common protocol between Internet Applications
2.XML(Extensible Markup language), the format for exchanging data between Internet Applications.
3.SOAP, the standard format for requesting Web Services
Simple Object Access Protocol is an XML-based protocol used for messaging delivery, language independent
and platform independent. SOAP is remote procedure call over using HTTP using XML.
4.UDDI, the standard to search and discover and Integration to create third party web services Discovery
directory.
The .NET Framework
The .NET Framework is the infrastructure for the new Microsoft .NET Platform is an integral Windows
component that supports building and running the next generation of applications and XML Web services.
Microsoft .NET offers language-independence and language-interoperability.
This allows the developers to write their applications/programs in any of the .NET languages with which they
are most comfortable , i.e. a single .NET component can be written , for example , partially in VB.NET ,
the .NET version of Visual Basic , and C#.
How does this work ?
First source code is translated into Microsoft Intermediate Language(MSIL or IL). This IL code is language –
neutral and is analogous to Java byte code. The IL code needs to be interpreted and translated into a native
executable. The .NET Framework includes the Common Language Runtime(CLR), analogous to Java Runtime
Environment(JRE), which achieves this goal. The CLR is Microsoft’s intermediary between .NET developers’
source code and the underlying hardware and all .NET code ultimately runs within the CLR.
CLR is a runtime environment in which programs written in c# and other .NET languages are executed. It also
support cross-language interoperability.
The CLR provides many exciting features
Automatic garbage collection
Exception handling
Cross-language inheritance
Debugging
Side-by-side execution of different version of the same .NET component
Loading and execution of programs
Memory isolation for applications
Verification of type safety
Compilation of IL into native executable code
Providing meta data
Memory management
Enforcement of security
Interoperability with other systems
Common language runtime components
1. Common type system
2. Intermediate language
The .NET Framework objectives
1.To provide a consistent object-oriented programming environment whether object code is stored and
executed locally, executed locally but Internet-distributed, or executed remotely.
2.To provide a code-execution environment that minimizes software deployment and versioning conflicts
3.To provide a code-execution environment that promotes safe execution of code, including code creted by an
unknown or semi trusted third party.
4.To provide a code-execution environment that eliminates the performance problems of scripted or
interpreted environments.
5.To make the developer experience consistent across widely varying types of applications, such as Windows-
based applications and Web-based applications.
6.To build all communication on industry standards to ensure that code based on the .NET Framework can
integrate with any other code.
.NET Building Blocks
.NET Building Blocks is a set of core Internet Services.
Web Services
Web Services provide data and services to other applications via standard web format
(HTTP,HTML,XML,SOAP).
Standard Communication
Official Web standards(XML,UDDI,SOAP) will be used to describe what Internet data is , and to describe what
Web services can do.
Internet Storages
.NET offers secure and addressable places to store data and applications on the web allowing all types of
Internet devices to access data and applications. The web services are built on NTFS and SQL Server.
Internet Dynamic Delivery
Reliable automatic upgrades by demand and installation independent applications.
Internet Identity
.NET supports many different levels of authentication services like passwords, wallets and smart cards.
Internet Messaging
.NET supports integration of messaging, e-mail, voice-mail and fax into one unified Internet Service targeted
for all kinds of PCs or smart Internet devices.
Internet Calendar
.NET supports Internet integration of work, social and private home calendars. Allowing all types of Internet
devices to access the data.
Internet Directory Services
.NET supports a new kind of directory services that can answer XML based questions about the Internet
Services, far more exactly than search engines and yellow pages.
Principle Design Features
Interoperability
Because interaction between new and older applications is commonly required , the .NET framework provides
means to access functionality that is implemented in programs that execute outside the .NET environment.
Common Runtime Engine
All .NET programs execute under the supervision of the CLR, guaranteeing certain properties and behavior in
the areas of memory management, security and exception handling .
Language Independence
The .NET Framework introduces a common Type system . The CTS specification defines all possible data types
and programming constructs supported by the CLR.
Base class Library
The Base class library , part of the framework class library , provides classes which encapsulates a number of
common functions, including file reading and writing , graphic rendering, database interaction and XML
document manipulation.
Simplified Deployment
The .NET Frame work design and tools that help manage the installation of computer software to ensure that
is does not interfere with previously installed software.
Security
The design is meant to address such as buffer overflows, that have been exploited by malicious software.
Portability
The design of the .NET Framework is cross-platform compatible. That is, a program written to use the
framework should run without change on any type of system for which the framework is implemented.
Web services and the software strategy for implementing and delivering these services is .NET.
.NET is a software framework that includes everything required for developing software for web services.
It integrates presentation technologies, component technologies and data technologies on a single platform so
as to enable users to develop internet application as easily as they do on desktop systems.
Three generation of component model
Object linking & EmbeddingOLE TechnologyInter process communication
Component object modelCOM TechnologyInter module communication
.NET TechnologyInter Site communication
The Microsoft.NET software solution strategy includes three key approaches
1. Microsoft .NET platform
2. Microsoft.NET products & services
3. Third party .NET services
1.Microsoft.NET platform includes the following components
1. .NET infrastructure and tools
2. .NET user experience
3. .NET building blocks
4. .NET device software
.NET also includes several tangible products, such as compilers, class libraries and even whole end-user
application.
2.Microsoft .NET products and services consist of the following
1. Windows .NET
2. MSN .NET
3. Visual Studio .NET
4. Office .NET
5. Personal subscription services
6. bCentral for .NET
3. The visual studio.NET supports an integrated development environment (IDE) with a rich set of features and
productivity tools. These features and tools allow development to build web applications faster and easier.
Using web services and XML regardless of the language chosen for development there is now one
environment to learn, configure and use. We need not have to switch back and forth between environment to
build, debug and deploy our code.
VS.NET provides tools that extends support to the development lifecycle
Manage and collaborate
1. Planning
2. Analysis
3. Design
4. Development
5. Testing
6. Deployment
.NET languages
C#,C++,Visual Basic, Jscript
3.Third party .NET services will provide opportunities to a vast range of developers and users to produce
corporate and verified services using .NET platform.
Third party language
COBOL, Eiffel, Perl, Small TALK
1.1 .NET infrastructure and tools
1. Visual Studio .NET
2. Windows .NET
3. .NET experience services
4. .NET Framework
.Architecture of .NET Framework
1. ASP.NET(Web Services)
2. Windows Forms user interface
3. Frame Base classes
4. Common language Runtime

Common type system


The .NET framework provides multiple language support using the feature known as common type system
that is built into the CLR. The CTS supports a variety of types and operations found in most programming
languages and therefore calling one language from another does not require type conversion.
Common language specification
The common language specification defines a set of rules that enables interoperability on the .NET platform.
These rules serve as a given to third party compilers designers and library builders. The CLS is subset of CTS
and therefore the language supporting the CLS can use each other’s class libraries as if they are their own.
Application program interfaces(APIS) that are designed following the rules of LS can easily be used by all
the .NET language.
MSIL
An instruction set into which all the
.NET programs are compiled
It is a kin to assembly language and contains instruction for loading
Storing
Initializing
And calling methods
Source code is compiled into MSIL
Managed code
The code that satisfies the CLR at runtime in order to execute is referred to as managed code.
For example
C# compiler generate managed code
The managed code generated by C# is IL code.
The IL code is then converted to native machine code by the JIT compilers.
Flow chart of CLR activities for executing a program
C# Source code Program

Compilers

IL and metadata meta data engine

Linker other native code

Exe code

Class loader base class library

Verifier test for type safety

JIT compiler

Native machine code

Run time manager

Output
Framework base classes
.NET supplies a library of base classes that we can use to implement application quickly.
We can use them by simply instantiating them and invoking their methods or by inheriting them through
derived classes, thus extending their functionality.
Base frame classes resides in the namespace called system
Input/output operations managing errors and exceptions
String handling
Managing arrays , lists , maps etc. connecting to the internet
Accessing files and file system
Accessing the registry many more
Security
Windowing
Windows messages
Data base management
Evaluation of mathematical functions
Drawing
Benefits of the .NET approach
Simple and faster system development
Rich object model
Enhanced built in functionality
Many different ways to communicate outside world
Integration of different language into one platform
Easy deployment and execution
Wide range of scalability
Interoperability with existing application
Simple and easy to build sophisticated development tools
Fewer bugs
Potentially better performance
User and program interfaces
.NET framework provides the following tools for managing user and application interfaces
1. Windows forms
2. Web Form
3. Console application
4. Web services
Common programming model
Client side Server side
Win forms ASP.NET web forms
Win forms control Web forms control
Web services
BASE CLASS LIBRARY
Networking Web protocols
Threading FTP/SMTP/TCP/IP
The .NET framework
The .NET platform provides a new environment for creating and running robust, scalable and distributed
applications over the web.
Key features of the .NET framework
.NET platform
.NET infrastructure and tools
.NET framework
Visual studio.net
ASP.NET
The .NET framework provides an environment for building , deploying and running web services and other
application.
It consist of three distinct technologies
CLR
Frame base class
User and program interface(ASP.NET and Winform)
The CLR is the core of the .NET framework and is responsible for loading and running c# programs.
Base classes provides base data types, collection classes and general class for use by c# and .NET languages.
The top layer contains a set of classes for developing web services and to deal with the user interface.
Building block of .NET
1. C# , a new language
2. CLR
3. CLS
4. A rich set of language that target the CLR
5. Web services
6. Visual Studio.NET
Object Oriented Programming concept
Class as simply a type (just like char, int or long) that has methods associated with it.
Class is blueprint for an object.
Object: An object is an instance of a type or class.
Instantiation:- is simply the act of creating an instance of a class.
The instance is an object.
The three tenets of Object oriented programming
Encapsulation: Assigning an access modifier-public, private or protected to each class.
Abstraction: Declare class whose names and interface closely mimic real-world problem domain entities such
that using objects have a more natural feel of them.
Advantage –reusable software
Inheritance:-One class has a kind of relationship with another class.
The decoupling of user and implementation detail is what makes an entire system easier to understand and
therefore easier to maintain.
Two major types of Web Application
1.ASP.NET Web Site

Web forms let you create Web based application

That use standard HTML controls or new server controls that are handled on the web server. Server controls are
displayed using HTML, but execute code on the server.

Application example

Home page e-commerce

2.ASP.NET Web Services

ASP.NET WEB SERVICES made of code that can be called by other components on the internet or applications that use
IP. Using Web services you can send and process data using HTTP and XML messaging standards on the Internet.

Web services provide data and services to other applications. Future application will access Web Services via standard
Web formats (HTTP, HTML, XML, and SOAP), will no need to know how the Web Service itself is implemented. Web
Services are main building blocks in the Microsoft.Net programming model

Example:

Distributed database applications on the Internet

Check the data a user enters into a Web form using validation controls.

Application Example

Banking Applications

E-Commerce
Just-In-Time Compilation (JIT)

The MSIL is the language that all of the .NET languages compile down to. After they
are in this intermediate language, a process called Just-In-Time (JIT) compilation
occurs when resources are used from your application at runtime. JIT allows “parts”
of your application to execute when they are needed, which means that if something
is never needed, it will never compile down to the native code. By using the JIT, the
CLR can cache code that is used more than once and reuse it for subsequent calls,
without going through the compilation process again.
The figure below shows the JIT Compilation Process:
1. .NET Assembly
2. Class Loader
3. IL to PE Conversion
4.1 Assembly Resolver (1)
4.2 Managed code
5.CPU
6.Initial Method Call
7.Initial Reference to type(2)
DLL

DLLs gave developers the ability to create function libraries and programs that could
be shared with more than one application. Windows itself was based on DLLs. While
the advantages of shared code modules expanded developer opportunities, it also
introduced the problem of updates, revisions, and usage. If one program relied on a
specific version of a DLL, and another program upgraded that same DLL, the first
program quite often stopped working.

Microsoft added to the problem with upgrades of some system DLLs, like comctl.dll,
the library used to get file, font, color and printing dialog boxes. If things weren't
bad enough with version clashes, if you wanted to uninstall an application, you could
easily delete a DLL that was still being used by another program.
Recognizing the problem, Microsoft incorporated the ability to track usage of DLLs
with the Registry starting formally with Windows 95, and allowed only one version of
a DLL to run in memory at a time. Adding yet another complication, when a new
application was installed that used an existing DLL, it would increment a usage
counter. On uninstall, the counter would be decremented and if no application was
using the DLL, it could be deleted.

Solving DLL hell is one thing that the .NET Framework and the CLR targeted. Under
the .NET Framework, you can now have multiple versions of a DLL running
concurrently. This allows developers to ship a version that works with their program
and not worry about stepping on another program. The way .NET does this is to
discontinue using the registry to tie DLLs to applications and by introducing the
concept of an assembly.

On the .NET Platform, if you want to install an application in the clients place all you
have to do is use XCopy which copies all the necessary program files to a directory
on the client’s computer. And while uninstalling all you have to do is just delete the
directory containing the application and your application is uninstalled.
Metadata
An Assembly is a logical DLL and consists of one or more scripts, DLLs, or
executables, and a manifest (a collection of metadata in XML format describing how
assembly elements relate). Metadata stored within the Assembly, is Microsoft's
solution to the registry problem. On the .NET Platform programs are compiled into
.NET PE (Portable Executable) files.

Metadata is nothing but a description of every namespace, class, method,


property etc. contained within the PE file. Through Metadata you can discover all the
classes and their members contained within the PE file.

Metadata describes every type and member defined in your code in a Multilanguage
form. Metadata stores the following information:

Description of the assembly


o Identity (name, version, culture, public key).
o The types that are exported.
o Other assemblies that this assembly depends on.
o Security permissions needed to run

Description of types
o Name, visibility, base class, and interfaces implemented.
o Members (methods, fields, properties, events, nested types)
Attributes
o Additional descriptive elements that modify types and members
Assembly

In ASP.NET , the component is the DLL file that contains the application logic, and is known as the assembly.

Assemblies are the building blocks of .NET Framework applications; they form the
fundamental unit of deployment, version control, reuse, activation scoping, and
security permissions. An assembly is a collection of types and resources that are
built to work together and form a logical unit of functionality. An assembly provides
the common language runtime with the information it needs to be aware of type
implementations. To the runtime, a type does not exist outside the context of an
assembly.
An assembly does the following functions:
It contains the code that the runtime executes.
It forms a security boundary. An assembly is the unit at which permissions are
requested and granted.
It forms a type boundary. Every type’s identity includes the name of the
assembly at which it resides.
It forms a reference scope boundary. The assembly's manifest contains assembly
metadata that is used for resolving types and satisfying resource requests. It
specifies the types and resources that are exposed outside the assembly.
It forms a version boundary. The assembly is the smallest version able unit in the
common language runtime; all types and resources in the same assembly are
versioned as a unit.
It forms a deployment unit. When an application starts, only the assemblies the
application initially calls must be present. Other assemblies, such as localization
resources or assemblies containing utility classes, can be retrieved on demand.
This allows applications to be kept simple and thin when first downloaded.
It is a unit where side-by-side execution is supported.
Contents of an Assembly
Assembly Manifest
Assembly Name
Version Information
Types
Locale
Cryptographic Hash
Security Permissions

In general, if you have an application comprising of an assembly named Assem.exe


and a module named Mod.dll. Then the assembly manifest stored within the PE
Assem.exe will not only contain metadata about the classes, methods etc. contained
within the Assem.exe file but it will also contain references to the classes, methods
etc, exported in the Mod.dll file. While the module Mod.dll will only contain metadata
describing itself.
How to write first program in ASP.NET

Click all programs


Select Visual Studio
Select Visual Studio -2005
Select Create Web Site
Select Language VB or VC#
Select ASP.NET Web Site
Default.aspx web page will be displayed
Copy three textboxes tool to Web form
Copy two Labels to Web form
Copy one Button to Web form
Double click to button
Write code in case of VB
TextBox3.Text=Val(TextBox1.Text)+Val(TextBox2.Text)
Write code in case of VC#
Int i=int.Parse(TextBox1.Text);
Int j=int.Parse(TextBox2.Text);
Int sum=i+j;
Textbox3.Text=sum.ToString();

Debugg the program

Run
Input value in TextBox1 and TextBox2
click Button
See Result
Processing ASP.NET Applications

Any page ending in .aspx is directed to ASP.NET engine, which is located on the server in a file named aspnet_isapi.dll

Each Application directory in your Web application is compiled into a single file called an assembly.

The main directory and subdirectories are compiled into a single assembly named [Your_application_name].dll by
default.

You can also precompile code using the ASP.NET compiler tool (ASPNET_Compiler.exe), and place it in the bin
directory of your application, which frees you from having to store the source code files on the Web Server.

Then when you are ready to publish your site , you only have to deploy your ASP.NET and additional resource files,
configuration files, and dll files.

Steps in Web deployment

1. Web Developer deploy website at server

2. Pre-compile source code into MSIL in the project assembly at design time or dynamically at first run_time

3. Client browser requests homepage.aspx[Address: http://localhost:portnumber/website/homepage.aspx

4. JIT compiles assembly into matching specific code at run time. Only compiles the source file once.

ASSEMBLY/website1/bin/website1.dll

5.Web page sent to the browser

Two methods to connect to the web server and publish the web projects.

File share

Front page extension

If you select using a file system as the method to create and publish the application, you can use a simple File
Transfer Protocol program to copy the file to the server.
How to Install IIS on Windows XP and Windows 2000
Follow these steps to install IIS on Windows XP and Windows 2000:

1. On the Start menu, click Settings and select Control Panel


2. Double-click Add or Remove Programs
3. Click Add/Remove Windows Components
4. Click Internet Information Services (IIS)
5. Click Details
6. Select the check box for World Wide Web Service, and click OK
7. In Windows Component selection, click Next to install IIS

After you have installed IIS, make sure you install all patches for bugs and security problems. (Run Windows
Update).

Test Your Web


After you have installed IIS or PWS follow these steps:

1. Look for a new folder called Inetpub on your hard drive


2. Open the Inetpub folder, and find a folder named wwwroot
3. Create a new folder, like "MyWeb", under wwwroot
4. Write some ASP code and save the file as "test1.aspx" in the new folder
5. Make sure your Web server is running (see below)
6. Open your browser and type "http://localhost:portnumber/MyWeb/test1.asp", to view your first web
page

Note: Look for the IIS (or PWS) symbol in your start menu or task bar. The program has functions for starting
and stopping the web server, disable and enable ASP, and much more.

C:\Inetpub\wwwroot\MyWeb\test1.aspx

Or

Through browser

http://localhost:port number/MyWeb/test1.aspx
Visual Studio Internal Debugger :

We are all aware of that visual studio is having its own internal ASP.NET debug engine which is used to debug
our ASP.NET web application while we are developing it. The process which is used to debug the application
within visual studio is WebDev.WebServer.Exe . ASP.NET Engine uses WebDev.WebServer.exe to debug the
application. Now if you want to know more details about it please read this .

Fig: Block Diagram for Visual Studio Internal Debugger

Local IIS Debugging :

I am explaining the whole scenario using following diagram.


Fig: Block Diagram for Debugging ASP.NET site from Local IIS Server

In local IIS debugging, IIS should be installed in the local system where we have visual studio installed. For
debugging the application hosted on IIS from visual studio, we need to attach the worker process (w3wp.exe)
with in visual studio. After that we will able to start the debugging of the web application.

How to create a local IIS web site


A local IIS web site is a web site that resides on your local computer. To create a local IIS web site, then, you
must have IIS installed on your computer.

To start, you select HTTP for the location option in the New Web Site dialog box . Then, you typically click
the Browse button to display the Choose Location dialog box .

In the Choose Location dialog box, you can click the Local IIS button at the left side of the dialog box to
display the IIS web server. Then, you can select the directory where you want to create your web site. I selected
the ASPNET2005 directory. Then, I clicked the Create New Web Application button to create a new web site
named Su in that directory.

The files for the web site are stored within the directory you create. If that’s not what you want, you can create a
virtual directory that points to the directory where the files for the web site will be stored. To do that, just click
the Create New Virtual Directory button in the Choose Location dialog box. Then, a dialog box is displayed that
lets you enter a name for the virtual directory and the path where the files for the web site should be stored. In
the dialog box shown in this figure, for example, the virtual directory will be named Sut, and the files will be
stored in a directory with the same name within the ASP.NET 2.0 Web Sites directory on the C drive.

You can also use New virtual directory dialog box to create a virtual directory for a file-system web site you’ve
already created. To do that, just enter the path for the existing web site in this dialog box. Then, when you click
the OK button in the New Web Site dialog box, Visual Studio will warn you that there is already a web site at
the location you specified. To create a virtual directory that points to the existing web site, select the Open the
Existing Web Site option.

Before I go on, you should realize that you can also create a virtual directory for a file-system web site using the
IIS Management Console.

Description • To create a web site that will run under IIS on your local computer, select HTTP for the location
option in the New Web Site dialog box. Then, enter the path of the IIS directory where you want to create the
web site, or click the Browse button to display the Choose Location dialog box.

• From the Choose Location dialog box, click the Local IIS button and expand the Default Web Site node.
Then, select the directory where you want to create the web site from the default web site and click the Open
button, or create a new directory or virtual directory.

• To create a new IIS directory for a web site, click the Create New Web Application button and then enter the
name of the directory. The files for the web site will be stored in this directory.

• To create a virtual directory for the web site, click the Create New Virtual Directory button to display the New
Virtual Directory dialog box. Enter a name for the directory and the path where you want to store the files for
the web site. If the path you specify already contains a web site, you can open that web site from the virtual
directory.
Open command prompt from start option

1) To start world wide web services c:\>net start w3svc


2) To start the ftp service c:\>net start msftpsvc
3) To start the smtp service c:\>net start smtpsvc
4) To start the plesk control panel service c:\>net start PleskControlPanel
5) To start the HTTP SSL service c:\>net Start HTTPFilter
6) To restart IIS services c:\>iisreset /restart
7) To check the status of the IIS services c:\>iisreset /status

To stop the services use stop instead of start in the above 5 commands .

To Develop Web Application

1.Startup Visual Studio

2.Click Create New Web Site

3.Highlight Visual Basic/C# Project

4.Click ASP.NET Web Application in the Templates Window

5.Name of Project with WebSite

6.Address http://Server Name/WebSite/dafault.aspx

7.Rename Default.aspx to Login.aspx

8.Right-mouse click on the Login.aspx page change ser as start page from the content menu.

9.Press F5 to run.
http://localhost/CurrentTime.asp to display current time

To publish web site on Internet

Web site address is http://www.4GuysFromRolla.com/webtech/hosts.shtrail

The role of intellisense

Intellisense detects what you have typed and tries to predict what you type next. Intellisense detects built-in keywords
and properties, as well as third –party controls installed with your application.

Every day, the built-in web server will have a different port number following http://localhost

The internal web server can be referred to as the localhost

The web application includes all of the files and resources within the root folder.

Web Parts: Web Parts are a collection of controls. Web parts contain user controls and web controls. Within a web
form, you can load web parts dynamically. The web parts can be configured to allow the end user to control the display
layout dynamically and edit the content loaded on the page.

Web Portals: Web portals provide way that users can access other application through a single interface. The Web portal
may contain one or more Web parts.

A NOTE ON SYNTAX

<%@Page Language=”vb”%>

Auto Hide Property is a feature that allows you to store the window on the desktop as a tab.

Dock able Property: Allows windows to be moved to other location on the desktop and to be placed on top of one
another.

Floating property: Allows you to select the window and drag and drop it to any location on the desktop; the window
does not have to be placed on top of another window.

Tags for Headings: <h1></h1>

Tags for paragraphs:<p></p>

The blockquote tags<blockquote></blockquote> Indicating quotations

The span tags <span></span> and div tags <div></div> are container tags used to separate content into logical blocks.

Div tag will place a carriage return at the end of the content

The span tag formats the content within the current line.

<body></body> forward slash and angle brackets


<title></title>

<script>

<styl> FOR CSS

<meta> to force browser to identify keywords

<a></a> create hyper link to another document

The master page is used to provide hierarchical control of content , layout and design. The master page will contain one
or more ContentPlaceHolder contrls. ContentPlace Holder controls are used to identify locations where content may be
inserted in a content page.

Content pages contain content controls that map to the ContentPlace Holder controls. Content pages insert content only
within area defined by the ContentPlaceHolder controls of the master page.

A skin is a file that contains style and other properties that are used to format Web controls

A theme is a collections of skin files along with style sheet and image resources. The theme files are stored together
within named folder that is named after the theme.

A buffer is an area in memory on the server . As a request is processed the data generated from the response is stored in
the buffer.

AJAX(Asynchronous Java Script XML) is an architecture that allows the application to save a complete round trip to the
server on post back.

In the .NET Framework, classes are organized into logical hierarchical treelike structure groupings used to categorize the
base class types called namespaces, which are spilt across several physical files.

Namespaces are a hierarchical way to organize objects.

Post Back Process: When a user fills out a form and clicks the Submit button, the data is sent to Web server for
processing. If the user enters an invalid value, the form is redisplayed to the client. Such maintenance of information
across browser requests is known as maintain state.

You can turn the postback feature on or off by setting the EnableViewState property to true or false within the @Page
directive. The Page directive is located on the first line of every Web Form and used to modify the settings for the entire
page.

If you need to send information securely across the Internet , if you enable the Secure Socket Layer(SSL) protocol when
you request page using https:// instead of http://.

MessageBox.Show("Image does not exist in database.");

Uploading a file with the fileUpload Control

FileUpload1.PostedFile.SaveAs(“c:\\MyDocumets\\Vijay.jpg”);
Spam is unauthorized delivery of e-mail messages. The bulk of e-mail today on the internet is spam. Because there is
virtually no cost to deliver spam, it is commonly used as a marketing tool to attract customers. A vast amount of spam
also consists of proliferation of pornographic and illicit material, such as advertisement of drugs. Some spam poses as
legitimate e-mail and use hyperlinks to lure end users onto websites that downloaded viruses and steal information such
as passwords, bank account numbers and credit card information.

To Creating Directory

DirectoryInfo sd=new DirectoryInfo(“C:\\MyDocumets\\”);

Sd.CreateSubdirectory(“Test”);

To Delete Directory

DirectoryInfo sd=new DirectoryInfo(“C’\\MyDocuments\\Test”);

Sd.Delete();
Publishing a Web Application
Another way to deploy your web application from within Visual Studio is to use the Publish option, which is
accessible via the Build menu. The Publish option explicitly compiles the application and then copies all of the
necessary files up to the specified remote site. As we'll see shortly, the Publish option is more blunt than the
Copy Web Site tool. Whereas the Copy Web Site tool lets you examine the files on the local and remote sites
and permits you to upload or download individual files as needed, the Publish option deploys the entire web
application.

In addition to copying all of the needed files to the specified remote site, the Publish option also explicitly
compiles the application. Given that Web Application Projects need to be explicitly compiled it should come as
no surprise that the Publish option is available for Web Application Projects. What may be a bit surprising is
that the Publish option is also available for Web Site Projects. Web Site Projects can be explicitly compiled
through a process referred to as pre-compilation. This tutorial focuses on using the Publish option with Web
Application Projects; a future tutorial will explore pre-compilation, at which point we'll return to look at using
the Publish option with Web Site Projects.

Note: While the Publish option is available in Visual Studio for both Web Site Projects and Web Application
Projects, Visual Web Developer only offers the Publish option for Web Application Projects.

Let's look at deploying the Book Reviews application using the Publish option. Start by opening
BookReviewsWAP (the Web Application Project) in Visual Studio. From the Publish menu choose the Build
BookReviewsWAP project. This brings up a dialog box that prompts for the target location, among other
configuration options . Much like with the Copy Web Site tool you can enter a location that points to a local
folder, a local website on IIS, a remote website that supports FrontPage Server Extensions, or an FTP server
address. You can choose whether to replace the files on the remote web server with the deployed files or to
delete all of the content on the remote site before publishing. You can also specify whether to copy:

 Only the files in the project needed to run the application, which omits the unneeded source code and project-
related files.
 All project files, which includes the source code files and Visual Studio project files like the Solution file.

 All files in the source project folder, which copies all files in the source project folder regardless of whether
they're included in the project.

There's also an option to upload the contents of the App_Data folder.


Figure 6: Specify the Destination Website
Application configuration
A web application is a group of files and folders (including virtual folders) located under the web application’s root
directory. A web application is defined by the web server software. Internet information server (IIS) has the capacity to
define multiple web applications on the same computer. In IIS, the root directory of a web application may be
configured as a virtual web. A virtual web is web application that is stored outside of the C:\Inetpub\wwwroot folder. A
web application can be configured to include one or more virtual directories. A virtual directory is a directory stored
outside of the web application folder or the wwwroot folder.

The Application object stores the application variables in the server’s memory, and any user can access them from any
page within the web site. The application variables are released from memory only when the web application is stopped,
when the web server is stopped, or when the server is stopped.

The website could be configured locally using the MMC.

If you have Microsoft IIS installed and running, you can view the property sheets for the web server by completing the
following steps:

1. Click the start button and then open the Control panel

2. Double_click the administrative Tools icon. Double_click the IIS icons.

3. Double _click the computer name. Double_click Web sites.

4. Right_click Default web site, then click Properties. The Web site property sheets open.

The Web Site property sheet contains information that identifies the web site, such as the IP address and TCP port.
RequiredFieldValidator - Checks if the control is not empty when the form is submitted.

CompareValidator - Compares the value of one control to another using a comparison operator (equal,
less than, greater than etc).

RangeValidator - Checks whether a value falls within a given range of number, date or string.

RegularExpressionValidator - Confirms that the value of a control matches a pattern defined by a regular
expression. Eg: Email validation.

CustomValidator - Calls your own custom validation logic to perform validations that cannot be handled by
the built in validators.

ValidationSummary - Show a summary of errors raised by each control on the page on a specific spot or in
a message box.

What's New in 2.0


 Validation Groups - You can assign a group name to a set of validators to ensure that validation occurs only for
controls in the specified group. This enables you to have multiple control groups that are validated separately on
the same page.

 Set Focus on Error - Using the new Focus API feature in ASP.NET validators can be configured to set focus to
their associated control to be validated when a validation error occurs. The first control in the form that has a
validation error will receive default focus when the form is submitted.

 Culture Invariant Values - When doing conversion on a compare validator's non strongly-typed properties
(CompareValidator.ValueToCompare, RangeValidator.MaximumValue, RangeValidator.MinimumValue) the
validator will use a culture neutral format (Date: YYYY/MM/DD, Double & Currency: US culture format) to do the
conversion when CultureInvariantValues is true.

 Validate Empty Text - The ValidateEmptyText property fixes an issue with CustomValidator. In ASP.NET 1.0
custom validation would not fire if ValidationText was empty. You can set this property to true to cause custom
validation to occur for empty input values.

Some examples:
Working with CompareValidator

The CompareValidator server control compares the values of two controls. CompareValidator uses three key properties
to perform its validation. ControlToValidate and ControlToCompare contain the values to compare. Operator defines the
type of comparison to perform--for example, Equal or Not Equal. CompareValidator performs the validation by
evaluating these properties as an expression, as follows:

If the expression evaluates true, the validation result is valid. You can optionally specify the ValueToCompare property to
compare against a static value instead of ControlToCompare.
The CompareValidator server control could also be used to do Datatype validation.For example, if birth date information
has to be collected from a user registration page, CompareValidator control could be used to make sure that the date is
in a recognized format before it is submitted to the database.

Working with Regular Expressions

The RegularExpressionValidator server control checks that the entry matches a pattern defined by a regular expression.
This type of validation allows you to check for predictable sequences of characters, such as those in social security
numbers, e-mail addresses, telephone numbers, postal codes, and so on.

RegularExpressionValidator uses two key properties to perform its validation. ControlToValidate contains the value to
validate. ValidationExpression contains the regular expression to match.

Working with RangeValidator

The RangeValidator server control tests whether an input value falls within a given range. RangeValidator uses three key
properties to perform its validation. ControlToValidate contains the value to validate. MinimumValue and
MaximumValue define the minimum and maximum values of the valid range.
Steps to be followed

ASP:Text Box

Input type=”text” server controls

Add the required field validator

Go right next to form field textbox

Add on the Regular expression validator control.[By Dbl_Click validation control]

Go right next to the form field texture

The age regular expression validate contains a regular expression that ensures the entry is one, two or three digits.

The SSN Regular expression validate ensures that the SSN is in the format XXX-XX-XXX, where X is digit.

The Range validates ensures that the Age is between a 5 and 120(Value Range).

The maximum control and minimum control need to reference asp textbox controls with the minimum and maximum
range entered.

Add the Range validator to each from field.

The validator should go right next to the form field texture.

Two asp.TextBox controls visible property is set to false so they won’t show upon the web page. 5 and 120 have been
coded as the Min age and Max age control.

Page validator Will ensure the page to be reloaded when the user submit the form.

ASP.NET will automatically pass back the various form field elements through a post back form.

Special validator controls can be set up to validate a specific form field.

If all of the user’s entries are deemed valid by these form validators , the page is invalid property is set to True.

Validation controls are web controls that use the rules to validate the content of form fields. A rule can contain a variety
of requirements. For example, the rule may require that the controls contain any value or a specific form of data such as
alphabetical or numeric. The rule may also specify that data must be contained within range of two values. The rule may
be general, or it may be vary specific and required formatting such as uppercase letters and periods.

There are five built in validation controls and a control to display a summary of the validation errors. All five controls can
be added to your web page using the validation tab on the tool box or entering manually in the source code view of the
web page.

RequiredFieldvalidator –Make sure a form field is not left blank


The required FieldValidator control is used to determine whether the end users has entered or selected any value at all
The controlToValidate property specifies the Input Control to validate.

This control can combined with other controls. For Example, you can use it to detect whether an end user typed in
number for a credit card, but you would use the RegularExpressionValidator control to check whether the number is
actually a valid credit card numbers.

Range validator-Make sure a field’s value falls within given range

The RangeValidator control checks whether the value of an input control is within a specified range of values. You must
assign Minimum value and Maximum Value properties to specify the minimum and maximum values of the valid range.
Then, the value entered in the field is compared against these two values.

Compare validation-Compares a field‘s value with other value of other fields’ values

The Compare Validator control inherits the BaseCompareValidate class. This control compares the value entered by the
user into an Input control, such as a text box, with the value that is already contained in another Input control, or with a
constant value.

If you want to compare specific Input control with another Input control, set the ControlToCompare property to specify
the comparison control. If you want to compare the Input control with a constant value, you can specify the constant
value with the ValueToCompare property. You must specify the input control to validate by setting the
ControlToValidate property.

Regular Expression to represent a specific date format, but you could use the CompareValidator control to validate a
date. If you select date as the value for the Type property, and the DateTypeCheck for the Operator property, you can
allow the user to enter the date formatted as mm/dd/yyyy or mm/dd/yy using forward slashes or hyphens. The day or
month optionally can have a leading zero, but the month has to be between 1 and 12 the days have to be between 1 and
31.

Regular expression validator-evaluation data against a regular expression

A regular expression is a rule that describes values that are permitted or are not permitted. The Regular Expression is a
language that describes a pattern of one or more groups of characters. These characters can be alphanumeric or
symbols, such as the comma. There are several standards Regular Expression already built into VS.NET.

Social Security Numbers-^d{3}-\{2}-d{4}/

Internet E-Mail Address-\w+(-+.]\w+)*@\w+([-.)\w+)*\.\w+([-.]\w+)*

Internet URL-http://(\w-]+[\w-]+(/[\w-./?%&=]*)?

Phone Number-\d{3}-\d{2}-\d{4}

You can also create your own custom Regular Expression. The components of a Regular Expression can be individual
characters, set of characters, and range of characters, choice between characters, or any combination. You can construct
a custom Regular Expression by putting the various components of the pattern between delimiters. The back slash is
used to insert a pattern or rule into the expression.

Regular expression use characters such as d to represent single digit. The number of digits required is listed within curly
braces. Therefore, the Regular Expression \d{5} means that the value had to consist of 5 digits such as 12345. You can
use a vertical line to combine expression and parentheses to combine expression. So\d{5|6} would allow either a 5-or-6
digit number.

Lowercase; represent a rule that requires a single digit from 0 through 9 in that character

By inserting brackets and the range of digits allowed such as [0-9].

To set the rule not to allow a digit or space, you can use the caret to signify not to allow that character.

To not allow a single digit or space, you could use an uppercase D character or [^0-9].

In a regular expression the word characters are represented as a lowercase w or [A-Za-z-0-9]

You can be more specific and only require uppercase letters by using [A-Z-] or lowercase with [a-z].

To change the rule not to allow a word character, you could use the uppercase W, or the caret, as in [^A-Za-z_0-9].

The lowercase s represents a white space character, and the uppercase S represents a non-white space character.

A white space character consists of any of the special characters, such as \n that is used to insert a new line\t that is
used to insert a tab space, and \r that is used to insert a carriage return.

Quantifiers indicate how many characters this rule will apply to.

\d{5}, 5 would be the quantifier and there would be 5-digit characters required.

\[A-Za-z]{1,} could be used to require 1 alphabetical character at a minimum such as in a name.

There may be 4 to 6 numbers in a product model number. Rule would be \d{4, 6}.

Regular expression can be applied to many types of web applications. In an e-commerce application, you often need to
validate the shipping cart, order, shipping and payment data. Credit card numbers can be validated with regular
expressions.

The regular expression Validator control inherits from the BaseCompareValidator class. This control validates whether
the value of an input control matches a pattern defined by a Regular Expression. A Regular Expression can be used to
check for predictable sequences of characters, such as those in Social Security numbers, e-mail addresses, telephone
numbers and postal codes.

You can preview the Regular Expression selected in the Validation expression text box.

You still configure the ControlToValidate

You can enter the ValidationExpression manually or use the Regular Expression Editor.

The Regular Expression editor can be used to select a standard built-in expression

Custom validator-Evaluates data against custom criteria

Validation summary-Displays a summary of validation errors.

The ValidationSummary control is used to summarize the error messages from all validator controls on a web
page, In one location. The Validation Summary control has properties such as DisplayMode, ShowSummary,
ShowMessageBox and HeaderText
Why we use validation controls?

Validation is important part of any web application. User's input must always be validated before sending across different layers of the
application.

Validation controls are used to:

 Implement presentation logic.


 To validate user input data.

 Data format, data type and data range is used for validation.

Validation is of two types:


1. Client Side
2. Serve Side

Client side validation is good but we have to be dependent on browser and scripting language support.

Client side validation is considered convenient for users as they get instant feedback. The main advantage is that it prevents a page
from being postback to the server until the client validation is executed successfully.

For developer point of view serve side is preferable because it will not fail, it is not dependent on browser and scripting language.

You can use ASP.NET validation, which will ensure client, and server validation. It work on both end; first it will work on client
validation and than on server validation. At any cost server validation will work always whether client validation is executed or not.
So you have a safety of validation check.

For client script .NET used JavaScript. WebUIValidation.js file is used for client validation by .NET

Validation Controls in ASP.NET

An important aspect of creating ASP.NET Web pages for user input is to be able to check that the information users enter is valid.
ASP.NET provides a set of validation controls that provide an easy-to-use but powerful way to check for errors and, if necessary,
display messages to the user.

There are six types of validation controls in ASP.NET


1. RequiredFieldValidation Control
2. CompareValidator Control

3. RangeValidator Control

4. RegularExpressionValidator Control

5. CustomValidator Control

6. ValidationSummary
The below table describes the controls and their work:

Validation Control Description


RequiredFieldValidation Makes an input control a required field
CompareValidator Compares the value of one input control to the value of another input
control or to a fixed value
RangeValidator Checks that the user enters a value that falls between two values
RegularExpressionValidator Ensures that the value of an input control matches a specified pattern
CustomValidator Allows you to write a method to handle the validation of the value
entered
ValidationSummary Displays a report of all validation errors occurred in a Web page

All validation controls are rendered in form as <span> (label are referred as <span> on client by server)

Important points for validation controls


 ControlToValidate property is mandatory to all validate controls.
 One validation control will validate only one input control but multiple validate control can be assigned to a input control.

Validation Properties
Usually, Validation is invoked in response to user actions like clicking submit button or entering data. Suppose, you wish to perform
validation on page when user clicks submit button.

Server validation will only performed when CauseValidation is set to true.

When the value of the CausesValidation property is set to true, you can also use the ValidationGroup property to specify the name of
the validation group for which the Button control causes validation.

Page has a Validate() method. If it is true this methods is executed. Validate() executes each validation control.

To make this happen, simply set the CauseValidation property to true for submit button as shown below:

<asp:Button ID="Button2" runat="server" Text="Submit" CausesValidation=true />

Lets understand validation controls one by one with practical demonstration:

RequiredFieldValidation Control

The RequiredFieldValidator control is simple validation control, which checks to see if the data is entered for the input control. You
can have a RequiredFieldValidator control for each form element on which you wish to enforce Mandatory Field rule.

CompareValidator Control

The CompareValidator control allows you to make comparison to compare data entered in an input control with a constant value or a
value in a different control.

It can most commonly be used when you need to confirm password entered by the user at the registration time. The data is always
case sensitive.

RangeValidator Control

The RangeValidator Server Control is another validator control, which checks to see if a control value is within a valid range. The
attributes that are necessary to this control are: MaximumValue, MinimumValue, and Type.

RegularExpressionValidator Control

A regular expression is a powerful pattern matching language that can be used to identify simple and complex characters sequence that
would otherwise require writing code to perform.

Using RegularExpressionValidator server control, you can check a user's input based on a pattern that you define using a regular
expression.

It is used to validate complex expressions. These expressions can be phone number, email address, zip code and many more. Using
Regular Expression Validator is very simple. Simply set the ValidationExpression property to any type of expression you want and it
will validate it.

If you don't find your desired regular expression, you can create your custom one.

In the example I have checked the email id format:

The complete code for the above 4 controls is as:

Default.aspx Design
CustomValidator Control

You can solve your purpose with ASP.NET validation control. But if you still don't find solution you can create your own custom
validator control.

The CustomValidator Control can be used on client side and server side. JavaScript is used to do client validation and you can use any
.NET language to do server side validation.

I will explain you CustomValidator using server side. You should rely more on server side validation.

To write CustomValidator on server side you override ServerValidate event.

Code behind file

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page


{
protected void UserCustomValidate(object source, ServerValidateEventArgs args)
{
string str = args.Value;
args.IsValid = false;
//checking for input length greater than 6 and less than 25 characters
if (str.Length < 6 || str.Length > 25)
{
return;
}
//checking for a atleast a single capital letter
bool capital = false;

foreach (char ch in str)


{
if (ch >= 'A' && ch <= 'Z')
{
capital = true;
break;
}
}
if (!capital)
{
return;
}
//checking for a atleast a single lower letter
bool lower = false;
foreach (char ch in str)
{
if (ch >= 'a' && ch <= 'z')
{
lower = true;
break;
}
}
if (!lower)
{
return;
}
bool digit = false;
foreach (char ch in str)
{
if (ch >= '0' && ch <= '9')
{
digit = true;
break;
}
}
if (!digit)
{
return;
}
args.IsValid = true;
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
The server side validation you write does not need to provide the exact same validation as that of the client side validation. The
client side validation can check for the user input data for range and type and server side validation can check for matching of data
with database. Both server side and client side validation can be used for total solution.

Default.aspx Design

ValidationSummary

ASP.NET has provided an additional control that complements the validator controls.

The ValidationSummary control is reporting control, which is used by the other validation controls on a page.

You can use this validation control to consolidate errors reporting for all the validation errors that occur on a page instead of leaving
this up to each and every individual validation control.

The validation summary control will collect all the error messages of all the non-valid controls and put them in a tidy list.

Both ErrorMessage and Text properties are used to display error messages. Text error message have precedence.

If you are using ValidationSummary than only ErrorMessage and Text property is used.

The complete code for the above ValidationSummary is as:


Default.aspx Design
Output of ValidationSummary program
Creating Sql Database Connection in Asp.net Web Application Through C#

1: Open visual studio 2005 and from FILE select NEW-> WebSite, then from pop-menu select asp.net website
(Note: Language must be C#) , then press OK.

2: Now create three textboxes from the toolbox , to remove ambiguity I am using default name for that
textboxes and that should be textbox1,textbox2 & textbox3. And also drag & drop the button to the asp.net
application.

3: Meanwhile, Open SQL SERVER Management studio 2005 and open adventureworks(or you can create your
own database by the Sql command CREATE DATABASE database_name), but here I am using
AdventureWorks database.

4: Then create table by clicking right mouse button and form three column, Name them according to your
requirement , for your information only I used EID,name,Address. And click save button, then you’ll get a pop
up menu where you have to enter the Table Name, for this example I used students.

5: Now Come Back to Visual studio Application and write the following code in the button_click event

protected void Button1_Click(object sender, EventArgs e)


{
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = “Connection string(See Below for this — )COPY PASTE HERE“;

myConn.Open();
string strqry = “Insert into students values (” + TextBox1.Text +
“,’” + TextBox2.Text + “‘,’” + TextBox3.Text + “‘)”;

SqlCommand myCom = new SqlCommand(strqry, myConn);


int numrow = myCom.ExecuteNonQuery();
myConn.Close();

Kindly note down the connectionString Syntax, to obtain this string do the following steps :
Step 1 : Go to toolbox and from data section drag & drop SqlDataSource.
Step 2: Then on left clicking the mouse on SqlDataSource , you will get configureDataSource link, Select this.
Step 3: NewConnection String -> Provide Server Name then select or write database name , i.e.
AdventureWorks.[HCL,Other,.Net SQL Data Adapter]
Step 4: TestConnection and then Press OK.
Step 5 : Now you will again redirect to the page that you actually see in the step 2, but this time click + sign
before the connection string and from the drop drown hierarchy you will receive the connection string.
Step 6: Just copy and paste this string to the place of connectionstring.
1.Data Binding
The Binding class represents the simple binding between the property value of on object(Data Base) and
the property value of a control.[Grid]
Binding Data to Controls by Using the IDE
Add a GridView control to the Form
SqlDataSource properties
Connection String
Provider Name: The database type
GridView properties
Columns:The set of columns to be shown in the control
DataSourceId:The control ID of a Data source

2.Data Set
Read/Write access
Includes multiple tables from different databases
Disconnected
Bind to multiple controls
Forward and backward scanning of data
Slower access
Creating a Data set
DataSet mydataset=new DataSets();

3.Data adapter is the object that connects to the database to fill data set. It connects to the database to
update the data.
Filling the Data Set
myDataAdaper1.Fill(ds);
myDataAdapter2.Fill(ds);

4.Data Reader: Which provides a bridge to retrieve and save data between a Data Set and its source Data
Store.
Read-only
Based on one SQL statement from one database
Bind to one control only
Forward-only
Faster access

ExecuteReader:Returns a DataReader object


ExecuteScalar:Returns a single scalar value object
ExecuteNonQuery:Executes a command that does not return any rows.

SqlDataAdapter dataAdapter = new SqlDataAdapter ("SELECT userId,username FROM users ORDER


BY username", sqlConn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataSet dataSet = new DataSet();
dataAdapter.Fill (dataSet,"users");
myDataGrid.DataSource = dataSet.Tables[0];

Then, when we've finished making our changes to the DataSet via the DataGrid, we call

dataAdapter.Update(dataSet);
foreach(DataRow dataRow in dataSet.Tables["users"].Rows)

{
Response.Write(dataRow["username"] + "(" + dataRow["userid"] + ")");
}

 DataView dataView = dataSet.Tables["users"].DefaultView;


dataView.RowFilter = "username like 'Bob%'";
dataView.Sort = "dateJoined DESC";

myDataGrid.DataSource = dataView;

//myDataGrid.DataBind();

 {

 using (SqlCommand command = connection.GetCommand("SELECT textBox1 =
@textBox1 FROM dbo.table1 WHERE textBox2 = @textBox2", CommandType.Text))
 {

 command.AddParameter("@textBox1", TextBox1.Text,
SqlDbType.VarChar);
 command.AddParameter("@textBox2", TextBox2.Text,
SqlDbType.VarChar);


 using (SqlDataReader reader = command.ExecuteReader())
 {

 if (!reader.HasRows)
 {
 reader.Close();
 command.CommandText = "INSERT INTO dbo.table1 (textBox1,
textBox2) VALUES (@textBox1, @textBox2)";
 command.ExecuteNonQuery();
 }
 }
 }


 using (SqlCommand command = connection.GetCommand("SELECT * FROM
dbo.table1 WHERE textBox1 = @textBox1", CommandType.Text))
 {

 command.AddParameter("@textBox1", TextBox1.Text,
SqlDbType.VarChar);


 using (SqlDataReader reader = command.ExecuteReader())
 {
 Label1.Text = convert.ToString(reader["textBox2"]);
 }
 }
 }
 }
 }

myGridView.DataSource = dtReader;
myGridView.DataBind();
ASP.NET Image Control

The Image control is used to display an image.

Properties
Property Description .NET

AlternateText An alternate text for the image 1.0

DescriptionUrl The location to a detailed description for the image 2.0

Specifies whether or not the control creates an empty string as an alternate


GenerateEmptyAlternateText 2.0
text

ImageAlign Specifies the alignment of the image 1.0

ImageUrl The URL of the image to display for the link 1.0

runat Specifies that the control is a server control. Must be set to "server"

Image1.ImageUrl = Server.MapPath("img/85.jpg")

Path of the file=”C:\\Directory\\Filename.txt”;


To display Rollno and Name

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page

{ protected void Page_Load(object sender, EventArgs e)

protected void Button1_Click(object sender, EventArgs e)

SqlConnection Myconn = new SqlConnection();

Myconn.ConnectionString = "Data Source=HCL;Initial Catalog=Test;Integrated Security=True";

Myconn.Open();

String strcopy = "Select * From Student";

SqlDataAdapter da = new SqlDataAdapter(strcopy,Myconn);

DataSet ds = new DataSet();

da.Fill(ds, "student");

Response.Write("Sr.No. RollNo Name");

Response.Write("<br>");

int i = 1;

foreach (DataRow dataRow in ds.Tables["student"].Rows)

{ Response.Write(i);

Response.Write(dataRow["Rollno"] + " , " + dataRow["Name"] );

Response.Write("<br>");

i = i + 1;

da.Dispose();
Myconn.Close();

To insert Rollno and Name in the database

protected void Button2_Click(object sender, EventArgs e)

SqlConnection Myconn = new SqlConnection();

Myconn.ConnectionString = "Data Source=HCL;Initial Catalog=Test;Integrated Security=True";

Myconn.Open();

String strcopy = "Insert into student values('" + TextBox1.Text + "','" + TextBox2.Text + "')";

SqlCommand MyCom = new SqlCommand(strcopy, Myconn);

int numrow = MyCom.ExecuteNonQuery();

Myconn.Close();

Response.Redirect("http://localhost:1345/WebSite4/t1.aspx");

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)

To delete record

protected void Button4_Click(object sender, EventArgs e)

SqlConnection Myconn = new SqlConnection();

Myconn.ConnectionString = "Data Source=HCL;Initial Catalog=Test;Integrated Security=True";

Myconn.Open();

String strcopy = "Delete FROM student ";

SqlCommand MyCom = new SqlCommand(strcopy, Myconn);

MyCom.ExecuteNonQuery();
Myconn.Close();
}
To display Name

protected void Button3_Click(object sender, EventArgs e)

{ SqlConnection Myconn = new SqlConnection();

Myconn.ConnectionString = "Data Source=HCL;Initial Catalog=Test;Integrated Security=True";

Myconn.Open();

String strcopy = "SELECT Name from student";

SqlCommand MyCom = new SqlCommand(strcopy, Myconn);

SqlDataReader dr=MyCom.ExecuteReader();

String Mycat=" ";

while (dr.Read())

Mycat=Mycat+dr["Name"];

Label3.Text=Mycat;

Myconn.Close(); }

To insert Rollno and Name from Textbox1,Textbox2

protected void Button5_Click(object sender, EventArgs e)

SqlConnection Myconn = new SqlConnection();

Myconn.ConnectionString = "Data Source=HCL;Initial Catalog=Test;Integrated Security=True";

Myconn.Open();

String strcopy = "INSERT INTO student(RollNo,Name) Values(@TextBox1.Text,@TextBox2.Text)";

SqlCommand MyCom = new SqlCommand(strcopy, Myconn);

MyCom.Parameters.Add("@RollNo",SqlDbType.VarChar).Value="'+TextBox1.Text'";

MyCom.Parameters.Add("@Name", SqlDbType.VarChar) .Value="'+TextBox2.Text'";


Myconn.Close();
Response.Write("Your Record is updated"); }}
Save and Retrieve Images from the Database using ASP.NET 2.0
and ASP.NET 3.5
What if we have to show an online form, with the person’s details and his photo along with it, or for that
case, display the image in an ASP.NET server control along with other controls?

Let us start off by first creating a sample database and adding a table to it. We will call the database
‘Employee’ and the table will be called ‘EmpDetails’. This table will contain an image column along with
some other columns. Run the following script in your SQL 2005 Query window (or server explorer) to
construct the database and the table.

Database Script

CREATE DATABASE [Employee]


GO
USE [Employee]
GO
CREATE TABLE EmpDetails
(
empid int IDENTITY NOT NULL,
empname varchar(20),
empimg image
)

Step 1: Create a new asp.net website. In the code-behind, add the following namespace

C#

using System.Data.SqlClient;

Step 2: Drag and drop two label and one textbox control. Also drag drop a FileUpload control and a button
control to upload the selected image on button click. As mentioned earlier, there are no validations
performed. The source would look similar to the following:

Step 3: In the button click event, add the following code:

C#

protected void btnSubmit_Click(object sender, EventArgs e)


{
SqlConnection connection = null;
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the employee name and image into db
string conn = ConfigurationManager.ConnectionStrings
["EmployeeConnString"].ConnectionString;
connection = new SqlConnection(conn);
connection.Open();
string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT
@@IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("@eimg", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", id);
}
catch
{
lblResult.Text = "There was an error";
}
finally
{
connection.Close();
}
}
In the code above, we are creating a byte array equal to the length of the file. The byte array will store
the image. We then load the image data into the array. The record containing the Employee Name and
Image is then inserted into the database using the ADO.NET code. The ID inserted is returned back using
the @@Identity. We will shortly use this ID and pass it as a query string parameter to the ShowImage
handler. The image will then be fetched against the EmployeeID (empid).

Step 4: In order to display the image on the page, we will create an Http handler. To do so, right click
project > Add New Item > Generic Handler > ShowImage.ashx. The code shown below, uses the
Request.QueryString[“id”] to retrieve the EmployeeID from it. The ID is then passed to the
‘ShowEmpImage()’ method where the image is fetched from the database and returned in a
MemoryStream object. We then read the stream into a byte array. Using the OutputStream.Write(), we
write the sequence of bytes to the current stream and you get to see your image.

C#

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class ShowImage : IHttpHandler


{
public void ProcessRequest(HttpContext context)
{
Int32 empno;
if (context.Request.QueryString["id"] != null)
empno = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");

context.Response.ContentType = "image/jpeg";
Stream strm = ShowEmpImage(empno);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);

while (byteSeq > 0)


{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}

public Stream ShowEmpImage(int empno)


{
string conn = ConfigurationManager.ConnectionStrings
["EmployeeConnString"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT empimg FROM EmpDetails WHERE empid = @ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", empno);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}

public bool IsReusable


{
get
{
return false;
}
}

Step 5: One final step. Add the following code in the button click (just above the catch block) to call the
handler and display the newly inserted image from the database. In the code below, we pass the
EmployeeID as a query string parameter to the Http Handler.

C#

// Display the image from the database


Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;

That’s it. Run the code and check out the functionality. Just change the connection string in the web.config
to point to your database. The code works fine for .jpg, .gif and .bmp images. I would encourage you to
extend the sample and include validations in it. Some validations could be to check the size of the image
uploaded, make sure that only images are uploaded, check the length of the Employee name, prevent the
user from entering numeric and special characters, so on and so forth.
private void cmdSave_Click(object sender, EventArgs e)
03.{
04. try
05. {
06. //Read Image Bytes into a byte array
07. byte[] imageData = ReadFile(txtImagePath.Text);
08.
09. //Initialize SQL Server Connection
10. SqlConnection CN = new SqlConnection(txtConnectionString.Text);
11.
12. //Set insert query
13. string qry = "insert into ImagesStore (OriginalPath,ImageData) _
14. values(@OriginalPath, @ImageData)";
15.
16. //Initialize SqlCommand object for insert.
17. SqlCommand SqlCom = new SqlCommand(qry, CN);
18.
19. //We are passing Original Image Path and
20. //Image byte data as sql parameters.
21. SqlCom.Parameters.Add(new SqlParameter("@OriginalPath",
22. (object)txtImagePath.Text));
23.
24. SqlCom.Parameters.Add(new SqlParameter("@ImageData",
25. (object)imageData));
26.
27. //Open connection and execute insert query.
28. CN.Open();
29. SqlCom.ExecuteNonQuery();
30. CN.Close();
31.
32. //Close form and return to list or images.
33. this.Close();
34. }
To insert image in the database
protected void Button5_Click1(object sender, EventArgs e)
{ SqlConnection Myconn = new SqlConnection();

Myconn.ConnectionString = "Data Source=HCL;Initial Catalog=image;Integrated Security=True";

Myconn.Open();

byte[] imagebyte=File.ReadAllBytes("C:\\Inetpub\\wwwroot\\WebSite7\\Sunset.jpg");

String strcopy = "INSERT INTO ima Values(@img)";

SqlCommand MyCom = new SqlCommand(strcopy, Myconn);

MyCom.Parameters.AddWithValue("@img", imagebyte);

MyCom.ExecuteNonQuery();

Myconn.Close();

Response.Write("Your Image is saved");

}}

Full page image display

protected void Button6_Click(object sender, EventArgs e)

SqlConnection Myconn = new SqlConnection();

Myconn.ConnectionString = "Data Source=HCL;Initial Catalog=image;Integrated Security=True";

Myconn.Open();

String strcopy = "SELECT Image FROM ima";

SqlCommand MyCom = new SqlCommand(strcopy, Myconn);

SqlDataReader dr = MyCom.ExecuteReader();

dr.Read();

Response.BinaryWrite((byte[]) dr["Image"]);

Myconn.Close();

Response.Write("Your Image Displayed");


}}

To display image in image box

1. Add a new GENERIC HANDLER (ImageDisplay.ashx) to the project.


2. Set the ImageControl's ImageUrl to this ashx page.

imgDisplay.ImageUrl = "ImageDisplay.ashx?imageId=1";

where imageId is the Database ID of the image that needs to be fetched.


3. Now write code to fetch data from Database for that imageId in the ProcessRequest event of the ashx page.

public void ProcessRequest(HttpContext context)


{
Int32 imageId = Convert.ToInt32(context.Request.QueryString["imageId"]);

// This is the function that returns the Byte Array from the Database
Byte[] pict = GetImageById(imageId);
context.Response.ContentType = "image/bmp";
context.Response.OutputStream.Write(pict, 0, pict.Length);
}

4. The method GetImageById would depend upon the Database and data-type that you have for the
column for image. Since I had a MySQL database with BLOB column, which can hold a Byte[], the method
was quite simple for me and I just had to pull it out from Database and insert it into a Byte[] object.

code in Generic Handler

public void ProcessRequest (HttpContext context) {

SqlConnection Myconn = new SqlConnection();

Myconn.ConnectionString = "Data Source=HCL;Initial Catalog=image;Integrated Security=True";

Myconn.Open();

String strcopy = "SELECT Image FROM ima";

SqlCommand MyCom = new SqlCommand(strcopy, Myconn);

Byte[] pict = (Byte[])MyCom.ExecuteScalar();

context.Response.ContentType = "image/bmp";

context.Response.OutputStream.Write(pict, 0, pict.Length);

Myconn.Close();
Code in button

Image2.ImageUrl = "http://localhost:1345/WebSite4/Display.ashx";

Response.Write("Your Image Displayed");

SqlConnection Myconn = new SqlConnection();

Myconn.ConnectionString = "Data Source=HCL;Initial Catalog=Test;Integrated Security=True";

Myconn.Open();

String RollNo = TextBox1.Text;

String strcopy = "SELECT Name from student WHERE RollNo=RollNo";

SqlCommand MyCom = new SqlCommand(strcopy, Myconn);

SqlDataReader dr = MyCom.ExecuteReader();

String Mycat = " ";

dr.Read();

Mycat = Mycat + dr["Name"];

TextBox1.Text=RollNo;

TextBox2.Text = Mycat;

Myconn.Close();
Data Types for SQL Server
Real

Datetime

Character/Strings :Char,varchar,text

Binary strings: varbinary

Sql Command
SELECT * FROM Products

SELECT DISTINCT Manufacturers FROM Products

SELECT TOP(50) PERCENT * FROM Products

SELECT TOP(100) PERCENT Products, CategoryID, ModelName, Manufacturer FROM dbo.Products WHERE
(Manufacturer=N’Waterford’)

ORDER BY ModelName

WHERE [expression1][comparisonoperator][expression2]

WHERE User=’George’ AND Password=’Thunderbowl’

WHERE state=’CA’ OR state=’TX’ AND People>=1000

WHERE LastVisit>#12/31/2009# OR Member=’New’

WHERE Member=’Staff’ AND Salary>55000

WHERE Birth=IS NULL OR Email=IS NULL

SELECT * FROM Products GROUP BY CategoryID

SELECT CategoryName FROM Categories ORDER BY CategoryName ASC

INSERT INTO Products VALUES (‘chair’,153.29,#12/1/2009#,NULL,’furniture’)

INSERT INTO Products(name,price) VALUES (‘chair’,153.29)


SQL=”UPDATE Products SET” & “ProductName=’Claddagh’ ,”& “UnitCost=25.45 WHERE ProductID=353”

SQL=”DELETE FROM Products” & “WHERE ProductsID=”& MyProductID

To upload file

protected void Button8_Click(object sender, EventArgs e)

FileUpload1.PostedFile.SaveAs("C:\\Documents and Settings\\vijay\\My Documents\\Visual Studio 2005\\


WebSites\\WebSite4\\photo.jpg");

Response.Write("File uploaded");

protected void Button9_Click(object sender, EventArgs e)

String fn = FileUpload1.PostedFile.FileName;

FileInfo fa = new FileInfo(fn);

string fd = fa.DirectoryName;

string fe = fa.Extension;

string fn1 = fa.Name;

int a = fn1.Length;

string fname = fn1.Remove(a - 4);

Response.Write("Directory Name : ");

Response.Write(fd);

Response.Write("<BR>");

Response.Write("File Name : ");

Response.Write(fname);

Response.Write("<BR>");

Response.Write("File Extension : ");

Response.Write(fe);

Response.Write("<BR>");

Response.Write("Full File Name : ");

Response.Write(fn1);
}

To create Directory

protected void Button10_Click(object sender, EventArgs e)

DirectoryInfo dd = new DirectoryInfo(TextBox4.Text); D:\

dd.CreateSubdirectory(TextBox5.Text); Test

Response.Write("Directory created");

To Delete Directory

protected void Button11_Click(object sender, EventArgs e)

DirectoryInfo dd = new DirectoryInfo(TextBox4.Text); D:\Test

dd.Delete();

Response.Write("Directory Deleted");

You might also like