You are on page 1of 70

ASP.

NET

 Introduction to ASP.NET
 ASP stands for Active Server Page.
 ASP.Net is the Server side scripting language.
 ASP.Net application running under the IIS ( Internet Information Service )
 It’s a set of technologies in the Microsoft .NET framework for building web applications
and XML web services.
 ASP.NET page execute on the server and generate markup(HTML, XHTML,XML) that is
sent to desktop or mobile browser.
 ASP.NET pages use a compiled, event-driven programming model that improves
performance and enables the separation of application logic and user interface.
 ASP.NET pages and XML web services files created using ASP.NET contain server-side
(rather than client – side) logic written in visual basic, c# or any .NET compatible language.
 Web application and XML web services take an advantage of the features of the common
language runtime, such as type safety, inheritance, language interoperability, versioning
and integrated security.

 New to ASP.NET 2.0

1. Master Pages
 Master page enable you to create a “master” design of the look and feel of your web site.
 By using master pages, you can ensure visual consistency of your web pages and editing
the master will automatically update pages using the edited master page design.
 Your web application can have several master pages, each controlling different sets of
pages and you can even have nested master pages.

2. Personalization
 Personalization has become an essential part of modern web sites. This may involve
different color scheme, taking into account time zone in date stamps, or just greeting user
by name.
 Rather than writing complex code to support this manually, you can take advantage of the
new personalization support in ASP.NET 2.0

3. Localization
 Multi language support.
 The process of customize or translating the separated data and resources needed for a
specific region or language.

4. Globalization
 Globalization is the process of designing and developing web application that can adapt to
different language and culture.

5. Themes & Skin


 A theme can then be applied to any site to affect the look and feel of pages and controls
within the site.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 Style changes to a site can then be easily maintained by making changes to the theme,
without having to edit the individual pages in your site.
 Themes are made of a set of element : skin, css and images.
 Advantage of ASP.NET
1. Separation of code from HTML

 To make a clean sweep, with ASP.NET you have the ability to completely separate layout
and business logic.
 This makes it much easier for teams of programmers and designers to collaborate
efficiently.

2. Complete Object Oriented

 It supports completely object oriented support which includes an event driven architecture.

3. State management
 ASP.Net provides application state management.
 State information, e.g. for to keep the information in memory or stored in db.

4. Support of compile language

 Developer can use C#.net and access features such as strong typing and object oriented.
 Using compile languages also means that ASP.NET pages do not suffer the performance
penalties associated with interpreted code.
 ASP.Net pages are precompiled to byte code and just in time(JIT) compiled when first
requested. Subsequent requests are directed to the fully compiled code, which is cached
until the source changes.

5. Graphics IDE

 Visual studio .NET provides a very rich development environment for web developers.
You can drag and drop control and set the properties.

6. Update the file while running server

 Component of your application can be updated while the server in online or client
connected.

7. XML Based config. Files

 Configuration settings in ASP.NET are stored in XML files that you can easily read and
edit.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 You can also easily copy these to another server, along with the other files that comprise
your application.

8. Security

 With built in windows authentication and pre-application config., you can be assured that
your application is secure.
 Features of .NET

1. Rich set of Classes


 In C and C++ programs uses header file like “stdio.h”,”conio.h” etc.
 Visual studio .net contain hundreds of classes and namespace for provide variety of
functionality in your application.
 E.g. for, to work with database in.net we have to include System.Data namespace file

2. Object Oriented programming system

 Vs.net provide a fully object oriented environment.


 Vs.net is supports OOPs concepts

3. In-built memory management

 Developer always worry for system resources like memory.


 Vs.net supports handling memory on its own.
 The garbage collector takes responsibility for free up unused objects for regular intervals.

4. Multi-language and multi-device support

 Vs.net support multiple language.


 This means if your skill in C++ then you can use C++, and if your skill in VB then you can
work using vb language too..
 The beauty of multi language support lies in the fact that even though the syntax of each
language is different, the basic environment of developing software is same.
 Vs.net supports multi-device.
 We can create mobile, barcode reader device supported software.

5. Faster and easy development of web applications

 Asp.net is useful for developing dynamic and database related web applications.
 It contains rich and faster development controls for web.

6. XML support

 Vs.net supports for writing, manipulation and transforming XML docs.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

7. Ease of deployment and configuration

 Deploying windows applications especially that used COM component were always been
a tedious task.
 .net provide simply way to deploy and config. Application.

And many more feature like Boolean conditions, automatic garbage collection, standard
library, properties and events etc.

 Essential Parts of Website

There are four parts basically.


1) HTML ( XHTML)

 It’s a markup language to design the application.


 HTML stands for Hypertext Markup Language
 HTML has predefine tag to design web page.
 It’s a type of computer language that is primarily used for files that are posted on the
internet and viewed by web browsers.
 Browser can understand only one language called HTML.
 We can create static pages with extension either .HTML or .HTM

2) CSS
 A Cascading Style Sheet(CSS) contains style rules that are applied to elements in a web
page.
 Css is a style sheet used to describe the presentation of a document written in a markup
language. CSS can be used to determine an element size, color, position etc.
 It’s a separation of document content from document presentation.
 Instead of assigning attributes to each element on your page individually, you can create a
general rule that applies attributes whenever a web browser encounters an instance of an
element or an element that is assigned to a certain style sheet.
 CSS style can be placed inline within HTML code or group in style at head section or as a
separate style sheet.
 When using CSS, you are defining how to display each element of the page.

3) Client and Server Side Code


 With Client – Side scripting, the script on the page are processed by the individual web
browser that requests the page.
 With server – Side scripting, on the other hand,. All scripts are processed on the server
before the requested page is ever sent to the browser.
 The biggest limitation of HTML is that it’s static.
 Client side coding is interpreted by browser and run on the client machine and do not have
an access to server machine.
 We have two option to work with client script i.e. VBScript & JAVAScript.
 Client side scripting executes in the browser after the page is loaded.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 By default any browser accept javascript as client side scripting but if we have to use
vbscript then we have to define it at script tag.
 For, Server side scripting we can use PHP, ASP,JSP etc.

4) Database
 Now – a – days, most of all the website has their own database to store an information.
 Most of the ASP.NET works with SQL Server Databse.

 Introduction to Visual Web Developer ( IDE – Integrated Development


Environment)

 IDE stands for INTEGRATED DEVELOPMENT ENVIRONMENT


 Visual studio .NET is complete package of development tools for developing web
application, desktop application, mobile application etc.
 The IDE provides you with a centralized location for designing the user interface for the
application, writing code and compiling and debugging the application
 For developing any type of software in .net we have to select language.
 VS.NET support more than 20 Language for developing software. Some common language
are Visual Basic .NET, Visual C++ .NET, Visual C# .NET, and Visual J%. NET
 Some common types of project that we can develop in Visual Studio .NET are as below.

1. Windows form based applications.


2. ASP.NET web applications
3. Console based applications.
4. Smart device applications( MOBILE )
5. Class libraries
6. Web or windows custom controls
7. Web services

 To organize various items of an application efficiently, Visual Studio .Net has provided
two types of containers: Projects and Solutions.
 A project typically contains items that are interrelated. It allows you to manage, build and
debug the items that make up the application.
 A solution usually acts as a container for one or more projects. It allows you to work on
multiple projects within the same instance of Visual Studio .Net IDE. A solution also
allows you to specify the setting and options that apply to multiple projects.

❖ Version History

Version & Framework Used Release Date Visual Studio


Visual Studio 1.0 13/02/2002 Visual Studio .Net
Visual Studio 1.1 24/04/2003 Visual Studio .Net 2003
Visual Studio 2.0, 3.0 07/11 /2005 Visual Studio .Net 2005
Visual Studio 2.0, 3.0, 3.5 19/11/2007 Visual Studio .Net 2008

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

Visual Studio 2.0, 3.0, 3.5, 4.0 12/04/2010 Visual Studio .Net 2010
Visual Studio 2.0, 3.0, 3.5, 4.0, 12/09/2012 Visual Studio .Net 2012
4.5, 4.5.1, 4.5.2
Visual Studio 2.0, 3.0, 3.5, 4.0, 17/10/2013 Visual Studio .Net 2013
4.5, 4.5.1, 4.5.2
Visual Studio 2.0, 3.0, 3.5, 4.0, Summar/Autumn Visual Studio .Net 2015
4.5, 4.5.1, 4.5.2, 4.6 2015

❖ Screen Layout

❖ Parts Of IDE / Component Of IDE (INTEGRATED DEVELOPMENT


ENVIRONMENT)
1) Start page is a home page for Visual Studio .Net. Display Last website list and
given option for new / open website.

2) Projects and solutions explorer (Ctrl + Alt + L). Solution is a group of projects
and misc. files.

It will show us each items of our project files, forms, classes, namespace, database
etc. that we include in our solution

3) Menu bar : very common for any software. Contains option like file, edit, view,
project, build and help menus.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

4) Context Menu : it is very common for any software. It contain shortcut to


frequently performed actions.

To open context menu. Right click on any object. It will display the action regarding
the object.

5) Toolbox (Ctrl + Alt + X) : provides a set of control to place on a form

We can also set our own toolbox, by right click of it.

6) Toolbars : provide quick access to commonly used commands like save, undo,
comment, cut, copy, paste etc.

We can add other toolbars from view menu or right click on toolbar itself.

7) Properties Windows (F4) : It displays different properties of selected object.

8) Form Designer View (F7) : we can drag and drop controls in this view of the form

We can also see some type of preview of our form.

9) Code Editor Windows (F7) : where we can write coding of the form or class etc.

10) Task list window (Ctrl + Alt + K ) : it helps you create and manage a list of
programming tasks.

We can add user task, which are notes about work to be done. Task can be anything
like comments, reminders, URL etc.

Task list also display detected error.

11) Server explorer (Ctrl + Alt + S): Displays various database connections, services
and network related information.

12) Command Window ( Ctrl + Alt + A ) : we can execute both menu commands and
commands that do not appear on any menu.

The command window is used to execute commands or aliases.

 Different Types of File used in ASP.NET

Extension Web Page


.aspx Web Form
.master Master Page
.ascx Web user Control

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

.asmx Web Services


.aspx.vb( vb ) Code behind of Web Page
.ashx custom HTTP handlers
.axd when enabled in web.config requesting trace.axd outputs
application-level tracing. Also used for the special webresource.axd
handler which allows control/component developers to package a
component/control complete with images, script, css etc. for
deployment in a single file (an 'assembly')
.config web.config is the only file in a specific Web application to use this
extension by default (machine.config similarly affects the entire
Web server and all applications on it), however ASP.NET provides
facilities to create and consume other config files. These are stored
in XML format.
.skin themes skin files.
.sitemap sitemap configuration files. Default file name is web.sitemap
.resx resource files for internationalization and localization. Resource files
can be global (e.g. messages) or "local" which means specific for a
single aspx or ascx file.
.xsd DataSet
.disco Static Discovery File - An optional file that acts as a discovery
mechanism for the XML Web service. The .disco file is not
automatically created for an XML Web service. For information on
creating a discovery file for your XML Web service, see Enabling
Discovery for an XML Web Service.
.asax Global Application Class
 ASP.NET Page Cycle

 The life cycle starts when a user requests a web page through his/her browser. The Web
server than process the page through a sequence of steps before response is sent back to
the user's browser. Page life cycle are as under.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

1. Page Request
 The page request occurs before the page life cycle begins.
 When the page is requested by a user, asp.net determines whether the page needs to be
parsed and compiled or whether a cached version of the page can be send in response
without running the page.

2. Start
 In the start step, page properties such as request and response are set. At this stage, the
page also determines whether the request is a postback or a new request and sets the
ispostback property.
 Additionally during the start step, the pages UIculture property is set.
3. Page initialization
 During page initialization, controls on the page are available and each controls unique
ID property is set.
 Any themes are also applied to the page.
 If the current request is a postback. The post back data has not yet been loaded and
control property values have not been restored to the values from the view state.

4. Load
 During load, if the current request is a postback, control properties are loaded with
information’s recovered from view state and control state.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

5. Validation
 During validation, the validate method of all validator controls is called.

6. Postback event handling


 If the request is a postback, any event handlers are called.

7. Rendering
 Before rendering, view state is saved for the page and all controls.
 During the rendering phase, the page calls the render method for each control,
providing a text writer that writes its output to the outputstream of the page response
property.

8. Unload
 Unload is called after the page has been fully rendered, send to the client and is ready
to be discarded.
 At this point, page properties such as response and request are unloaded and any
cleanup is performed.

 ASP.NET Page Event Life Cycle

1. PreInit
 The entry point of the page life cycle is the pre-initialization phase called “PreInit”.
 This is the only event where programmatic access to master pages and themes is
allowed.
 You can dynamically set the values of master pages and themes in this event. You can
also dynamically create controls in this event.

2. Init
 This event fires after each control has been initialized, each control's UniqueID is set
and any skin settings have been applied.
 You can use this event to change initialization values for controls.
 The “Init” event is fired first for the most bottom control in the hierarchy, and then fired
up the hierarchy until it is fired for the page itself.

3. PreInitComplete
 Raised once all initializations of the page and its controls have been completed.
 Till now the viewstate values are not yet loaded, hence you can use this event to make
changes to view state that you want to make sure are persisted after the next postback.

4. PreLoad
 Raised after the page loads view state for itself and all controls, and after it processes
postback data that is included with the Request instance.

5. Load
 The important thing to note about this event is the fact that by now, the page has been
restored to its previous state in case of postbacks.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 Code inside the page load event typically checks for PostBack and then sets control
properties appropriately.
 This method is typically used for most code, since this is the first place in the page
lifecycle that all values are restored.
 You may also wish to call Validate and check the value of IsValid in this method. You
can also create dynamic controls in this method.

6. Control events
 Use these events to handle specific control events, such as a button controls click event
or a textbox controls textchanged event.

7. LoadComplete
 This event signals the end of Load.

8. PreRender
 Allows final changes to the page or its control.
 This event takes place after all regular PostBack events have taken place.
 This event takes place before saving ViewState, so any changes made here are saved.
 For example : After this event, you cannot change any property of a button or change
any viewstate value. Because, after this event, SaveStateComplete and Render events
are called.

9. Save state complete


 Before this event occurs, viewstate has been saved for the page and for all controls.
 Any changes to the page or controls at this point will be ignored.
 Use this event perform tasks that require view state to be saved, but that do not make
any changed to controls.

10. PreRenderComplete
 This is a method of the page object and its controls (and not an event).
 At this point, ASP.NET calls this method on each of the page’s controls to get its
output. The Render method generates the client-side HTML, Dynamic Hypertext
Markup Language (DHTML), and script that are necessary to properly display a control
at the browser.

11. Unload
 This event is used for cleanup code. After the page's HTML is rendered, the objects are
disposed of.
 During this event, you should destroy any objects or references you have created in
building the page.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 ASP.NET Application Folder / Application Directory Structure.

 ASP.NET 2.0 onwards uses a file-based approach.


 That means, all class files, resource files, data files and folders are maintained in a
hierarchical structure.
 If we are working with ASP.NET 2.0, we can add files and folders using the Add Items
option.
 If we look at a sample application hierarchy, it will look like the following figure.

 We can add as many as files and folders as we like (according to our requirements) within
our solutions.
 And it won't be necessary to recompile them each and every time they are added.
 It is ASP.NET's task to dynamically compile them when required.
 So, what ASP.NET 2.0 does is, it uses a predefined folder structure containing the files
(classes, images, resources, etc.), to compile them dynamically and we can access those
files throughout the application.
 ASP.NET also provides special folders to maintain files and resources.
 Let's see the advantages of using these folders.

Advantages of Application Folder


 We can maintain resources (classes, images, code, databases, themes) in an organized
manner, which allows us to develop and maintain sites easily
 All files and folders are accessible through the application
 We can add as many files as required
 Files are compiled dynamically when required
 Different Types of Application Folder
 ASP.NE treats the following folders in a special manner.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

Application Folder Or Application Directory Structure :

1. App_Code
 As its name suggests, the App_Code Folder stores classes, typed data sets, etc.
 All the items that are stored in App_Code are automatically accessible throughout
the application.
 If we store any class files (like .cs or .vb) it compiles them automatically.
 It automatically creates type data sets from .xsd (XML schema) files, and creates
XML web service proxy classes from WSDL.Let's have a look at how we can use
the App_Code folder.
 We can add an App_Code folder, by Solution File → right click → Add ASP.NET
Folder → App_Code. The App_Code folder is now added to your application.

 Try to add one more App_Code folder by using the same steps. Oops... the
App_Code folder is no longer available there. So, ASP.NET allows you to add an
App_Code folder only once.
 Now we can add new items like classes, text and xml files into the App_Code folder
and we can also add existing files there.

 Let’s use the app_code folder

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 Let's have a look at one example that shows how it works. Into the App_Code folder,
I have added a class MyVBClass.vb.
 In that class I have written a small spice of code for adding two numbers.

small spice of code for adding two numbers.

 Now, Try to access this class, from any where in your application. You will see that
MyVBClass accessible throughout the application.

 If we want to store different classes like .cs or .vb, then what will happen? If we kept
both .cs and .vb classes in the same folder, it will give following compilation error.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 This is because all the classes contained in the App_Code folder are built into a
single assembly and it can't have different languages at root level, or even at child
level folders in following manner:

 We have a solution to overcome this problem. We have to create separate folders for
C# and for VB or other classes

 Store class files separately in those folders and configure the folder hierarchy in the
web.config file.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

2. Bin
 The Bin folder is used for keeping assemblies inside it.
 We can access those as a reference from anywhere of our web application.
 Use of Bin folder comes into the picture if we use any class library within our web
application.
 Suppose we are creating a class library called TestLib After building the library, we will
get TestLib.dll.
 Now, right click on solution file → Add References → Project, select the TestLibProject,
click on OK.
 Check the Bin folder, it will contain TestLib.dll and TestLib.pdb files.

 Assemblies in the Bin folder do not need to registered on the system, ASP.NET recognizes
the presence of DLLs inside the Bin Folder.
 Keeping .pdb files inside Bin folder helps us in debugging.
 The main limitation of storing assemblies in the Bin folder is that their scope is limited to
the current application.
 Therefore, they cannot access any code outside of current web application.

3. App_Data

 The App_Data folder is used as a ata storage for the web application.
 It can store files such as .mdf, .mdb, and XML.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 It manages all of your application's data centrally.


 It is accessible from anywhere in your web application.
 The real advantage of the App_Data folder is that, any file you place there won't be
downloadable.
 We can add .mdf files to the App_Data folder directly by selecting Add New Item.
 From there we can a create table, procedure or function without opening SQL Server.
 Now if we want to add that data to our application, we can easily use it.

 Now , look at the connection string that we need to write for accessing the App_Data
folder's databases.

 We can connect with MyDB.mdf database using this connection string. Check the example
below, which I have used to read the table data from the MyDB.Mdf file.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

4. App_Themes

 If you want to give your web sites a consistent look, then you need to design themes for
your web application.
 The App_Themes folder contains all such themes.
 An App_Theme folder can contain two subfolders; one for CSS files and the other for skin
files.
 When we add an App_Theme folder, a subfolder with name Theme1 will be automatically
created.
 We can change the name of the theme folder as per our requirements.

 Now lets see how to create skin files or CSS file , the main concern here is how to apply
them.
 You can easily find the details ofskins and CSS via Google.
 Now that we have to apply the theme to the page, there are several way to do that.
 We could set the theme from aspx page using a page directive in following way

 While we are going to set themefrom aspx page, the list of themes available to us is as
shown in the figure.
 We can set the theme from the code behind file also, and we can even change theme at
runtime (using HttpHandler ).

5. App_Browser

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 The App_Browser folder contains browser information files (.browser files).


 These files are XML based files which are used to identify the browser and browser
capabilities.
 You will find the browser files in the following location.

 If you want to change a .browser file, just copy the file to the App_Browser folder and
change it.
 You can create new browser files by just clicking on Add New Item of the App_Browser
folder.
 As I already mentioned, a browser file is a configuration file, it generally looks like this:

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

6. App_WebReference

 As the name suggests, the App_WebReference folder contain references to any web
services.
 If we added any web services with our web application, they go automatically into the
App_WebReference folder, in the same way as in windows applications, if we added any
DLLs, they would go under the Reference folder.

 Before starting on the App_GlobalResource and App_LocalResource folders, lets have a


small introduction on ASP.NET resources.
 If you are, say, creating sites for a multinational company, or a public web sites that can be
accessible from all over the world, you need to consider the best way to address users in
different cultures and different countries in different languages.
 ASP.NET provides the infrastructure to create web applications that automatically adjust
formatting and language according to the user's preferences, by using resource files.The
main purpose of resource files is localization of the web application.
 ASP.NET uses resource files to make supporting multiple languages simpler.
 Visual Studio 2005 can automatically generate XML resource files that contain text for
your controls in different languages.
 When a user visits the sites, they can change the languages of the sites based on their
preference.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 There are two type of resources:


✓ Local resources
✓ Global resources

7. App_LocalResource

 Local resources are specific to a single web page, and should be used for providing
multilingual functionalityon a web page.
 Local resources must be stored in the App_LocalResource subfolder of the folder
containing the web page.
 Because you might have local resources for every page in your web application, you might
have App_LocalResource subfolders in every folder.
 If you want to create local resources for a page, open the design view of the page and then
from Tool Menu select Generate Local Resource.
 You will then see that a resource file is automatically created in the corresponding
App_LocalResource folder.

Note: Default2.aspx.resx is the resource file for Default2.aspx, and Others.aspx.resx is the resource file
for Others.aspx. Both resource files are inside the App_LocalResource folder.

 The following code shows you the XML code for the resource file. To change the resource
file, we can either change the XMLdirectly or use the Resource Editor.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 If we change anything on the page, the resource file will be automatically updated.
 If you want a test application for Local_Resource, just create a copy of Default2.aspx.resx
and rename it to default2.aspx.fr.resx (for French resources).
 Now, as a test, I have changed the button's tool tipfor the French resource to "French
ToolTip".
 Now change your web browser settings and set French as the default culture.
 (For Internet Explorer, use Tools → Internet options → Languages, add French to the top
of the list and test the application)
 Test the button tool tip in this way, and you can test it for other languages also.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

8. App_GlobalResource

 The App_GlobalResource folder can be read from any page or code that is anywhere in the
web site.
 Global resources must be stored in the App_GlobalResource folder at the root of the
application.
 We should use the App_GlobalResource folder when we need a single resource for
multiple web pages.
 We can define ASP.NET control properties by manually associating them with resources
in global resource files.

You can add a global resource file by right clicking on the App_GlobalResource folder and
clicking on Add Items. Add .resx files as resources.

 We can access these resources programmatically by using the Resource.Resourceobject.

E.g.:

Label1.Text = Resource.Resource.MyText

We can use the GetLocalResourceObject()and GetGlobalResourceObject()


methods to access global resources, and then cast them to the correct type.

Label1.Text = GetLocalResourceObject("Label1.Text").ToString();

 Dissecting of URL

 Web addresses are URL (Uniform Resource Locator)


o A server address and a path to a particular file
o URLs are often redirected to other places

e.g
http://www.swamigurukul.com/classes/asp.net/index.aspx
.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

protocol http://www.
web server Swamigurukul
Domain .com
Path /classes/asp.net/ (dirs(folders))
File Index
file extension .aspx

 Global Application Class File ( Global.asax)

 Global application class file stores information that apply to the entire website.
 This file resides in the root directory of the website.
 This is an optional file so while creating an application it does not exist in the root directory.
 It contain the code that is executed when certain events, such as start of an application or
error in an application.
 This file contain event handling code for events that are raised for the application or
session.
 No user can see the code written in this file.
 Global.asax is a file used to declare application level events and object.
 The global.asax file is compiled upon the arrival of the first request for any resource in the
application.
 When the application is requested for the first time, the global.asax file is parsed and
compiled to a class that extends the HttpApplication class.
 Asp.net automatically recognize the changes in global.asax
 There are only one global.asax file reside in root directory.
 In this file. There are the following event occur to handle.

1. Application_Start
 Code that runs on application startup
2. Application_End
 Code that runs on application shutdown
3. Application_Error
 Code that runs when an unhandled error occurs
4. Session_Start
 Code that runs when a new session is started
5. Session_End
 Code that runs when a session ends.
' Note: The Session_End event is raised only when the sessionstate mode is set to InProc
in the Web.config file. If session mode is set to StateServer or SQLServer, the event is
not raised.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 Web Configuration File (Web.config)

 Each and every asp.net application has its own copy of configuration settings stored in a
file called Web.Config.
 The XML based web.config file is used to specify the application wide settings for your
entire application.
 The web.config file is basically XML-based text file.
 There can be multiple config file in your application.
 Web.config file does not have any visual representation.
 If the web application spans multiple folders, each sub folder has its own web.config file
that inherits or overrides the parents file setting.
 WEB.CONFIG looks Like the following

<?xml version="1.0"?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>

<configSections>
</configSections>
<appSettings/>
<connectionStrings/>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="false">

</compilation>
<authentication mode="Windows" />
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

<customErrors mode="RemoteOnly"
defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
</configuration>

❖ Configuration Setting
<configuration>
The root element of a web.config file is always a <configuration> tag. Every web.config
file must have a configuration element.
<appSettings>
The appSettings section provides a way to define custom application setting for asp.net
application.
<connectionStrings>
It stores all kinds of connection string information.
<system.web>
It’s a fixed area of web.config file. Programmer cannot change or add any elements to the
structure.
<compilation>
Configure various options like debug assemblies, default language to use in dynamic
compilation model and other compiler options like compiling custom resource files.
<Pages>
Identifies page specific configuration settings.
<authentication>
Authentication is a process of identifying a user, while authorization is the process of
determining if an authenticated user has access to the resources they requested.

Whenever a user logs on to an application, the user is first authenticated and then
authorized.

ASP.NET PROVIDES THREE WAYS TO AUTHENTICATE A USER

Authentication Definition
Type
None No Asp.net authentication services are active. Note that IIS
authentication services can still be present.
Windows This is the default authentication mode in asp.net.
Using this mode, a user authenticated based on his/her windows
account.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

Forms Provides information on how to create an application specific


login form and perform authentication using your own code.

The authentication mode is based on cookies where the user


name and the password are stored either in a text file or the
database.

After a user is authenticated, the user credentials are stored in a


cookie for use in that session.

Whern user has not logged in and requests for a page that is
insecure, he or she is redirected to the login page of the
application.
Passport Passport authentication is a centralized authentication service
provided by Microsoft that offer a single logon and core profile
services for member sites.

It allows the user to create a single sign-in name and password to


access any site that has implemented the passport single sing-in
(SSI) services.

 RoundTrip

When user interaction requires processing on the server, the web page Is posted back to
the server processed and returned back to browser. This sequence called roundtrip.

 ASP.Net State Management

 Web is stateless. A Web page is recreated every time it is posted back to the server.
 In traditional web programming, all the information within the page and control gets wiped
off on every postback.
 To overcome this problem, ASP.NET Framework provides various ways to preserve the
states at various stages like controlstate, viewstate, cookies, session, etc. These can be
defined in client side and server side state management.
 State management option can be divided into two categories

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

STATE
MANAGEMENT

CLIENT SIDE SERVER SIDE

APPLICATION
VIEW STATE HIDDEN FIELDS SESSION STATE
STATE

QUERY STRING COOKIES DATABASE

A. Client Side State Management


 In this type, stored information either in the page or on the client computer.
 For these options, no information is maintained on the server between round trips.

1.ViewState
 This is the default method that page use to keep information between round trips.
 View state is used to store information for single user.
 We can set the page specific information in viewstate.
 View state is the default built in feature control persist data between post backs.
 Each webpage has the EnableViewState Property. Programmer can on/off as per
requirement. By default this property is set to true.
 You can also disabled view state for the entire page using EnableViewState=false
@page directive.
 The view state is implemented with a hidden form field called _VIEWSTATE, which
automatically create in web page.
 View state data is encoded as binary Base64.

❖ Advantages
✓ Simple for page level data.
✓ Encrypted storage
✓ It can set also at control level
✓ Simple implementation

❖ Disadvantage

✓ Make a page heavy loaded.


✓ Device limitations.
✓ Mobile device might not have the memory capacity to store large amount of data.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

Syntax:

1. To Store Value in ViewState


ViewState(“KeyName”) = Value to Store

2. To Retrieve Value from ViewState

Variable Name = ViewState(“KeyName”)

2. Hidden Field

 Hidden fields are used to store data at page level.


 As its name, these field are not rendered by browser and visible to user.
 A hidden field stores a single variable in its value property and must be explicitly added
to the page.
 It’s a standard control for which you can set its properties. When the page is submit to
server, hidden field value are also posted to server along with other control on the page.
 The important properties of the control Is VALUE.

❖ Advantages
✓ No server resource required.
✓ Widespread support.
✓ Almost all browser and client device support.
✓ Simple to implementation.
✓ Store small amount of data so they occupy small size.

❖ Disadvantage

✓ Potential Security Risk.


✓ Performance consideration
✓ Storage limitation.

Syntax:

1. To Store Value in Hidden Field

HiddenField1.Value = “Data to Store”

2. To Retrieve Value from Hidden Field

Variable Name = HiddenField1.Value

3. QueryString

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 A query string is information that is appended to the end of a page URL.


 Query string are usually used to send information from one page to another page.
 In the URL, the query string starts with a question mark( ? ) and included the
attributes/value.
 Most of the browser has the limit to pass data upto 255 character.

E.g. http://www.swamigurukul.com?Course=BCA

❖ Advantages
✓ No server resource required.
✓ Widespread support.
✓ Almost all browser and client device support.
✓ Simple to implementation.

❖ Disadvantage

✓ Client browser limit on URL length.


✓ Cross paging functionality makes it redundant.
✓ Easily modified by end users.
✓ Security risk.
✓ Limited capacity.

Syntax:

1. To Pass Value using Querystring

Response.Redirect(“PageName.aspx?KeyName=Value”)

2. To Retrieve Value from querystring

Variable Name = Request.QueryString(“KeyName”)

3. Cookies
 A Cookies are small amounts of text that can be stored on the client pc by the browser.
 The cookie can be accessed both at the client through the use of Javascript and also at
the server.
 While cookies can be a convenient way to store small bits of state information, it's
important to keep in mind that the client browser may have been configured not to
accept cookies.
 In each cookie you can’t save more than 4k of information. Remember clients can open
cookies and see the content of a cookie so never save a password there. Cookies are
usually used to save user preference information.

❖ Disadvantage

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 Most browsers support cookies of up to 4096 bytes. This limitation makes the cookies
a way to store only small amount of data.

 Browsers have a limit on the amount of cookies a web site can save in the client. Most
browsers allow only 20 cookies per site.

 The user can set the browser to disable cookies and therefore you can't trust cookies
and you always have to check if the browser enables cookies.

Syntax:

1. To Store Value using Cookies

Dim snk As New HttpCookie(“StoreKeyName”)


Snk.Values(“KeyName”) = Value
Snk.Expires = Date
Response.Cookies.Add(snk)

2. To Retrieve Value from Cookies

Variable Name =
Request.Cookies(“StoreKeyName”).Value(“KeyName”).Tostring()

B. Server Side State Management

1. Application State

 Application object provided a great place to store frequently used pieces of data that
changed infrequently, such as content menus or reference data.
 It can be implemented using System.Web.HttpApplicationState.
 Using this method, we can store an information globally and access it.
 Data which is needed to be persisted for entire site can stored in this application object.
 For efficiency, this state is typically stored once and then read from many times.

Syntax:

1. To Store Value using Application State

Application(“KeyName”) = Value

2. To Retrieve Value from Application State

Variable Name = Application(“Name”)

2. Session State

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 ASP.NET allows you to save values by session state which is an instance of


HttpSessionState class.
 Session state can store value and pass across the page.
 It’s allows to store any kinds of object.
 Session state is similar to application state, except that it is scoped to the current
browser session.
 Every client that uses the application have their own session.
 A session end if the session timeout or programmer required as per requirement.
 It lives for as long as the user continues to makes requests plus some period of time
afterward.(20 Min.)
 Each active ASP.Net session is identified and tracked using a 120 bit sessionid
contained in URL.

❖ Important Properties/Method of Session state

Method Use
Session.Abandon Cancel the current session
Session.Remove Delete the particular session.
Session.Remove(SName)
Session.RemoveAll Delete All The session.
Session.Timeout If user inactive on the web then session time out.
Session.Timeout = 20
Session.SessionId Get the session id in reqd only mode.

❖ Advantages
✓ Simple implementation.
✓ Session Specific Events.
✓ Data persistence.
✓ Cookieless support.

❖ Disadvantage

✓ Performance consider.

Syntax:

1. To Store Value using Session

Session(“KeyName”) = Value

2. To Retrieve Value from Session

Variable Name = Session(“Name”)

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 Image Control
 Image box control is used to display images on it.
 The images displayed can be anything varying from Bitmap, JPEG, GIF, PNG or any other
image format files. The Image control is based on the Control class.
 Notable property of the Image Control in the Appearance section of the properties window
is the ImageURL property which allows to add the image to be displayed on the control.
 Images can be added to the image control with the Imageurl property from the Properties
window or by code.

 ImageUrl is the method of Image properties to load image in image control dynamically.

 Important Properties

Properties Description
AlternateText Alternate text to be displayed in absence of the image.
ImageAlign Alignment options for the control.
ImageUrl Path of the image to be displayed by the control.

 File Upload Control

 ASP.NET has two controls that allow users to upload files to the web server. Once the server
receives the posted file data, the application can save it, check it, or ignore it. The following
controls allow the file uploading

HtmlInputFile - an HTML server control


FileUpload - and ASP.NET web control

 The FileUpload control allows the user to browse for and select the file to be uploaded,
providing a browse button and a text box for entering the filename.
 Once, the user has entered the filename in the text box by typing the name or browsing, the
SaveAs method of the FileUpload control can be called to save the file to the disk.

The basic syntax of FileUpload is

<asp:FileUpload ID= "Uploader" runat = "server" />

 The FileUpload class is derived from the WebControl class, and inherits all its members. Apart
from those, the FileUpload class has the following read-only properties.

 Important Properties

Properties Description
FileBytes Returns an array of the bytes in a file to be uploaded.
FileContent Returns the stream object pointing to the file to be
uploaded.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

FileName Returns the name of the file to be uploaded.


HasFile Specifies whether the control has a file to upload.
PostedFile Returns a reference to the uploaded file.

 The posted file is encapsulated in an object of type HttpPostedFile, which could be accessed
through the PostedFile property of the FileUpload class.
 The HttpPostedFile class has the following frequently used properties:

 Important Properties

Properties Description
ContentLength Returns the size of the uploaded file in bytes.
ContentType Returns the MIME type of the uploaded file.
FileName Returns the full filename.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 Drop Down List


 Drop-down lists contain one or more list items from where we can select one item at a time.
These lists can be loaded either by code or by the ListItemCollection editor.

 Important Properties

Properties Description
Items The collection of ListItem objects that represents the
items in the control
Rows Specifies the number of items displayed in the box. If
actual list contains more rows than displayed then a
scroll bar is added.
SelectedIndex The index of the currently selected item. If no item is
selected, the value of this property is -1.
SelectedValue The value of the currently selected item. If no item is
selected, the value of this property is an empty string ("").
Text The text displayed for the item.

 The SelectedIndexChanged event is raised when the user selects a different item from a drop-
down list.

 Important Method

Method Description
Add(string) Adds a new item at the end of the collection and assigns
the string parameter to the Text property of the item.
Insert(integer, string) Inserts an item at the specified index location in the
collection, and assigns string parameter to the
text property of the item.
Remove(string) Removes the item with the text value same as the string.
RemoveAt(integer) Removes the item at the specified index as the integer.
Clear Removes all the items of the collection.
FindByValue(string) Returns the item whose value is same as the string.
FindByValue(Text) Returns the item whose text is same as the string.

 Bulleted List

 The bulleted list control creates bulleted lists or numbered lists. These controls contain a
collection of ListItem objects that could be referred to through the Items property of the control.
 The item can be statically written or can be bound with the data source.

 Important Properties

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

Properties Description
BulletImageURL The URL of image use as a bullets
BylletStyle The style used for the bullet like Number, LowerAlpha,
UpperAlpha, LowerRoman, UpperRoman, Disc, Circle,
Square, CustomImage
Display Mode The display mode of the bulleted list like hyperlink, text
or linkbutton.
ITEM The collection of the item in the list.

 Checkbox

 The CheckBox Web server control gives us an option to select, say, yes/no or true/false.
 A checkbox is clicked to select and clicked again to deselect some option.
 When a checkbox is selected, a check (a tick mark) appears indicating a selection.
 CheckBox used when multiple selection allows in the application. E.g. for Games Like Cricket,
VolleyBoll, Chess etc.

 Important Properties

Properties Description
ID To identify in the coding window by the id.
Checked The Check state of the control Means to Check box check
by default.
TextAlign Set the Alignment of the Text Caption
Text Text Shown with the checkbox control

 Important Event

Event Description
CheckedChanged Fires when the checked state of the control changes.

 Radiobutton

 This control allows the user to select only single item from the list at a time by default.
 To create a group of radio buttons, you specify the same name for the GroupName attribute of
each radio button in the group. If more than one group is required in a single form, then specify
a different group name for each group.
 If you want check box or radio button to be selected when the form is initially displayed, set
its Checked attribute to true. If the Checked attribute is set to true for multiple radio buttons in
a group, then only the last one is considered as true.

 Important Properties

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

Properties Description
ID To identify in the coding window by the id.
Checked The Check state of the control Means to Check box check
by default.
TextAlign Set the Alignment of the Text Caption
Text Text Shown with the checkbox control
GroupName To specify same group name in all the option button
controls to make in a group wise

 Important Event

Event Description
CheckedChanged Fires when the checked state of the control changes.

 Hyper Link

 The HyperLink is used to create a link to another Web page.

 Important Properties

Properties Description
ID To identify in the coding window by the id.
Text To Specifies the text on a hyperlink
ImageURL The URL of the image to display for the link
Navigate URL The target URL of the link
Target The target frame of the URL
Target Means
_blank - the target URL will open in a new window
_self - the target URL will open in the same frame as it
was clicked
_parent - the target URL will open in the parent frameset
_top - the target URL will open in the full body of the
window

 Tables

 Table control is used to structure a web pages. In other words to divide a page into several
rows and colums to arrange the information or images. When it is rendered on the page, it is
implemented through <table> HTML tag.

 We can simply use HTML <table> control instead of using asp:Table control. However many
of one benefits of using asp:Table control is we can dynamically add rows or columns at the
runtime or change the appearance of the table.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 You can skip ID property of the TableRow or TableCell, however it is advisable to write these
property otherwise you will not be able to play with these controls.

 Important Properties

Properties Description
BackImageUrl Used to Set background image of the table
Caption Used to write the caption of the table.
BorderStyle Style around the border
Gridlines Which gridlines display around the cells
CaptionAlign Alignment to the assosicated caption
Rows The collection of rows within the table.

 Panel

 The Panel control works as a container for other controls on the page. It controls the appearance
and visibility of the controls it contains. It also allows generating controls programmatically.

 Important Properties

Properties Description
BackImageUrl URL of the background image of the panel.
DefaultButton Gets or sets the identifier for the default button that is
contained in the Panel control.
Direction Text direction in the panel.
GroupingText Allows grouping of text as a field.
HorizontalAlign Horizontal alignment of the content in the panel.
ScrollBars Specifies visibility and location of scrollbars within the
panel.
Wrap Allows text wrapping.

 Tree View Control

 The TreeView control is the most impressing new control in ASP.NET 2.0. It is used to display
the hierarchical data in tree view format.
 It also supports dynamic population of the node on demand without page refresh.
 When TreeView is displayed for the first time, it displays all its nodes. However, it can be
controlled by setting ExpandDepth property.

 Important Properties

Properties Description
DataSourceID Indicates the data source to be used (You can use .sitemap
file as datasource).

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

Text Indicates the text to display in the node.


Tooltip Indicates the tooltip of the node when you mouse over.
Value Indicates the nondisplayed value (usually unique id to use in
server side events)
NavigateUrl Indicates the target location to send to the user when node is
clicked. If not set you can handle
TreeView.SelectedNodeChanged event to decide what to do.
Target If NavigationUrl property is set, it indicates where to open the
target location (in new window or same window).
ImageUrl Indicates the image that appears next to the node.
ImageToolTip Indicates the tooltip text to display for image next to the
node.
Style Properties
NodeSpacing Space (in pixel) between current node and the node above or
below it.
VerticalPadding Space (in pixel) between the top and bottom of the node text.
HorizontalPadding Space (in pixel) between the left and right of the node text.
ChildNodePadding Space (in pixel) between the parent node and its child node.

 Menu Control

 The Menu control is used to create a menu of hierarchical data that can be used to navigate
through the pages.
 The Menu control conceptually contains two types of items. First is StaticMenu that is always
displayed on the page, Second is DynamicMenu that appears when opens the parent item.

 Important Properties

Properties Description
DataSourceID Indicates the data source to be used (You can use
.sitemap file as datasource).
Text Indicates the text to display in the menu.
Tooltip Indicates the tooltip of the menu item when you mouse
over.
Value Indicates the nondisplayed value (usually unique id to
use in server side events)
NavigateUrl Indicates the target location to send the user when menu
item is clicked. If not set you can handle
MenuItemClick event to decide what to do.
Target If NavigationUrl property is set, it indicates where to
open the target location (in new window or same
window).
Selectable true/false. If false, this item can't be selected. Usually in
case of this item has some child.
ImageUrl Indicates the image that appears next to the menu item.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

ImageToolTip Indicates the tooltip text to display for image next to the
item.
PopOutImageUrl Inidcates the image that is displayed right to the menu
item when it has some subitems.
Target If NavigationUrl property is set, it indicates where to
open the target location (in new window or same
window).
Style Properties
StaticMenuStyle Sets the style of the parent box in which all menu items
appears.
DynamicMenuStyle Sets the style of the parent box in which dynamic menu
items appears.
StaticMenuItemStyle Sets the style of the individual static menu items.
DynamicMenuItemStyle Sets the style of the individual dynamic menu items.
StaticSelectedStyle Sets the style of the selected static items.
DynamicSelectedStyle Sets the style of the selecdted dynamic items.
StaticHoverStyle Sets the mouse hovering style of the static items.
DynamicHoverStyle Sets the mouse hovering style of the dynamic items
(subitems).

 Site map path

 The SiteMapPath control displays the trail (navigation path) to the current page. The path acts
as clickable links to previous pages.
 Unlike the TreeView and Menu control the SiteMapPath control does NOT use a
siteMapDataSource. The SiteMapPath control uses the web.sitemap file by default.

 Important Properties

Properties Description
PathSeparator Gets or sets Path separator text. (By default it is : )
NodeStyle Sets the style of all nodes that will be displayed.
CurrentNodeStyle Sets the style on node that represent the current page.
RootNodeStyle Sets the style on the absoulte root node.
PathSeparatorStyle Sets the style of path separator.
NodeStyle Sets the style of all nodes that will be displayed.
Path Direction The direction of the path to render.

 Wizard Control

 The Wizard control is a more advanced version of the MultiView control.


 It has built-in yet customizable behavior, including sidebar with step links, style, and
navigation buttons.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 Generally, Wizards represent a single task and user moves, from the current step to the next or
immediately preceding step in case he/she wants modification.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 Master Page

 Master pages allow you to create a consistent look and behavior for all the pages (or group
of pages) in your web application.
 A master page provides a template for other pages, with shared layout and functionality. The
master page defines placeholders for the content, which can be overridden by content pages.
The output result is a combination of the master page and the content page.
 The content pages contains the content you want to display.
 When users request the content page, ASP.NET merges the pages to produce output that
combines the layout of the master page with the content of the content page.
 Source View While Adding Master Page.

<%@ Master Language="VB" CodeFile="MasterPage.master.vb"


Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0


Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >


<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:contentplaceholder
id="ContentPlaceHolder1" runat="server">

</asp:contentplaceholder>
</div>
</form>
</body>
</html>

Master and Content Pages

 Defining a Master Page is just like defining a normal page. Master Pages can contain markup,
controls, or code, or any combination of these elements.
 However, a Master Page can contain a special type of control, called a ContentPlaceHolder
control.
 A ContentPlaceHolder defines a region of the master page rendering that can be substituted
with content from a page associated to the master. A ContentPlaceHolder can also contain
default content, just in case the derive page does not need to override this content.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 To differentiate a Master Page from a normal page, a Master Page is saved under the .master
file extension. A page can derive from a Master Page by defining a MasterPageFile attribute
on its Page directive, A page that is associated to a Master Page is called a Content Page.

Advantage of Master Page

1. Centralized Updating
2. Common Controls
3. Flexibility
4. Enhanced User Experience
5. Site Management
6. Less Code
7. Less Storage Requirements

 Themes

 ASP.NET includes a number of features for customizing the look-and-feel or style of pages
and controls in your application.
 Controls support a Style object model for setting stylistic properties such as fonts, borders,
background and foreground colors, width, height, and more. Controls also fully support
Cascading Style Sheets (CSS) for factoring style settings separately from control properties.
 You can define style information as control properties or CSS, or you can also define this
information in a separate group of files called a Theme, to be applied to all or a portion of the
pages in your application. Individual control styles are specified as a Skin within a Theme.
 Themes implement under the App_Themes Folder. It contains images, skin & css files.

HOW TO DEFINE THEME


 To define a Theme, you need to right click the Web Project > Add ASP.NET Folder
>Theme. This will by default create a new folder called App_Themes > Theme1. You
are free to rename the Theme1 folder but not the App_Themes folder. The folder name
under App_Themes folder will be considered as Theme name and all .css files and .skin
files under this will be attached with that theme. You can create as many number of theme
you want under App_Themes folder.
 A Theme can have more than one .css and/or .skin files.

WHAT IS .CSS FILE

 A .css file is a Cascading Style Sheet file that contains the style, behavior about a html page
and its elements. These styles are written in the .css file as a block of code and they are
referred to as css class.

WHAT IS .SKIN FILE

 .skin file is a new type of file introduced in ASP.NET 2.0, this can contain style information
of any asp.net server control. These information are written in this file as if they are
written asp.net page but ID property is not specified

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 Validation Control
ASP.NET validation controls validate the user input data to ensure that useless,
unauthenticated, or contradictory data don't get stored.

BaseValidator Class

The validation control classes are inherited from the BaseValidator class hence they inherit
its properties and methods. Therefore, it would help to take a look at the properties and the
methods of this base class, which are common for all the validation controls

Members Description
Properties
ControlToValidate Indicates the input control to validate.
Display Indicates how the error message is shown.
Enabled Enables or disables the validator.
ErrorMessage Error string.
Text Error text to be shown if validation fails.
SetFocusOnError It indicates whether in case of an invalid control, the
focus should switch to the related input control.
ValidationGroup The logical group of multiple validators, where this
control belongs.

A. Required Field Validators


The RequiredFieldValidator control ensures that the required field is not empty. It is
generally tied to a text box to force input into the text box.

B. Range Validators
The RangeValidator control verifies that the input value falls within a predetermined
range.It has three specific properties

Properties Description
Type it defines the type of the data; the available values are:
Currency, Date, Double, Integer and String
MinimumValue it specifies the minimum value of the range
MaximumValue it specifies the maximum value of the range

C. Regular Expression Validators

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

The RegularExpressionValidator allows validating the input text by matching against a


pattern against a regular expression. The regular expression is set in the
ValidationExpression property.

The following table summarizes the commonly used syntax constructs for regular
expressions

Character Description
Escapes
\b Matches a backspace
\t Matches a tab
\r Matches a carriage return
\v Matches a vertical tab
\f Matches a form feed
\n Matches a new line
\ Escape character

Apart from single character match, a class of characters could be specified that can be
matched, called the metacharacters.

Metacharacters Description
. Matches any character except \n
[abcd] Matches any character in the set
[^abcd] Excludes any character in the set
[2-7a-mA-M] Matches any character specified in the range
\w Matches any alphanumeric character and underscore
\W Matches any non-word character
\s Matches whitespace characters like, space, tab, new line
etc.
\S Matches any non-whitespace character
\d Matches any decimal character
\D Matches any non-decimal character

Quantifiers could be added to specify number of times a character could appear

Quantifier Description
* Zero or more matches
+ One or more matches
? Zero or one matches
{N} N matches
{N,} N or more matches
{N,M} Between N and M matches

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

D. Compare Validators
The CompareValidator control compares a value in one control with a fixed value, or, a
value in another control.

It has the following specific properties

Properties Description
Type it specifies the data type
ControlToCompare it specifies the value of the input control to compare with
ValueToCompare it specifies the constant value to compare with
Operator it specifies the comparison operator, the available values
are: Equal, NotEqual, GreaterThan, GreaterThanEqual,
LessThan, LessThanEqual and DataTypeCheck

E. Custom Validators
The CustomValidator control allows writing application specific custom validation
routines for both the client side and the server side validation.

The client side validation is accomplished through the ClientValidationFunction property.


The client side validation routine should be written in a scripting language, like JavaScript
or VBScript, which the browser can understand.

The server side validation routine must be called from the control.s ServerValidate event
handler. The server side validation routine should be written in any .Net language, like C#
or VB.Net.

F. Validation Summary
The ValidationSummary control does not perform any validation but shows a summary of
all errors in the page. The summary displays the values of the ErrorMessage property of all
validation controls that failed validation.

The following two mutually inclusive properties list out the error message:

✓ ShowSummary: shows the error messages in specified format.


✓ ShowMessageBox: shows the error messages in a separate window.

 Ad Rotators

 The AdRotator control randomly selects banner graphics from a list, which is specified in an
external XML schedule file. This external XML schedule file is called the advertisement file.
 The AdRotator control allows you to specify the advertisement file and the type of window
that the link should follow in the AdvertisementFile and the Target property respectively.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 The basic syntax of adding an AdRotator is as follows

<asp:AdRotator runat = "server" AdvertisementFile = "adfile.xml" Target = "_blank" />

Advertisement File

 The advertisement file is an XML file, which contains the information about the
advertisements to be displayed.
 Extensible Markup Language (XML) is a W3C standard for text document markup. It is a text-
based markup language that enables you to store data in a structured format by using
meaningful tags. The term 'extensible' implies that you can extend your ability to describe a
document by defining meaningful tags for the application.
 XML is not a language in itself, like HTML, but a set of rules for creating new markup
languages. It is a meta-markup language. It allows developers to create custom tag sets for
special uses. It structures, stores, and transports the information.
 Following is an example of XML file:

<Advertisements>
<Ad>
<ImageUrl>rose1.jpg</ImageUrl>
<NavigateUrl>http://www.1800flowers.com</NavigateUrl>
<AlternateText>
Order flowers, roses, gifts and more
</AlternateText>
<Impressions>20</Impressions>
<Keyword>flowers</Keyword>
</Ad>

<Ad>
<ImageUrl>rose2.jpg</ImageUrl>
<NavigateUrl>http://www.babybouquets.com.au</NavigateUrl>
<AlternateText>Order roses and flowers</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>

<Ad>
<ImageUrl>rose3.jpg</ImageUrl>
<NavigateUrl>http://www.flowers2moscow.com</NavigateUrl>
<AlternateText>Send flowers to Russia</AlternateText>
<Impressions>20</Impressions>
<Keyword>russia</Keyword>
</Ad>
</Advertisements>

Element Description
Advertisements Encloses the advertisement file.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

Ad Delineates separate ad.


ImageUrl The path of image that will be displayed.
NavigateUrl The link that will be followed when the user clicks the ad.
AlternateText The text that will be displayed instead of the picture if it
cannot be displayed.
Keyword Keyword identifying a group of advertisements. This is used
for filtering.
Impressions The number indicating how often an advertisement will
appear.
Height Height of the image to be displayed.
Width Width of the image to be displayed.

 Login Control
1) Login

Login control provides a ready to use user interface that can be used as a Login interface
in the web site.

Properties of the Login Control


DestinationPageUrl Indicates the URL to be sent after login attempt
successful.
DisplayRememberMe true/false. Indicates whether to show Remember Me
checkbox or not.
CreateUserUrl Indicates the url of the create user page.
CreateUserText Indicates the text of the create user link.
PasswordRecoveryUrl Indicates the url of the password recovery page.
PasswordRecoveryText Indicates the text of the password recovery link.

2) Login View

LoginView control is very simple yet very powerful and customizable. It allows user to
customize its view for both anonymous user and logged in user.

3) Password Recovery

PasswordRecovery control is a ready to use control to help user to recover their


password, if they forget.

PasswordRecovery control uses Membership service to retrieve or reset user's password.

4) LoginStatus

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

LoginStatus control is a very simple and compact control that displays either Login (if
user is not nog logged in) or Logout (if user is logged in).

5) LoginName

LoginName control is used to display current logged in user name

6) Create User Wizard

CreateUserWizard control is a ready to use control that is used to create a new user to the
website.

Following are some important events that are very useful.

Events of CreateUserWizard Control


ContinueButtonClick Fires when user clicks Continue button in the last
wizard step.
CreatingUser Fires before creating a new user.
CreatedUser Fires after new user created.
CreateUserError Fires when creation of user is not successful.

7) Change Password

ChangePassword control is a ready to use control to help users to change their password.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

❖ Introduction to ADO.Net

 ADO.NET is a model used by .NET application to communicate with database


retrieving, accessing and updating data.
 Ado.Net has ability to separate data access mechanisms, data manipulation mechanisms
and data connectivity mechanisms.
 Ado.net is a part of the Microsoft .Net framework.
 The full form of ADO.Net is ActiveX Data Object.
 Ado.net provide set of classes that allow applications to read and write information in
databases.
 It’s a concept. It’s not a programming language.
 Ado.net introduces the concept of disconnected architecture.
 We need to add System.Data namespace for work with ADO.NET.
 It’s a next version of ActiveX Data Objects ( ADO ) technology which was used in VB 6.0

❖ Differentiate : ADO & ADO.Net

ADO ADO.NET
Ado used connected data usage ( ADO.NET used disconnected data
Connection Oriented Models ). environment ( Disconnected Models ).
XML Support is limited XML Full Support
This is used technology to access data and It’s uses XML for transmitting data to and
is COM based. from your database and web application.
ADO disconnected data provide by record Ado.net disconnected data provide by
set dataset and dataadapter
Ado, Record set is like a single table or Ado.net dataset, can contain multiple tables.
query result
Ado client connection model is very poor. Ado.net client disconnected as soon as the
Client application needs to be connected to data is fetched or processed. Data set is
data-server while working on the data always disconnected.

❖ Explain the Feature of ADO.Net


1. Disconnected data Architecture

 ADO.NET uses the disconnected data architecture. Applications connect to the


database only while retrieving , updating data.

 After the data is retrieved, the connection with database is closed. When the database
needs to be updated, the connection is re-established.

 Working with application that do not follow disconnected architecture leads to a


wastage of valuable system resources.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 Since the application connects to the database and keeps the connection open until it
stop running, but does not actually interact with the database except while retrieving
and updating data.

2. Data Cached in datasets

 A dataset is most common method of accessing data since it implements a


disconnected architecture.

 Since ADO.NET is based on a disconnected data structure, it is not possible for


application to interact with the database for processing each record.

 Therefore the data is retrieved and stored in datasets. A dataset is a cached set of
database records. You can work with the records stored in a dataset as you work with
the real data.

 The only difference being that the dataset is independent of data source and you remain
disconnected from the data source.

 ADO.NET support scalability by working with datasets. Database operations are


performed on the dataset instead of on the database. As a result, resources are saved,
and the database can meet the increasing demand of users more efficiently.

3. Data transfer in XML format

 XML is the fundamental format for data transfer in ADO.NET. Data is transferred
from a database into a dataset and from dataset to another component by using XML.
You can even use an XML file as a data source and store data from it in a dataset.

 The knowledge of XML is hidden from the user. Since a dataset is stored in XML
format, you can transmit it between different types of applications that support XML
and any component that read the dataset structure can process the data.

4. Interaction with the database is done through data commands

All operations on the database are performed by using data commands. A data
command can be a SQL statement or a stored procedure. You can retrieve, insert, delete
or modify data from a database by executing data commands.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

❖ Explain the ADO.Net Architecture / Write a note on ADO.NET Modal.


The data residing in a database is retrieved through data provider. Different components
of the data provider retrieved the data from database and provides the data to.Net application,
and update the database with the changes made in the application.

An application can access data either through a dataset or through a DataReader object.
Using a data set: - In this case, the data is cached in a dataset and the application accesses
the data from the dataset.
Using a data reader :- In this method, a DataReader object, which is a component of the
data provider, uses the Connection object to connect to the database, uses the Command
object to retrieve data and provides data to the application in a read only and forward
only mode.

Data Provider

A data provider is used for connecting to a database, retrieving data, sorting the data in a
dataset, reading the retrieved data updating the database.
There are two types of data providers:

a. OLEDB Data Provider: This type of data provider works all the OLEDB
providers, such as SQL OLEDB provider, Oracle OLEDB provider and Jet OLEDB

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

provider. The OLEDB data provider classes are present in System.Data.oleDB


namespace.

b. SQL Server data Provider: This type of data provider is used to work specifically
with Microsoft SQL Server. A SQL server data provider is recommended for
working with a Microsoft SQL Server data source, since a SQL server data provider
allows fast access to a data source without going through an OLEDB or ODBC
layer. The SQL Server data provider classes are present in the
System.Data.sqlClient Namespace.

➢ Component Of Data Provider

1. Connection

 This components is used to establish a connection with a data source.

 Two of the most common connection objects used is OleDbConnection and


SqlConnection.

 The table given below display the commonly used properties and methods of a
Connection object.

Name Description
ConnectionString() It provides information such as the data source and database
name that is used to establish connection with database.
ConnectionString Specifies
Provider, DataSource, Integrated Security

E.g.
“Provider=Microsoft.Jet.OLEDB.4.0;
DataSource=d:\abc.mdb”
Open() Method It is used to open connection with the data source that is
specified in the ConnectionString property.
Close() Method It is used to close connection with data source.
State It is used to describe the current state if the Connection
object. The value 0 indicates that the connection is closed
and value 1 indicates that the connection is open.
Dispose It release the connection object

2. Data Adapter

 A data adapter is used to integral working of ADO.NET since data is transferred to


and from a database, through a data adapter.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 A data adapter retrieves data from a database into a dataset and updates the database.

 When you make changes to the dataset, the changes in the database are actually done
by the data adapter.

 There are two types of data adapters that can be configured to connect a database on
Visual Studio .NET.

✓ SqlDataAdapter: This type of data adapter is configured to access data


specifically from Microsoft SQL Server.
✓ OleDbDataAdapter: This type of data adapter is configured to access data
from any database that is supported by an OLEDB data provider.

 A data adapter handles data transfer between the database and the dataset through its
properties and methods.

 Data Adapter Properties and Methods:

 A data adapter communication with a database while retrieving, inserting, deleting


and updating data. The following properties and methods of data adapter can be set
to perform various operations on a database:

✓ SelectCommand – Refers to a SQL statement or a stored procedure to


retrieve data from the database.

✓ InsertCommand - Refers to a data command to insert data into a database.

✓ UpdateCommand - Refers to a data command to update a database.

✓ DeleteCommand - Refers to a data command to delete data from a


database.

✓ Fill() Method – Fills the dataset with the records from a database.

✓ Update() Method – Executes the corresponding InsertCommand,


UpdateCommand or DeleteCommand for each insert, modified or deleted
row to reflects the changes in the database.

3. Data Command

 A data command is a SQL statement or a stored procedure that is used to insert, delete
or modify data in a data source. A data command is an object of the OleDbCommand
or SQLCommand class.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 For retrieving data through data commands, a connection object is created first to
connect to the database from where the data to be retrieved. Then, a command object
can be derived from SqlCommand or OleDbCommand class.

 To access a data source, a data command should provides information about the
connection for communicating with the data source, the SQL statement of the name
of the stored procedure to execute, and the parameter that may be required for
execution of the data command.

 Methods of Data Command Object

a) Execute Reader

✓ Execute commands that return rows


✓ Data reader object is a read and forward only cursor.
✓ It need live connection to data source.

b) ExecuteNonQuery

✓ Returns rows affected


✓ For UPDATE, INSERT, and DELETE statements, the return value is the number
of rows affected by the command.

c) ExecuteScalar

✓ Return a single value


✓ Used with aggregate function.
✓ It returns only first column of first row.

4. Data Reader

 Data reader is used to retrieve data from a data source in a read only and forward only
mode.

 A data reader uses the Connection object to connect to the database, the Command object
to execute SQL statements or procedures on the database and retrieves the data in a
sequential mode.

 Using data reader results in faster access to data and less memory usage since at any time,
only a single row is stored in the memory. The table given below displays the common
methods.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

NAME DESCRIPTION
Read Method It is used to read a row of data returned by executing the
command on a data source.
Close Method It is used to close the DataReader object.
NextResult Method It is used to navigate to the next of data in case the
command executing returns multiple rows of data.

5. DataSet

 In most cases, data is retrieved through datasets, since working with data commands is very
tedious and a data reader only allows data to be retrieved in read-only and forward-only
mode.
 Dataset is a disconnected, cashed set of records that are retrieved from a database. When
a connection is established with the database, the data adapter creates a dataset and stores
data in it. After the data is retrieved and stored in dataset, the connection with the database
is closed. Such a working architecture is called disconnected architecture. The dataset acts
like a virtual database containing tables, rows and columns. An application works with the
database records stored in the dataset.
 It can be considered as a local copy of the some portions of the database.
 The dataset contains a collection of one or more dataTable object made up of rows and
column of data.
 Tables can be identified in dataset using Dataset’s Table Properties
 It also contains primary key, foreign key, constraint and relational information about the
data in the dataTable objects.
 Dataset are also fully XML Featured.
 The Dataset is populated by dataadapter’s fill method

❖ What is Crystal Report / Why we used crystal report / Explain Crystal


Report with its design section.

 Crystal Reports is a popular Windows-based report writer (report generation program) that
allows a programmer to create reports from a variety of data sources with a minimum of
written code. OR Crystal Reports is a business intelligence application used to design and
generate reports from a wide range of data sources.

 Aim behind the reporting is to summarize the information from huge amout of data store
in database.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 Crystal Reports can access data from most widely-used databases and can integrate data
from multiple databases within one report using Open Database Connectivity ( ODBC ).

 Crystal Reports uses an ActiveX control called CrystalReport to establish a connection


with another program. A programmer can set properties of the CrystalReport control during
design time or at run time.

 To display a report in web or desktop application we have to use crystal report viewer.

 Crystal Reports for Visual Studio 2005 ships with an extensive SDK. You can use the SDK
to interact with the report programmatically at runtime, by use of one of four possible object
models:

✓ CrystalReportViewer, the simplest object model.

✓ ReportDocument, the more extensive object model.

❖ Crystal Report Design Section


 Crystal Reports design is divided in five section where concern information is stored for
display to user.

1. Report Header :

 Objects placed in the Report Header section print once, at the beginning of the
report.
 The Report Header section generally contains the report title and other information
you want to appear only at the beginning of the report.

2. Page Header

 Objects placed in the Page Header section print at every page, at the beginning of
the page.

 The Page Header section generally contains the report title and other information
you want to appear only at the beginning of the page.

3. Detail

 Objects placed in the Detail section display the data of the report.

4. Report Footer

 Objects placed in the Report Footer section print once at the end of the page.

 The Report Footer section generally contains the total page and other information
you want to appear only at the end of the page.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

5. Page Footer

 Objects placed in the Page Footer section print at end of the every page.

❖ SQL (Structured Query Language)

 SQL is a standard language for accessing and manipulate databases. OR


 SQL is a database computer language designed for the retrieval and management of data
in relational database. SQL stands for Structured Query Language.
 SQL is the standard language for Relation Database System. All relational database
management systems like MySQL, MS Access, Oracle, Sybase, Informix, postgres and
SQL Server use SQL as standard database language.

What is RDBMS

 RDBMS stands for Relational Database Management System. RDBMS is the basis
for SQL, and for all modern database systems like MS SQL Server, IBM DB2,
Oracle, MySQL, and Microsoft Access.

 A Relational database management system (RDBMS) is a database management


system (DBMS) that is based on the relational model as introduced by E. F. Codd.

What is table?

 The data in RDBMS is stored in database objects called tables. The table is a
collection of related data entries and it consists of columns and rows.3

 Remember, a table is the most common and simplest form of data storage in a
relational database.

What is field?

 Every table is broken up into smaller entities called fields. The fields in the
CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 A field is a column in a table that is designed to maintain specific information about


every record in the table.

What is record or row?

 A record, also called a row of data, is each individual entry that exists in a table.

+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+

 A record is a horizontal entity in a table.

What is column?
 A column is a vertical entity in a table that contains all information associated with a
specific field in a table.
 For example, a column in the CUSTOMERS table is ADDRESS, which represents
location description and would consist of the following:

+-----------+
| ADDRESS |
+-----------+
| Ahmedabad |
| Delhi |
| Kota |
| Mumbai |
| Bhopal |
| MP |
| Indore |

❖ SQL Queries

1) Select Query

 SQL SELECT statement is used to fetch the data from a database table which returns
data in the form of result table. These result tables are called result-sets.

Syntax:

SELECT column1, column2, columnN FROM table_name;

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 Here, column1, column2...are the fields of a table whose values you want to fetch. If
you want to fetch all the fields available in the field, then you can use the following
syntax:
.

SELECT * FROM table_name;

2) Insert Query
 The SQL INSERT INTO Statement is used to add new rows of data to a table in the
database.

Syntax:
 There are two basic syntaxes of INSERT INTO statement as follows:

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]


VALUES (value1, value2, value3,...valueN);

 Here, column1, column2,...columnN are the names of the columns in the table into
which you want to insert data.

 You may not need to specify the column(s) name in the SQL query if you are adding
values for all the columns of the table. But make sure the order of the values is in the
same order as the columns in the table. The SQL INSERT INTO syntax would be as
follows:

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

3) Update Query
 The SQL UPDATE Query is used to modify the existing records in a table.

 You can use WHERE clause with UPDATE query to update selected rows otherwise
all the rows would be affected.

Syntax:

 The basic syntax of UPDATE query with WHERE clause is as follows:

UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 You can combine N number of conditions using AND or OR operators.

4) Delete Query
 The SQL DELETE Query is used to delete the existing records from a table.

 You can use WHERE clause with DELETE query to delete selected rows, otherwise
all the records would be deleted.

Syntax:

 The basic syntax of DELETE query with WHERE clause is as follows:

DELETE FROM table_name WHERE [condition];

 You can combine N number of conditions using AND or OR operators.

❖ Working With Data Control

❖ Working with MS-SQL Server database


SQL Server is the product of Microsoft to working with database. Step to create SQL Sever
Database.

Go to solution explorer > Right click on website > select Add New Item > Select SQL
Database in Given Wizard > Give Suitable Name to Your Database and press ok button.

Sql server data base has extension .mdf.

❖ Database programming using Code [Write Code Here]

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

 What is Ajax
 AJAX = Asynchronous JavaScript and XML.
 AJAX is a technique for creating fast and dynamic web pages.
 AJAX allows web pages to be updated asynchronously by exchanging small amounts of
data with the server behind the scenes. This means that it is possible to update parts of a
web page, without reloading the whole page.
 Classic web pages, (which do not use AJAX) must reload the entire page if the content
should change.

 How Ajax works

When user first visits the page, the Ajax engine is initialized and loaded. From that point of
time user interacts with Ajax engine to interact with the web server. The Ajax engine operates
asynchronously while sending the request to the server and receiving the response from server.
Ajax life cycle within the web browser can be divided into following stages:
✓ User Visit to the page: User visits the URL by typing URL in browser or clicking a link
from some other page.
✓ Initialization of Ajax engine:
When the page is initially loaded, the Ajax engine is also initialized. The Ajax engine can
also be set to continuously refresh the page content without refreshing the whole page.
✓ Event Processing Loop:
* Browser event may instruct the Ajax engine to send request to server and receive the
response data
* Server response - Ajax engine receives the response from the server. Then it calls the
JavaScript call back functions

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

* Browser (View) update - JavaScript request call back functions is used to update the
browser. DHTML and css is used to update the browser display.

 Benefit of Ajax

 Ajax can be used for creating rich, web-based applications that look and works like a
desktop application.
 Ajax is easy to learn. Ajax is based on JavaScript and existing technologies like XML,
CSS, DHTML. etc. So, its very easy to learn Ajax.
 Ajax can be used to develop web applications that can update the page data continuously
without refreshing the whole page.

 AJAX is Based on Internet Standards

AJAX is based on internet standards, and uses a combination of:


✓ XMLHttpRequest object (to exchange data asynchronously with a server)
✓ JavaScript/DOM (to display/interact with the information)
✓ CSS (to style the data)
✓ XML (often used as the format for transferring data)
AJAX applications are browser- and platform-independent!

 Architecture of Asp.Net Ajax

Microsoft ASP.NET AJAX enables you to quickly create Web pages that include a rich user
experience with responsive and familiar user interface (UI) elements. ASP.NET AJAX
provides client-script libraries that incorporate cross-browser ECMAScript (JavaScript) and
dynamic HTML (DHTML) technologies, and it integrates them with the ASP.NET 2.0 server-
based development platform. By using ASP.NET AJAX, you can improve the user experience
and the efficiency of your Web applications.

ASP.NET AJAX Architecture

ASP.NET AJAX consists of client-script libraries and of server components that are integrated
to provide a robust development framework. In addition to ASP.NET AJAX, you can use the
ASP.NET AJAX Control Toolkit and the features in the ASP.NET AJAX Futures releases,
which are both community supported.

AJAX Client-Server Architecture

The ASP.NET AJAX server components basically consists of ASP.NET web server controls
and components to manage UI and and flow of an application, and to manage serialization,
validation, control extensibility.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

ASP.NET Web server controls:

1) ScriptManager : Manages script resources for client components, partial-page rendering,


localization, globalization, and custom user scripts.
2) UpdatePanel : Enables you to refresh selected parts of the page, instead of refreshing the
whole page by using a synchronous postback.
3) UpdateProgress : Provides status information about partial-page updates in UpdatePanel
controls.
4) Timer : Performs postbacks at defined intervals. You can use the Timer control to post the
whole page, or use it together with the UpdatePanel control to perform partial-page updates
at a defined interval.

ASP.NET AJAX Client Architecture

The ASP.NET AJAX client-script libraries be made of JavaScript (.js) files that provide
features for object-oriented development. The object-oriented features included in the
ASP.NET AJAX client-script libraries enable a high level of consistency and modularity in
client scripting. The following layers are included in the ASP.NET AJAX script libraries:
1) A browser compatibility layer. This provides compatibility across the most frequently
used browsers (including Microsoft Internet Explorer, Mozilla Firefox, and Apple Safari)
for your ASP.NET AJAX scripts.
2) ASP.NET AJAX core services, which include extensions to JavaScript, such as classes,
namespaces, event handling, inheritance, data types, and object serialization.
3) An ASP.NET AJAX base class library, which includes components such as string builders
and extended error handling.
4) A networking layer that handles communication with Web-based services and
applications, and that manages asynchronous remote method calls.
5) Support for JavaScript libraries that are either embedded in an assembly or are provided
as standalone JavaScript (.js) files. Embedding JavaScript libraries in an assembly can
make it easier to deploy applications and can solve versioning issues.
6) Support for accessing server-based forms authentication and profile information in client
script. This support is also available to Web applications that are not created by using
ASP.NET, as long as the application has access to the Microsoft AJAX Library.

 Working With AJAX Controls

Accordian
AutoComplete
Calender
Filtered Textbox

 Introduction to Web services

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

A web service is not a website that a human reads. It is not anything with which an end user
would directly interact. A web service is a standard platform for building interoperable
distributed applications. It allows you as a developer, to interact with other information
providers without worrying about what they are running either at the backend or even their
front-end.

What are Web Services?

1) Web services are application components


2) Web services communicate using open protocols
3) Web services are self-contained and self-describing
4) Web services can be discovered using UDDI
5) Web services can be used by other applications
6) XML is the basis for Web services

How Does it Work?

✓ The basic Web services platform is XML + HTTP.


✓ XML provides a language which can be used between different platforms and
programming languages and still express complex messages and functions.
✓ The HTTP protocol is the most used Internet protocol.
✓ Web services platform elements:
• SOAP (Simple Object Access Protocol)
• UDDI (Universal Description, Discovery and Integration)
• WSDL (Web Services Description Language)

What is SOAP?

SOAP is an XML-based protocol to let applications exchange information over HTTP.


Or more simple: SOAP is a protocol for accessing a Web Service.
• SOAP stands for Simple Object Access Protocol
• SOAP is a communication protocol
• SOAP is a format for sending messages
• SOAP is designed to communicate via Internet
• SOAP is platform independent
• SOAP is language independent
• SOAP is based on XML
• SOAP is simple and extensible
• SOAP allows you to get around firewalls
• SOAP is a W3C standard

What is WSDL?

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

WSDL is an XML-based language for locating and describing Web services.


• WSDL stands for Web Services Description Language
• WSDL is based on XML
• WSDL is used to describe Web services
• WSDL is used to locate Web services
• WSDL is a W3C standard

What is UDDI?
UDDI is a directory service where companies can register and search for Web services.
• UDDI stands for Universal Description, Discovery and Integration
• UDDI is a directory for storing information about web services
• UDDI is a directory of web service interfaces described by WSDL
• UDDI communicates via SOAP
• UDDI is built into the Microsoft .NET platform.

Why Web Services?

1) Interoperability has Highest Priority


2) Web Services take Web-applications to the Next Level
3) Web Services have Uses of – Connect Existing Software

 CREATING AND USING WEB SERVICES

PREREQUISITES : Microsoft Internet Information Services (IIS) installed locally on your


computer.

STEP TO CREATING A WEB SERVICE UNDER THE IIS ROOT

1. Open Visual Web Developer.


2. On the File menu, click New Web Site.
The New Web Site dialog box appearxs.
3. Under Visual Studio installed templates, click ASP.NET Web Service.
4. Click Browse.
5. Click Local IIS.
6. Click Default Web Site.
7. Click Create New Web Application.
Visual Web Developer creates a new IIS Web application.
8. Type the name TemperatureWebService.
9. Click Open.
The New Web Site dialog box appears, with the name of the new Web site in the
rightmost Location list. The location includes the protocol (http://) and location
(localhost). This indicates that you are working with a local IIS Web site.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

10. In the Language list, click the programming language that you prefer to work in.
The programming language that you choose will be the default for the Web site.
However, you can use more than one language in the same Web application by creating
pages and components in different programming languages. For more information
about how to create components using different languages.
11. Click OK.
Visual Web Developer creates the new Web service and opens a new class named
Service, which is the default Web service. However, in the following procedure you
will create a new Web service with a specified name and you will not use the Service
class.
12. Close the Service class.

WRITE A FOLLOWING CODE

<System.Web.Services.WebMethod()> _
Public Function FahrenheitToCelsius(ByVal Fahrenheit As Double) _
As Double
Return ((Fahrenheit - 32) * 5) / 9
End Function

<System.Web.Services.WebMethod()> _
Public Function CelsiusToFahrenheit(ByVal Celsius As Double) _
As Double
Return ((Celsius * 9) / 5) + 32
End Function

TO TEST THE WEB SERVICES

1. In Solution Explorer, click Service.asmx, and then press CTRL+F5.


The Web service is invoked and a page appears in the browser that shows the
methods that are exposed by the Web service.
2. Click CelsiusToFahrenheit, which invokes that method.
A page appears that prompts you for parameter values for the CelsiusToFahrenheit
method.
3. In the Celsius box, type 100, and then click Invoke.
A new window appears that displays the XML that the Web service returns when the
CelsiusToFahrenheit method is invoked. The value 212 appears in the XML.
4. Close the browser that contains the method results.
5. In the original browser, click Back to return to the list of methods.
6. Click FahrenheitToCelsius and test to make sure that the method is returning the
results that you expect.
If you type 212, the FahrenheitToCelsius method will return 100.
7. Close the browser.
You have finished creating the Web service; the next step is to use it.

TO CREATE A WEB SITE TO USE THE WEB SERVICES

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

1. On the File menu, click New Web Site.


2. Under Visual Studio installed templates, click ASP.NET Web Site.
3. Click Browse.
4. Click Local IIS.
5. Click Default Web Site.
6. Click Create New Web Application.
Visual Web Developer creates a new IIS Web application.
7. Type the name TemperatureWeb.
8. Click Open.
9. In the Language list, click the programming language that you prefer to work in.
10.Click OK.

Visual Web Developer creates a new local IIS Web site and a new page named
Default.aspx.

ADDING THE WEB SERVICES AS A COMPONENT

To create a reference to the Web service


1) On the Web Site menu, click Add Web Reference.
The Add Web Reference dialog box appears, as shown in the following screen shot.
Add Web Reference dialog box

2) In the URL list, enter the following URL for the Web service, and then click Go
http://localhost/TemperatureWebService/Convert.asmx
When Visual Web Developer finds the Web service, information about the Web
service appears in the Add Web References dialog box.
3) Click one of the method links.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

The test page for the method appears.


4) Click Add Reference.

Visual Web Developer creates an App_WebReferences folder and adds a folder to it


for the new Web reference. By default, Web references are assigned a namespace
corresponding to their server name (in this case, localhost). Make a note of the name
for the Web reference namespace. In the folder, Visual Web Developer adds a .wsdl
file that references the Web service. It also adds supporting files, such as discovery
(.disco and .discomap) files, that include information about where the Web service is
located.

You can now use the Web service. In this walkthrough, you will add controls to
Default.aspx, and then program the controls to convert a specified temperature to both
Fahrenheit and Celsius. When the page is running, it will look something like the
following illustration.
Temperature conversion page

To call the Web service methods


1) Open the Default.aspx page and switch to Design view.
2) From the Standard group in the Toolbox, drag the following controls onto the page and
set their properties as indicated:

Control Properties
Textbox ID: TemperatureTextbox
Text: (empty)
Button ID: TemperatureTextbox

Prepared BY : - Prof. Nirav S. Shukla (CPICA)


ASP.NET

Text: (empty)
Label ID: FahrenheitLabel
Text: (empty)
Label ID: CelsiusLabel
Text: (empty)
3) Double-click ConvertButton to create an event handler for its Click event.
4) Make sure your event handler code matches the code in the following example.

Dim wsConvert As New localhost.Convert()


Dim temperature As Double
temperature = System.Convert.ToDouble(TemperatureTextbox.Text)
FahrenheitLabel.Text = "Fahrenheit To Celsius = " & _
wsConvert.FahrenheitToCelsius(temperature).ToString()
CelsiusLabel.Text = "Celsius To Fahrenheit = " & _
wsConvert.CelsiusToFahrenheit(temperature).ToString()

5) Press CTRL+F5 to run the page.


6) In the text box, type a value, such as 100, and then click Convert.

The page displays the result of converting the temperature value into both Fahrenheit
and Celsius.

Prepared BY : - Prof. Nirav S. Shukla (CPICA)

You might also like