Anda di halaman 1dari 261

Naga Raju Sri Sai Ram

ASP.Net --

Naresh Tech. Class Notes Hari Page1

ASP.Net Class Note Book (Naga Raju Sir)
Dt: 29-03-2010
ASP.Net:- Active Server Page for .Net. Its a part of .Net
ASP.Net is a Server-side Technology.



What is .Net?
.Net is a Framework, which is collection of libraries and Runtime.
More over all languages can use these libraries.
Why .Net?
To develop different types of applications any type of applications can be
developed today in .Net.
Ex:-
Command Line
Windows
Web
Mobile
Games
SOA
Embedded
Cloud computing Applications.
.(all types of applications)
All types of applications in a unified model-similar development style.
More over all languages can be usingthese libraries.
Sun java does not used to .Net
Today 40 + languages support .Net languages.
wikipedia.org
30,000 + languages / classes + all old languages components also.
Microsoft recommended or prepared languages are C# & VB.Net
Every .Net language is designed to consume .Net libraries and produce code for
CLR(Common Language Runtime).
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page2

Unlike older languages have their own libraries and own runtime.
C - Own libraries own runtime.
C# - No Libraries - No Runtime.
(C# has no Libraries and no runtime because its have .Net languages and
CLR because .Net is designed for multiple languages).
.Net + Favorite language =Application (Any type of applications).
ASP.Net + Favorite language = Web Applications.
(Part of .Net)

Important Points:

Why. Net?
What .Net languages are?
What is ASP.Net? Why?









*** END OF THE DAY ***



















Dt: 30-03-2010
.Net + Language = Application
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page3

ASP.Net + C# = Web Application
What are web applications?
Applications that develop with open standards and which are hosted in a public
network are called Web Applications. Any user how logs on to this public
network can access web applications no need of installing any software for
accessing this type of applications, in other words web applications are
universal applications.
The other types of applications that we have are desktop applications, which
are called standalone applications. Desktops are more rich in features like
performance, security, user interface, etcBut they are accessible locally web
applications are by default lowing features but accessible everywere. Today
most of the application development is web development, because of
accessibility.

While developing web apps programming remains same or with little changes
but of their architecture/ concept they are universal.
What is that concept or architecture or setup?
Web architecture are infrastructure is involved with following:
1. Server Model of Operating System.
Server: - A program which is return to serve requests and to manage resources
effectively for multiple users is called server program.
Ex:-DB Servers, Operating System, Application Servers, Integration Server.
Client:-A program which is return to make requests and gets results or which
is written to run as standalone is called Client Program.
Ex:- windows XP, MS-Office, Inventory packages.
i. For web some Operating System suitable.
Windows Server 2003
Windows Server 2008
Linux Server.
Solaris Server.

2. Web Server
- It is software which as a service under operating system and which
contain one or more web applications.
- Ex:-IIS, Apache
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page4


- All web servers take request only from their client softwares.
- HTTP-Hyper Text Transfer Protocol.
- Protocol is a set of rules, itsnot software.




Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page5


Note:-Google run in any application, we give HTTP request then we responded it.
Because of this HTTP Protocol web applications are universal, any device and
any OS can request web app and get results. All that they have to do is write a
program which generates request in the form of HTTP or use a tool which can
generate HTTP request for them like Browser.



*** END OF THE DAY ***


























Dot:02-04-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page6

Server Model of Operating System.
Web Server One or more web sites.
Browser.
HTTP

Note: -Symbol---OS will be using all mobiles.
1. Windows server 2003/2008.
- For standalone development any OS that supports a web server installation
can be use like,
Windows XP Professional
Windows Vista Ultimate.
Windows 7 Ultimate.
- It we are used it.
Windows XP Home/ Vista home/ 7 Home.Not used it.
To find which OS we are currently running go to Start run winder OK.
2. Web Server.
For ASP.Net development we need Microsoft web server called IIS.
(IIS Internet Information Services).
The latest version of IIS is 7.0
Every OS by default supports one version of IIS as its web Server.\
- Ex:- windows XP IIS 5.1(outdated)
- Windows Vista/ 7/ Server 2008
- IIS 7.0 (Recommended)
We have to install IIS in non-Server based OS like XP, VISTA & 7.
With server like 2003/2008 IIS is installed automatically.
To check whether IIS is currently running or not open Browser & type
http://localhost (or) http://<systemname>

My Computer computer name (properties).
Result: - if a welcome page or some message showing about IIS is display then
the server is running otherwise we need to check or install IIS.

(Q). How to install IIS?
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page7

Control panel Add/Remove programs Add/Remove Windows Components
select IIS.
After we select IIS & click next asked OS cod.
(Q). How to create a web site?
Once IIS is installed go to control panel Administrative Tools Internet
Services Manager (or) Internet info Services.
Start this program & we will get IIS console.
Select default web site (right click) & choose New Virtual Directory.
Enter Virtual Name (site name) followed by physical directory in the display
window.

Result: - the site is created.







*** END OF THE DAY ***





























DT: 03-04-2010
Explore the .Net Framework:
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page8

The .Net framework allows developers to use the same set of skills to rapidly
build great applications fort he web, devices services & more.
1. Windows 7 Ultimate
About IIS?
www.IIS.Net ----Download IIS6
Note: - For window XP Operating System we can separately download recognize
version if IIS today.
2. To Install IIS7 in vista / Win 7?
Control panel program & features turn windows features on or off open
a new window select IIS (Internet Information Service).
Note: - Select all options on (+) IIS

Select IIS along with all its Sub-options.
3. To create website under IIS7.


When we create website we provide 2 entries,
a. Virtual Directory.
- Which is the site name of users, only IIS or Web servers will be aware of this
Name.
b. Physical Directory.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page9

- This is the content directory where developer writes programs and saves
them. These are only accessed by users from virtual name.
One reason to provide 2 different names is for security, users will not be of
content directory.

Website is a collection of websites.
Programming the Web:-
Once website is created we can start writing programs which will be requested
by website users. Programming in web is different then a normal language
programming. We have use different languages to prepare a single page out put.
Some languages among these are compulsory which means we have to use the
specified language only for programming.
A website is collection of web pages, to design a webpage using ASP.Net we need
the following languages:
HTML(Hyper Text Markup Language)
JavaScript(client side scripting Language)
ASP.Net with C# / VB.Net/ (Server side Scripting Language).
HTML + JavaScript + ASP.Net =Web Page.
1. HTML: -
For web application client are Browsers, most of the web apps 90% + are
accessed using Browsers only. All Browsers understand only HTML for
inputs & outputs.
HTML is not a powerful language for programming- it provides few tags
using which we can take inputs as well produce outputs.
HTML cannot provide any functionality which means we can design static
content or non-interactive content.
The only advantage with HTML is with very few tags we can produce good
design.
Conclusion: Using HTML alone we cannot design todays wanted dynamic web
pages.
Sample HTML program along with its Structure:
We can use any simple text editor like notepad to write HTML program.
<Html >-------------------its root tag its can't repeated.
Every program has to two tags.
1. Head tag
2. Bottom tag (or) closing tag.

<head></head>---------outside world information.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page10

<body></body>---------presentation.
<html>
<head><title>Demo web app</title></head>
<body>
<h1>Welcome to web Application</h1>
<h2>Demo HTML Program</h2>
</body>
</html>
Virtual directory cannot shows.
Physical directory can be shows.
Then we save it Demo.html in physical directory(yahoo).
Virtual directory can be use IIS server only.
Run Demo.html
http://loaclhost/yahoo/demo.html
Note:-
http : protocol
localhost : it is a current system
yahoo : is website
demo.html : is program


















*** END OF THE DAY ***










Dot: 05-04-2010
Authentication Required: - Message that is getting displayed.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page11


IIS is installed & when we go to default website status is error or not
started?
Ans:-Every Service in operating system will use one port no(1-65536) for
its location.
The default port no. of web server is 80.
There might be a port no clash.
1. Stop existing web server. (or)
2. Change port no. of existing web server (or)
3. Change port no of IIS.
1. Stop existing Web Server.

---------------------------------------------------------------------------------------------------

2. How to change the IIS port no?
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page12


If IIS port no. is changed from 80 to other no. then we most specified port No.
also.

If we dont given the new port no. it will be taken default port no. 80
--------------------------------------------------------------------------------------------------
IIS .NET
For html/JavaScript (www.w3schools.com)
For ASP.Net BOOKUnleashed ASP.Net --- Stephen Walther(Author)
Sitehttp://www.asp.net (official site)
In this side we have videos/articles/ demos
One are more (alternative site)--- www.codeproject.com
Class room slides & some articles http://nbende.wordpress.com
(for NIT students).
HTML Forms:-
In HTML all graphical elements are designed as form elements. If we want to
create this graphical element then we must write <form>tag followed by
graphical elements like Button, Checkbox, radio button etc
Form is the important media of communication b/w client & server. When we
submit the form all form elements will travel to server.
To create a Button we use,
<input type=button name=b1 value=demo>
Here type means the control that we want.
Name is to refer programmatically.
Value is for appearance.


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page13

Example:-
<html>
<head><title>Forms Demo</title></head>
<body>
<h1>HTML Forms Example</h1>
<form name=frm>
UserName <input type=text name=t1>
<br>
Email id <input type=text name=t2>
<br>
<input type=button name=b1 value=Add>
</form>
</body>
File save as C# ShopApplication(ShopSite1) that ---demo.html
http://localhost/shopsite1/demo1.html (or)
http://nit/shopsite1/demo1.html

http://nit10/virtualdirectory/programname









*** END OF THE DAY ***



Dot: 06-04-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page14

Resources in web Applications: -

In web application when we refer a file from any of the program. Then the
referred file is called as resource. When we consume this kind of resource they
must be present in our project only or our directory only. We must not specified
nay c:/ or d:/ & soon the only alternate is we can use publicly accessible URL
(Uniform Resource Located).
Since URI = Uniform Resource Identifier.
<img name=m1 src=hai.jpg>
(Q). what is the directory structure of your project?
Ans: - We have categorized out content into following folders explain each folder & its
content.

SCRIPTING:
(Q).Why Scripting?
Ans:-using HTML alone we can design Non-interactive & static pages. If we want
pages we must add scripting support to it i.e., to HTML.
HTML + Scripting = Dynamic Web Page.
Scripting is divided into two forms,
1. Client side Scripting
2. Server side Scripting
(Q).What is Client side Scripting? *******
A program which is written for any other source is called script, unlike other
programs where we write independently also execute then as standalone.
Code that is executed or written to run as standalone is called program.
Code that is written for another source is called Script.
Client side script means which will be executed by an interpreter present in
Browser. Browser means nothing but client.



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page15


(Q). What client side scripts reside?
Ans:-@ Server Only.
(Q).What is Server side Scripting?
All scripts that are executed @ server using server resources is called Server
side script.

(Q).How to write client side scripting & which scripting language is preferred?
Ans: - In HTML we have <script> tag to write client side scripting. This tag indicates
Browser that we are writing code & needs to be executed with interpreter.
- Language =<language> or
- Type=<text/language> is an attribute of script tag to specify particular
language.
- We must close the opened script tag otherwise all content will be taken as
script only.
- Inside <script>tag we must write only relevant language code but not any
other code.
Ex: - <script type=text/javascript>
js code
</script>
Example:-1.<html>
<head><title>JavaScript Demo</title></head>
<body>
<h1>Java Script Demo</h1>
<h2>This is HTML</h2>
<script language=javascript>
Document.Write(this is javascript);
</script>
<h2>Back to HTML</h2>
</body>
</html>
Output:-

Example:-2.<html>
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page16

<head><title>JavaScript Demo</title></head>
<body>
<h1>Java Script Demo</h1>
<h2>This is HTML</h2>
<script language=javascript>
Document.Write(<h1>this is javascript</h1>);
</script>
<h2>Back to HTML</h2>
</body>
</html>
Output:-

Example:-3. <html>
<head><title>JavaScript Demo</title></head>
<body>
<h1>Java Script Demo</h1>
<h2>This is HTML</h2>
<script language=javascript>
<h1>This is also JavaScript</h1>
Document.Write(this is javascript);
</script>
<h2>Back to HTML</h2>
</body>
</html>













*** END OF THE DAY ***



Dt: 07-04-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page17

JavaScript is the most recommended client side scripting language for any type
of web application.
All browsers today that support interpreters for client side scripting support
JavaScript as their scripting language.
Firefox: Support JavaScript.
Safari: Support JavaScript.
( Firefox, safari both are web Browsers).
Internet Explore: JavaScript+VBScript+Jscript+
The best web application is which runs on all browsers same.
Java Script is open source & free.

Good on Java Script:-
Java Script can perform any client side activity.

Not Good on Java Script:-
Its not user friendly (it is not easy to develop).
Weak typed System(Data type system is very weak).
int a; var a;
a=Hello; a=10; //int
b=true; //bool
c=hello; //string
d=a+10; //20(a is integer a=10)
d=a+10; //1010
d=a+b; //11
d=b+c; //truehello

All JavaScript concerns (not good issues) are intentional. This weak support to
minimize the execution time by keeping the interpreter size very small*******.
With very less amount of memory JavaScript can run its code. To mobile
Browsers also have JavaScript is only the proof for our discussion.
---------------------------------------------------------------------------------------

Method-2:- Writing JavaScript.

To write JavaScript code in the form of functions.
int Add(int a, int b) function Add(a,b)
{ {
return Hello;
(or)
} return a+b;
}
- No return type.
- We can return any value.
- Arguments can be declared.
- But with no data types.
- Can take any type of values.

Ex:- If we write code in the form of function then it should be explicitly called. (Unlike
our first JavaScript program which executed without any call).
Example-1:-
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page18

<html>
<head><title>JavaScript Demo</title></head>
<body>
<h1>Java Script Function</h1>
<script language=javascript>
function simple()
{
Document.Write(<h2>javascript output</h2>);
}
</script>
<h2>Back to HTML</h2>
</body>
</html>
Output:-

Example-2:-
<html>
<head><title>JavaScript Demo</title></head>
<body>
<h1>Java Script Function</h1>
<script language=javascript>
function simple()
{
Document.Write(<h2>javascript out put</h2>);
}
Simple(); //call function
</script>
<h2>Back to HTML</h2>
</body>
</html>
Output:-




Example-3:-
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page19

<html>
<head><title>JavaScript Demo</title></head>
<body>
<h1>Java Script Function</h1>
<script language=javascript>
function simple()
{
Document.Write(<h2>javascript out put</h2>);
}
</script>
<h2>Back to HTML</h2>
<script language=javascript>
simple();
</script>
</body>
</html>
Output:-







*** END OF THE DAY ***

















Dt: 08-04-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page20

Method-3:-Writing JavaScript in the form of events.
(Q). what is an Event?
Ans:-It is an action, which is raise by the object based on its behavior. For example
Button is an object and click is one of its Events. This event is fired when user click on
the button. Similarly Mouse Enter, Mouse Leave, Double click are all events for button
some other object.
Every language or package that provides Graphical Programming will support
Events and Every language supports in different way of implementing Events.
JavaScript also supports Events and Event Handling concepts. In JavaScript
Events are provided as function pointers. Which means every Event that we use
is a pointer &requires to be mapped with function.


Ex: - private void button1_Click(object sender e)
Objects are predefined.
Events are predefined for objects.
Our job is to write functions & Map Event to function.
(Q). Why calls the Event or function?
An object only calls the event & event invokes the function. In JavaScript we can
write Events in 2 ways:
1. In side HTML Tag as an attribute, no separate script tag & others are required
for handling Events in this Method.
2. Writing Events inside script tag using JavaScript Syntax like,
object.Event=<fn>
<input type=button name=b1 value=ok onclick=f1()>
Since.b1 is object, onclick is Event, f1 is function
Ex:-1: <html> demo1.html
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page21

<body>
<h1>JavaScript Events</h1>
<form name=frm>
User Name<input type=text name=t1>
<br>
Emain Id<input type=text name=t2>
<br>
<input type=button name=b1 value=Submit onclick=ShowMsg()>
<script language=JavaScript>
function ShowMsg()
{
alert(Thank you for Submitting);
}
</script>
</form>
</body>
</html>
OutPut:-

--------------------------------------------------------------------
Ex:-2: <html>
<body> demo2.html
<h1>JavaScript Events</h1>
<form name=frm>
User Name<input type=text name=t1>
<br>
Emain Id<input type=text name=t2>
<br>
<input type=button name=b1 value=Submit onclick=ShowMsg()>
<input type=button name=b2 value=Help onclick=ShowHelp()>
<script language=JavaScript>
function ShowMsg()
{
alert(Thank you for Submitting);
}
functionShowHelp()
{
alert(Sorry No Help);
}
</script>
</form>
</body>
</html>
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page22

OutPut:-

Note: - Objects---2
Events--- 2
Functions---2
Since Help has one event the is onclick(ShowHelp)
Since Submit has one event the is onclick(ShowMsg)

Multiple Events can point to single function.
Reason:-Events are points to functions & multiple pointers can point the single
function.

Ex:-3: <html>
<body> demo3.html
<h1>JavaScript Events</h1>
<form name=frm>
User Name<input type=text name=t1>
<br>
Emain Id<input type=text name=t2>
<br>
<input type=button name=b1 value=Submit onclick=ShowMsg(Welcome)>
<input type=button name=b2 value=Help onclick=ShowMsg(No-Help)>
<script language=JavaScript>
function ShowMsg()
{
alert(x);
}
</script>
</form>
</body>
</html>
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page23

OutPut:-

Note: - Objects---2
Events--- 2
Functions---1
We can call functions with different objects and different events also. They need
not be similar object/similar events.
To write multiple Events for single objects just write it another attribute i.e.,
provide space after one event and write another event.
Ex:-4 <html>
<body onload=ShowMsg(10)> demo4.html
<h1>JavaScript Events</h1>
<form name=frm>
User Name<input type=text name=t1>
<br>
Emain Id<input type=text name=t2>
<br>
<input type=button name=b1 value=Submit onclick=ShowMsg(Welcome)>
<input type=button name=b2 value=Help onclick=ShowMsg(No-Help)
onmouseover=ShowMsg(cannot-click-Me)>
<script language=JavaScript>
function ShowMsg()
{
alert(x);
}
</script>
</form>
</body>
</html>
OutPut:-

Note: - Objects---3
Events--- 4
Functions---1

*** END OF THE DAY ***
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page24

Dt: 09-04-2010
Method-4 of Java Script:-
WritingJavaScript in a separate .Js file.
By default we are writing JavaScript & HTML in a single file. That means design
& code combined. This increases complexity of writing program& more difficulty
in debugging the program. For small program we can write single file but for big
programs have to separate them. JavaScript provides this option by allowing
users to write code in a separate .Js file. That is with extension .Js. In side .Js
file we must write only JavaScript statements not event script tag & other tag.
Inside HTML file we have to write script tag with SRC attribute pointing to .Js
file.

Reduces the complexity of writing code & design.
Reuse this .js file in other HTML files.
Note:-
1. <script language=javascript src=menu.js>
2. <script language=javascript src=jquery.js>
3. window.document.form1.textbox1.Value=100;
$find (textbox1).value=10
S.value=10;
Note:-When we have multiple.js files them we must write multiple <script src>tag.
code.js, menu.js, test.js
JavaScript DocumentObjectModel(DOM)-(JavaScript DOM):-
DOM Specification is provided by W3 Community.
W3C World Wide Web community.
DOM specification is provided by W3 for accessing all hierarchical elements.
HTML, XML, WSDL, etc are Hierarchical only.
All languages follow DOM specification for accessing HTML elements.
According to DOM we must first load all the elements into memory. These
loaded elements are referred as Documents.
Once documents is prepared different Objects must be provided to access the
loaded elements are referred as documents.
Once Document is prepared different objects must be provided to access the
loaded element.
Using JavaScript can access can access & modify many of the objects in a
document.
Containment Hierarchy of document objects.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page25


The above functions all are objects.Ex: - frame, documents,..checkbox.
Example:- <html>
<body>
<h1>Java Script DOM</h1>
<form name=frm>
<img name=m1, src=coworker.jpg>
<br>
UserName<input type=text name=t1>
<br>
<input type= button name=b1 value=Demo onclick=f1()>
<script language=javascript>
function f1()
{
window.Document.frm.t1.value=very Good;
document.m1.src=children.jpg;
}
</script>
</form>
</body>
</html>
i. <img name=m1, src=coworker.jpg onmouseover=f1()>
(iia). <img name=m1, src=coworker.jpg onmouseover=f2()>
(iib). function f2()
{
window.document.from.t1.value=
document.m1.src=cowork.jpg;
}
(f2() function will be write after the function f1())





*** END OF THE DAY ***




Dt: 10-04-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page26

Current version of HTML is XHTML 1.0 (in before 1.0/2.0/3.0/4.0/then after
XHTML 1.0).
DOM Versions
Timer in JavaScript
Table/Div Tags in HTML
1. DOM Versions:-
The first release of DOM is called version 0. This version is supported by all
Browsers. Next DOM version 1 & version 2 are also release to simplify
JavaScript, apart from that many new features are also added DOM version 2 is
not supported by the current Browsers.
Maximum support for 1 & minimum support for 2 is provided by latest
Browsers one of the important features in DOM version 1 is to get the element
reference based on its ID (or) Name.

document.frm.t1.value
var x=document.getElementById(m1);
x.src=;
Very simple to use.
No need to follow the hierarchy.

2. Timer in JavaScript:-
(Q). what is a Timer?
It is a component, which executes code at regular intervals. Its run this
as a support process.
In javaScript there is no Timer object but there is a method called
setTimeout(<fn>,<interval>). This function executes the given function
after the elapsed intervals.
setTimeout(f1,1000) //this is not Timer
f1();

function f1()
{ //acts like a timer
--------------------
--------------------
--------------------
--------------------
setTimeout(f1,1000);
}
---------------------------------------------------------------------------------
3. Div & Table Tags in HTML:-

One of the important issues while placing controls in web page in their
position. In HTML to accurately place element we use <div> or <table>.
<div> is like a container for other controls & can be used to place based
on x, y positions of Browser.
<table> is for tabular presentation of data. i.e., Rows/Columns.
<div>or <table> or <div>+<table>.


Ex:- animate.html
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page27

<html>
<head>
<title>JavaScript animation:Demo</title>
<script language="javascript">
var x=null; //object
function doMove(){
x.style.left=parseInt(x.style.left)+1+'px';
setTimeout(doMove,50);
}
function init(){
x=document.getElementById('xObject');
x.style.left='10px'; //set is initial position to 10px
doMove(); //start animating
}
window.onload=init; //2
nd
method java script events
</script>
</head>
<body>
<h1>javascript animation:Demo</h1>
<div id="xObject" style="position:absolute">
Hello
<img name=m1 src="a11.jpg" onclick=f1()>
</div>
</body>
</html>
Out Put:-


*** END OF THE DAY ***
Dt: 15-04-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page28

Server Side Programming: -
Programming that is executed @ server using server resources are called server
side programs.
ASP.NET provides good Server side environment for running programs. ASP is
classical development which was also used to server side programming.
ASP.NET is .NET based development.
ASP is COM based development (Unmanaged).
(Q). Does .NET support ASP Execution?
Ans: - YES. When we install .NET apart from base class Library (BCL) & CLR two more
engines called ASPX Engine & updated ASP Engine is installed.

ASPX engine is for executing ASP.NET programs. Its classed as worker process
which manages the entity ASP.NET page execution & provides results to clients.
ASP last version is 3.0 & .NET provides updated ASP engine which is more
bettor than ASP 3.0 execution for running ASP programs.
(Q). Can ASP & ASP.NET programs communicate with each other?
Ans:-No. They are different runtimes even through provided by .NET.



(Q). How a program is identified as server side program / aspx program / asp program or
PHP program.?
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page29

Ans: - Based on file extension*. Handlers are programs that reside with server & are
responsible to redirect the file to its related process / engine. All Handlers are based
on extension.



(Q). How to write an asp/aspx programs? What these programs can have?
Ans: -We can use any Simple editor like NOTEPAD for writing aspx programs. For RAD
(Rapid Application Development) we can use many tools available for developing aspx
applications like word class VS.NET, MS Expression, Dreamweaver etc
Inside a program we can write html, JavaScript & aspx code. Aspx engine will
parse only aspx code & process it. Rest all will be redirected as it is.
(Q). How Engine will parse only aspx code&process it.Rest all willbe redirected as it is?
Ans:-We have to write aspx code in a separate block <% %>
==== > called server side block.
Ex:-
<html>
<head><title>ASPX Demo</title></head>
<body>
<h1>Welcome to ASPX Programs</h1>
<%
Response.Write(This is ASP.NET output)
%>
<h2>Back to HTML</h2>
</body>
</html>

File SaveAs demo.aspx
http://localhost/shopsite/demo.aspx
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page30



Since demo.aspx called to (or) go to .net
In program <%..................%> in that particular part will be taken server,
Remaining part will be go to client.
<%...........%>it will betaken to server, executed that & after Result sent to
client.
Open view Source. (source will be changed)
OUTPUT:-

Ex:
(i). <%
<H!> that is HTMLH!>
Response.Write(This is ASP.NET output)
%>
(ii). Save As as demo.aspx to demo.html
(iii). Remove <%........%>part and Save as demo.aspx








*** END OF THE DAY ***



Dt: 16-04-2010
Developing ASPX applications using IDE Environment:
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page31

One of the feature or more advantage with ASP.NET & also .NET is they have
their own integrated development Environment.
We have 2 IDE for writing .NET programs,
1. Visual Studio .NET
2. Expression Suite.
Visual Studio .NET is a world class & the most leading Development
environment to, today it has every option that any critical project means,
staring from developing application, debugging application, testing Application,
deploying application.
Apart form this Microsoft provides expression suite that includes some
softwares like, expression web, expression Blend, Expression Media & few
more all these are provided by Microsoft for designing application with good
graphics & media.
We need not depend on softwares from other Benders like Photoshop,
Dreamweaver, Corel Draw, etc...which are good in designing, but doesnt
understand .NET
The Current version of .NET is 4.0 & the relevant Visual Studio IDE is Visual
Studio 10.0 also known as Visual Studio 2010.
.NET 3.5SP1 is the previous version of .NET & Visual Studio 9.0 also called
Visual Studio 2008, is used in developing application.
One of the important features of .NET is Multi targeting .NET framework. This
feature of .NET allows user to target any .NET framework staring 2.0 still 4.0
(Q). How to create aspx application using Visual Studio 2010?
Ans: -
Start a new website using File New website option.
Lot of templates in the window Select ASP.NET empty website. This
templatedoesnt create any file in the project except a Configuration file
called web.config
We have another template called asp.net website which by default
creates some pages along with Security added to our project.
More importantly when we start a new website we have an option to
select the target framework which is a very important entry.
Microsoft.com/azure
--- Operating System(O/S) on clouds

In Visual Studio .Net aspx page is called webform.
Add new item webform (aspx page).
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page32

Design the page using intelligence & execute it using start button. We
can also use Design view in the bottom of Screen to get WYSIWYG
approach.
WYSIWYG means What You See It What You Go
(Q). What Start Button does?
Ans: - Starts a new Browser & types the URL of the page as a request & gets the result.















*** END OF THE DAY ***














Dt: 17-04-2010
Cassini isa StandaloneServer (Independent).
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page33



Problem: - XML page cannot be displayed cannot view XML input using XSL style
sheet.
Solution: -Go to VS.NET command prompt & type ASPNET_REGIIS -i
VS.NET provides web development server (Cassini) which makes a programmer
to develop application in a standalone environment.
Independent of IIS & other Extensions.
Cassini is provided along with VS.NET installation only. (web
dev.webserver.exe file name)
Web Location in VS.Net New website template:
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page34

This entry specifies what type of server or location we have to use our
application.
HTTP we want to develop using IIS for this IIS should be running for
Vista\7\ server 2008 uses we must run visual studio in administrator mode.
File System: -
We want develop website using VS.Net in build Cassini web server. We can start
normally and our Virtual directory, Physical directory will be only one.
Whatever location we give that only because our directory.
If Visual Studio closed then Cassini be closed.
(Q). Is there any indication of Cassini Running?
Ans: - Yes. It shows an icon in system tray with title ASP.NET Web Development
Server.
Webdev.WebServer.exe 2234 bytes/ 3123 bytes Unable to connect with
ASP.Net web Development Server.
Solution-1: - Run antivirus program which cleans this file Defends.
Solution-2: - Del webdev.websrever.exe
Copy the same file from some other working system to your System.










*** END OF THE DAY ***























Dt: 19-04-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page35

Working with ASP.NET Controls: -
Normally web application interface is developed using HTML Controls. These
Controls are not highly feature oriented as well as doesnt provide project
requirements. To make application development simple one support that
ASP.Net provides is its controls. ASP.Net Controls are more featured controls &
fulfill most of the project task.
The following are main differences& also reasons for using ASP.NET controls
over the common HTML controls.
Reason-1: Simplified Controls.
Every ASP.NET control is design in user friendly manner. Which makes every
level of user produces good outputs.


Reason-2: Exclusive set of Controls.
HTML controls are hardly 10+ where are ASP.NET controls are around 100 &
most of the controls are highly features we do not have any HTML equalent to
perform those control tasks.
Ex:-1

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page36



Reason-3: Smart Controls (or) intelligent Controls.
Browser understands only HTML controls but not ASP.NET controls. So every
ASP.NET control after completing its processing at server, it gos another
process called Rendering.
What is Rendering?
Ans: - the process of converting ASP.NET states in to HTML (or) Browser
understandable format is called Rendering. This Rendering will be done
based on the type of client who makes the request.
Reason-4: Better State Management:
All web application are stateless & stateless means where every request is
identified as a new request. To day applications need high level state
management. Which is perform with lot of code/logic. All ASP.Net controls are
provided which state Management code. Which means ASP.NET controls are
State-full& Repair their values during round trips mode between client &
Server.
Reason-5: RAD Method of Development.

(Q).Which Controls are processed faster when we use them in our project.
HTML/ASP.NET Explain?
Ans: - No Rendering --- HTML Will be Processed faster.





*** END OF THE DAY ***

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page37

Dt: 20-04-2010
Writing Code for ASP.NET Controls:-
For HTML controls the only choice we have to write code using JavaScript.
For ASP.NET controls we can write code using JavaScript as well as using
C# at server side. Most of the coding is done at server side for ASP.NET
Control. We write the server side code using event of ASP.NET controls.
Once we write code at server side for an ASP.NET control then, when client
submit the form to server code is executed. For any reason if we cannot
submit the form then server side code will not be executed.
Another important point is when form is submitted to server it checks all
the control events & executes the relevant or fired events.

Create a new web form default.cs
Default.aspx(design)


Then we select View button and double click that button write following code:
- protected void Button1_click(object sender EventArgs e)
{
if(checkBox1.Checked)
Label1.Text=TextBox1.Text+is Employed;
else
Label1.Text=TextBox1.Text+is not Employed;
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page38

}
// we remove above if condition code part and write same code billow checkbox area.
And Add one more checkbox & Label in the above design part.
protected void CheckBox1_click(object sender EventArgs e)
{
if(checkBox1.Checked)
Label1.Text=TextBox1.Text+is Employed;
else
Label1.Text=TextBox1.Text+is not Employed;
}
protected void CheckBox2_click(object sender EventArgs e)
{
if(checkBox2.Checked)
Label2.Text=TextBox1.Text+C# .Net;
else
Label2.Text=TextBox1.Text+Not in C#.Net;
}
select Employ goto properties AutopostBack = True.

Output: -

Note: - for controls like checkbox, listBox & RadioButton, we have a property
called AutoPostBack property which makes a control perform PostBack (or)
Submit server. According to requirement we can set this true or false.








*** END OF THE DAY ***



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page39


Dt: 21-04-2010
Create a web Form default3.aspx
Create a table select table 4*4 or 4*5,..& background
image.browse(click that go to image & Add that)
(Go to table create Table)
We want an image go to solution explore right click new image
form select some images your folder.


Select 4 radio buttons one by one go to properties select Groupname = pay.
Code: -
- protected void Button1_click(object sender EventArgs e)
{ //snippets
if(RadioButton1.Checked)
{
Label1.Text=payment mode selected : + RadioButton1.Text;
Image1.imageUrl=xxx.jpg;
}
elseif(RadioButton2.Checked)
{
Label1.Text=payment mode selected : + RadioButton2.Text;
Image1.imageUrl=yyy.jpg;
}
elseif(RadioButton3.Checked)
{
Label1.Text=payment mode selected : + RadioButton3.Text;
Image1.imageUrl=aaa.jpg;
}
elseif(RadioButton4.Checked)
{
Label1.Text=payment mode selected : + RadioButton4.Text;
Image1.imageUrl=zzz.jpg;
}
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page40

}
Output: -



in above example we have used html image control as well as aps.net image
control. Html image cannot be used in code window of server side. Whereas
asp.net image can be use in code window.
Add a new web item default4.aspx
in design page write welcome web site.
drag& drop image button in toolbox and select that image button double click
write code.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page41


Code: -
- protected void ImageButton1_click(object sender EventArgs e)
{
Label1.Text=SelectedDocuments;
}
- protected void ImageButton2_click(object sender EventArgs e)
{
Label1.Text=SelectedDocuments;
}
Image Map Control:


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page42



In that rectangleHotSpot we fill the following steps:


After select image double click that write following code:
- protected void page_Load_click(object sender EventArgs e)()

- protected void ImageMap1_click(object sender EventArgs e)
{
Label1.Text=e.PostBackValue;
if (e.PostBackValue==eee Products)
{

}
else if(e.PostBckValue==skey)
{

}
}
Select image go to Properties:
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page43


*** END OF THE DAY ***
Dt: 21-04-2010
<image> = html
<asp:Image> = static image
<asp:ImageButton> = single image
<asp:ImageMap>= Multiple Image
(Rich control) using lot of time.
List Controls:
Among all basic input, output controls, list controls provide lot of dynamic
behavior. At Runtime we can add elements & get results a control which is lot
useful for application.
ASP.NET provides 5 list controls in its standard set. It also provides Menu,
TreeView as advanced list controls using which we can build good
Presentations.
5 list controls:
1. ListBox
2. DropDownList
3. CheckList
4. RadioButtonList
5. BulletedLsit
We can use these list controls in design time using its properties. It provides
items collection where we can add our elements.
Go to solution explorer C:///website/(Right Click)New
webform webform default6.aspx
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page44





Select Add Button double click and write following code:
Code:-
Protected void Button1_Click (Object Sender, EventArgs e)
{ //and button feature
ListBox1.Items Add (TextBox1.Text);
}
Protected void ListBox1_SelectedIndexChanged (Object Sender, EventArgs e)
{
Label1.Text=ListBox1.SelectedValue;
}
Select ListBox Properties AutoPostBack =True
Remove Label1.Text=ListBox1.SelectedValue;
And write following code:
Protected void ListBox1_SelectedIndexChanged (Object Sender, EventArgs e)
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page45

{
if(ListBox1.SelectedValue==10)
{
Label1.Text=Web Developed;
}
else if (ListBox1.SelectedValue==20)
{
Label1.Text=.Net language: prepared;
}
else if (ListBox1.SelectedValue==30)
{
Label1.Text=.Net language;
}
else
Label1.Text=ListBox1.SelectedValue;
}




Add one more webform default7.aspx
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page46

Design:-

Code:-
Protected void Button1_Click (Object Sender, EventArgs e)
{//and button feature
CheckBox1.Items Add (TextBox1.Text);
}
Protected void CheckBox1_SelectedIndexChanged (Object Sender, EventArgs e)
{
Label1.Text=CheckBox1.SelectedValue;
}
Select CheckBox Properties AutoPostBack =True
Remove Label1.Text=ListBox1.SelectedValue;
And write following code:
Protected void CheckBox1_SelectedIndexChanged (Object Sender, EventArgs e)
{
if(CheckBox1.SelectedValue==10)
{
Label1.Text=Web Developed;
}
else if (CheckBox1.SelectedValue==20)
{
Label1.Text=.Net language: prepared;
}
else if (CheckBox1.SelectedValue==30)
{
Label1.Text=.Net language;
}
else
Label1.Text=CheckBox1.SelectedValue;
}
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page47


NOTE:-Instead of ListBox, DropDownList if we use. CheckBoxList or RadioButtonList
it provides a good graphical view like creating controls @ runtime. Actually we handle
them as elements only.

*** END OF THE DAY ***





















Dt:23-04-2010
Handling List Controls with dataBinding Content: -
(Q). what is DataBinding Concept?
Ans:-It is a process where we prepare data object with data in side it & Bind the
control with create data object. Controls provide properties to bind them selves.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page48


(Q).How to prepare Data object?
Ans:-
.NET has many classesto support dataBinding data object. It has
System.Collections & System.Collections.Generics for general purpose data.
It also has System.Data.* for various database related data.
It also has good service oriented concepts which can get data from Non.NET
environments.
In our example we will start with a class called ArrayList present in
System.Collections namespace.
This an outdated and not recommended class for storing data. Its drawback is
it performs Boxing/ UnBoxing of data for every storage & retrieval. To replace
this we have System.Collections.Generics which are good in performance & also
simple to program. We have List<T> in this namespace where T is any
database.
Design:-

Code:-
using System;
using Syste.Collections.Genaric;
..
.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page49

.
(Add) using System.Collections; //public partial class default
----------------------------------------------------------------------------------------
protected void Page_Load(object sender, EventArgs e)()
------------------------------------------------------------------------------------------
protected void Button2_Click(object sender, EventArgs e)
{
ArrayList Courses=GetCourses(); //courses is DataObject
ListBox1.DataSource=Courses;
ListBox1.DataBind();
DropDownList1.DataSource=Courses;
DropDownList1.DataBind();
CheckBoxList1.DataSource=Courses;
CheckBoxList1.DataBind();
RadioButtonList1.DataSource=Courses;
RadioButtonList1.DataBind();
BulletedList1.DataSource=Courses;
BulletedList1.DataBind();
}
publicArrayListGetCourses() //prepared
{
ArrayList obj=new ArrayList();
obj.Add(ASP.NET 4.0);
obj.Add(C#.NET 3.0);
obj.Add(VB.NET 3.0);
obj.Add(SQL Server);
obj.Add(Biztalk Server);
return obj;
}
OutPut:-

EX-2:-
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page50


Code:-
using System;
using Syste.Collections.Genaric;
..
.
.
(Add) using System.Collections; //public partial class default
----------------------------------------------------------------------------------------
protected void Page_Load(object sender, EventArgs e)()
------------------------------------------------------------------------------------------
protected void Button2_Click(object sender, EventArgs e)
{
List<string> Courses=GetCourses(); //courses is DataObject
ListBox1.DataSource=Courses;
ListBox1.DataBind();
DropDownList1.DataSource=Courses;
DropDownList1.DataBind();
CheckBoxList1.DataSource=Courses;
CheckBoxList1.DataBind();
RadioButtonList1.DataSource=Courses;
RadioButtonList1.DataBind();
BulletedList1.DataSource=Courses;
BulletedList1.DataBind();
}
public List<string> GetCourses() //prepared
{
List<string> obj=new List<string>();
obj.Add(ASP.NET 4.0);
obj.Add(C#.NET 3.0);
obj.Add(VB.NET 3.0);
obj.Add(SQL Server);
obj.Add(Biztalk Server);
return obj;
}
Some Advantages of this Programming is:
- No need to write logics with loops & fill values in controls.
- Scalable application because data object can be modified independent of
control.
- We also get relation between control & data i.e., if we reflects with that &
viceversa..
Some advanced List controls are TreeView &Menu under Navigation tab.
This controls also support same behavior like List controls i.e. Design time,
runtime, dataBinding .
Add new item Webform home.aspx
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page51

Go to ToolBox Navigation Menu(Drag & Drop)- edit Menu Item
We add items click (+) button added item billow process.

We add sub items also select contact Us and click (+) button added sub item
same as process.
After we select Auto format:


After Goto Menu(select)propertiesOrientation
Vertixal(default)
(or)
Horizabtal



*** END OF THE DAY ***

Dt:26-04-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page52

Navigating Multiple forms:
The process of moving user from one form to another form within the
application as well as outside the applications is called Navigating between
forms.
Asp.Net provides varies options to navigate between forms.
1. Using Response.Redirect(<Url>)method.
- With this option we can take from one page to other page within the side
as well as outside the site. Redirect doesnt carry any values from
current page to new page. If Required we use a concept called
QueryString. To pass values from one page to other.
(Q).What is a QueryString?
Ans: - It a format that helps users to pass values between two forms.
o <programname>?name=value&name=value.255 characters.
o ?..........> separating program name and values.
o &> separating name = value pairs.
- Response.Redirect(default9.aspx?acno=+TextBox1.Text);
- To read the passed value from QueryString we will use another object of
ASP.NET called Request.
For Ex:- Request[acno]will read the value called acno. In our example
have to write it in Default9.aspx receving page.
Add a new item webform default8.aspx

Add a new item webform default9.aspx

First default8.aspx click Enter button & write following code:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect(Default9.aspx); //without values
}
OutPut: -

protected void Button1_Click(object sender, EventArgs e)
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page53

{
// Response.Redirect(Default9.aspx); //without values
Response.Redirect(Default9.aspx?acno=1001);
}

in default9.aspx click load page & double click write following code:

Code:-
protected void page_Load(object sender, EventArgs e)
{
Label1.Text=Request[acno];
}
After go to default8.aspx design page and run it.
Output:-


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page54

In default8.aspx (Design page) add one more text Box.

Code:-
protected void Button1_Click(object sender, EventArgs e)
{
// Response.Redirect(Default9.aspx); //without values
//Response.Redirect(Default9.aspx?acno=+TextBox1.Text);Response.Redirect
(Default9.aspx?acno=+TextBox1.Text
+&acname=+TextBox2.Text);
}
In default9.aspx (Design page) click Load_page & write following code.

protected void Page_Load(object sender, EventArgs e)
{
Label1.Text=AccountNo:+Request[acno]+Name:+Request[acname];
}
--------------------------------------------------------------------------------------------
Run it Default8.aspx (output)

---------------------------------------------------------------------------------------------
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page55

In Defalut9.aspx?acno=1001&acname=SCOTT
We can redirect to other website also.
Response.Redirect(http://www.google.co.in)
---------------------------------------------------------------------------------------------
Default8.aspx (Design page) added one more button Help.

in Help Button double click & write following code:
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect(http://localhost);
}
--------------------------------------------------------------------------------------------------
2. using Server Transfer(<pagename>);
- Server is another object of ASP.NET & its Transfer method takes user
from one page to other page which is in the same site.
- Transfer can implicitly carry one from values to other form no need of
querystring.
Add a new item webform default10.aspx

Add a new item webform default11.aspx

Code:
In default10.aspx submit button(Double click) write following code:
protected void Button1_click(object sender, EventArgs e)
{
Server.Transfer(default11.aspx); //correct within site
Server.Transfer(http://localhost); //wrong outside site
}
--------------------------------------------------------------------------------------------------
Run to the Default10.aspx
ERROR WILL BE OCCURRED.
*** END OF THE DAY ***
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page56

Dt:27-04-2010
Server.Transfer(default2.aspx, true);
- True means preserve current from values for new from.
- False means No values will be preserved.
Server.Transfer doesnt update the url of Browser it directly navigates to the
given page from server program only unlike redirect which travels to Browser &
then goes to new page @ server.
-----------------------------------------------------------------------------------------------
Add a new item webform default7.aspx

protected void Button1_Click (object sender, EventArgs e)
{
Server.Transfer(default8.aspx,true);
}
------------------------------------------------------------------------------------------------
Add a new item webform default8.aspx

protected void Page_Load (object sender, EventArgs e)
{
Label1.Text=Request[TextBox1];
}
------------------------------------------------------------------------------------------------
After go to default7.aspx (design page) & run it.

-------------------------------------------------------------------------------------------------
In default7.aspx added one more TextBox(drag &drop)

Write the code from default8.aspx page select Page_Load & double click, write
code:
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page57



Then go to default7.aspx design page Run it.


3. Using CrossPage*PostBack concept
By default every button are PostBack control submit the form to same webform
which is called PostBack form.
For example Button1 in webform1 on submit calls same webform1. A form
calling itself is called PostBack form.
In ASP.NET 2.0 Version a new concept called CrossPage PostBack is added.
Using this we can submit our form to another webform & it is implemented
using a property called PostBackUrl just specified the page name to display in
this property. When CrossPage PostBack is perform current form status is sent
to the new form which means we can need old page values in newly navigated
form.
Take a new webform default9.aspx


Other options are Hyperlink of ASP.NET, Hyperlink of html & also with some
other controls like Menu, TreeView, and ImageMap.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page58

MultiView Control (Rich Controls):-
It is used to Display multiple Views within a single page. Normally if we
have 2 pages content we have to design them in 2 pages. Using multiViews
in a Single page & display the Required View.
MultiView is collection of view controls.
View is a container for other Controls.
Calendar, Chart, Menu, ImageMap those are rich Controls.
Add a new form goto toolbox standard MultiView(D&D) & one more
View button(D&D)
This view Button drag & drop inside the tag only, because drag& drop to
the outside & run it ERROR will be occur.



Select Linkbutton1 double click & write code:
protectedvoid LinkButton1_Click(object sender, EventAgrs e)
{
MultiView1.ActiveViewIndex=0;
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page59

}
Select Linkbutton2 double click & write code:
protected void LinkButton2_Click(object sender, EventAgrs e)
{
MultiView1.ActiveViewIndex=1;
}
Select Linkbutton3 double click & write code:
protected void LinkButton3_Click(object sender, EventAgrs e)
{
MultiView1.ActiveViewIndex=2;
}

Place MultiView in the form.
Place 3 View Controls inside it.
Place the content in each View & write code if any normally.
Place 3 Link Buttons on top of MultiView like login, shopping &
EEE Way. Write code in these buttons to display the relevant
view.
Login MultiView1.ActiveViewIndex=0;
Shopping MultiView1.ActiveViewIndex=1;
EEE Way MultiView1.ActiveViewIndex=2;
www.ebay.in is the world number one site for e-commers sites.
And one more www.amazon.com.






*** END OF THE DAY ***

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page60


Dt: 28-04-2010
ASP.NET Validation Controls:
To perform validation in web applications we normally use JavaScript
coding for client side. Server side any language code that is possible.
JavaScript is complex & also time consuming ASP.NET validation controls
automatic the process of performing validation.
It internally Generate JavaScript to perform validation in client side &
server side code to perform validations at server.
As a user we can create the control set its property for required validation &
executes the form. All Validation controls are ASP.NET server side controls
& they perform smart rendering that is based on client Validations are
perform (client side or server side) Visual Studio .NET provides all this
control in Validation Tag of ToolBox.
- RequiredFieldValidator
- RangeValidator
- CompareValidator
- RegularExpressionValidator
- CustomValidator
- Dynamic Validator (DynamicData concept only)
- ValidationSummary
Note:-
Dynamic Validator is not there in Visual Studio 2008 we want this option in VS
2008 we install SPI for VS 2008 & also .NET 3.5 (800mb).
In Visual Studio 2010 we can direct use Dynamic Validator.
1. RequiredFieldValidator:
Used to check for null values among all validation controls only this
control performs null value checking. Rest of the controls perform
validation if value is entered otherwise they ignore validation only.

In order Button Double click write following code:
protected void Button1_Click(object sender, EventAgrs e)
{
Response.Redirect(Thanks.aspx);
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page61

}

JS Complex
- Time consuming
- ASP.NET Validation controls generates JavaScript for users, so that we
need not write explicitly JavaScript.

With ASP.NET Validation controls
- Validation is simplified.
- RAD
- Place RequiredFieldValidator in the form & set the following properties,
ControlToValidate:
ErrorMessage:
Result:-Generates JavaScript to perform Validation.
(Q). How Validation Controls work?
Ans: - All Validation controls of ASP.NET check for type of Browser. Browsers are of 2
types,
1. UpLevel:ABrowser that support dynamic html & also client side scripting.Ex:-
Internet Explorer 6,7,8.
2. DownLevel: A Browser that either does not support client side scripting or
Dynamic HTML is DownLevel Server.
Ex:- IE4 (Internet Explorer 4)
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page62


If UpLevel
o They generate JavaScript for client side execution & Server side code for
server side execution. First they perform validation in client, after
submitting the form to server they again perform validation @ Server &
continue the further process.
If DownLevel
o They dont generate any JavaScript code & doesnt perform validation in
client. Only after submitting the form validation is performed @ server
side.

All Validation controls are initially treated as invisible controls when error
occurs then they display error message & also step user in submitting the form.
On successful validation they remove error massage & allow stop user in
submit the form.
2. RangeValidator:
Used to check for range of values. Very use full for numeric & date
type of data. Dont use it for string type of data.
- MinimumValue
- MaximumValue
- Type:Integer/Date/.





*** END OF THE DAY ***


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page63


Dt: 29-04-2010
In our example RangeValidator has not displayed any errorMessage when no value is
entered. To avoid this problem we have to create another required field validator
performs null value checking.

There is one common property for all validation controls called display.
Display: static (d)/dynamic/none.
Static means the place for displaying error message will be
reserved.
Dynamic means only when error occurs, it creates place for
message & display it.
None means no display of error message.


3. CompareValidator:
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page64

Used to perform validations which are comparison based 3 types
compression can be done.
a) Control with another control
ControlToValidate
ControlToCompare
ErrorMessage
Operator
Type

b) Control-Value:
- ControlToValidator:Text
- ValueToCompare : 10
- Type : Integer
- Operator : Greater then
- ErrorMessage : Min 10 (or) above 10


<asp:CompareValidator ID=cv2 runit =server
ControlToValidate=TextBox5
ValueToCompare=10
ErrorMessage = must be above 10
Operator=Grater Then
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page65

Type =integer/>

c) Control-Data Types:

4. ValidationSummary:
This doesnt perform any validation instead it collects all validation error
messages& displays them in one place as a summary.



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page66


*** END OF THE DAY ***
Dt: 30-04-2010
5. RegularExpressionValidator:
One of the good features that a language can provide is pattern these searching
& a validation. This validation control provides validation based on expression.
Different expression it is very difficult to write an expression & to simplify
writing expression issue we were some tools like Regex tool available in
codeplex.com & in other locations also. .Net also provides some sample
validation expression which we can use as it is (or) modifying them according to
requirement.
Regex tool;
Product Id: QWER-12345
JS 60 to 70 lines of code.

RegExLib.com (Regular Expression Library)
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page67


Add one more textBox8 & RegularExpressionValidator

6. CustomValidator:
Which developing application, if all above four validation controls doesnt fulfill
our requirement then we have to write our own JavaScript code. Instead of
separately writing JavaScript code it is button to write under custom validator.
Reason:Custom validator provides automatic display of error message & also
handles the form submission apart from this RegularValidationControl benefit
are also provided.
We can use custom validator to perform validations client side, server side &
even both.

CustomValidatorClient side:
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page68

To perform client side validation using CustomValidator we have to write
JavaScript code. The following properties must be set for CustomValidator.
- ControlToValidate
- ErrorMessage
- ClientValidationFunction**:<js function name>
After specifying the properties go to source view & write the function which is specified
in the property.







*** END OF THE DAY ***















Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page69








Dt: 03-05-2010
CustomValidator Server side:
Server side means code which will be executed @ server after submitting the
form.
Place CustomValidator & set the following properties,
ControlToValidator:
ErrorMessage:
Go to Events & Select ServerValidate*event. As we select this VisualStudio
automatically adds a function in code window. We have to write validation code
here to perform our validation.


protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs Args)
{
if(int.Parse(args.Value)%5==0)
args.IsValid=true;
else
args.IsValid=false;
}

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page70


protected void Button1_Click()
{
//IsValid returns when all Validations resources performed
//returns false when one or more validations fail.
if(page.IsValid)
Label1.Text=Submitted Successfuly;
else
Label1.Text=please correct the errors;
}

More Important issues with Validation Controls:
A property called CausesValidation:true/false
- This property is set for Postback controls like button, linkbutton,
imagebutton ete. by default for most them it is true. When set to false
this control ignores all validations in the form & summit itself to server.

ValidationGroup**
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page71

- Added in ASP.NET 2.0 used to make different validation groups in a
single form. When we want different validation sets in as single from then
we have to use this group property.

Client Targeting:
(Q).which validation always gets performed irrespective of client levels i.e.
UpLevel/DownLevel?
Ans:- Server side.

For Up Level client side +server side (why)?
- For Security Client side there is every chance of malfunctioning code &
other entries.
Client Side validation is performed.
Server Side is it same repetition of validation.
Ans: -YES same repetition.
(Q). Our Validation control they are working like gmail (only server side)/ hotmail (client
side + server side)/none?
Ans:-None.
- It work like gmail for downlevel
- It work like yahoo for up level
If we want only server side validation we have one attribute called
ClientTarget for page.
Ex:- in source page write,
%@page ClientTarget=DownLevel Language=C#...........
- This setting is applicable for entire webpage validation controls.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page72


*** END OF THE DAY ***

Dt: 04-05-2010
EnableClientScript true/false:
Client target will apply validation settings for entire page. If we want to perform only
for control then we can use EnableClientScript property of Validation control.
Add a new windows form:

Example:-Place twoRequiredFiledValidators in the page & set its ControlToValidate
properties.
Go to 2 RequiredFieldValidater & Set EnableClientScript:false
Execute the form & click on button.
Result:- RequiredFieldValidator1 will run not 2
nd
RequiredFieldValidator.
Reason:-Because 2
nd
one will be fired only when it goes to server.
(Q). what is the different between EnableClientScript & Client Target?
Ans: -
ClientTarget for all controls in the page.
EnableClientScript for selected Controls.
Displaying more then a text in place of ErroeMessage:
We need not display simple text only for ErrorMessage instead we can show
only valid DHTML statement also. We can display an image to indicate an error.
Also we can display or play sound if Brower supports.
Just go to ErrorMessage or text properties & write HTML tags instead of simple
text.
ErrorMessage : Name Required
ErrorMessage :<img src=loading.gif> Required
Select 1
st
RequiredFieldValidator goto Preperties write,
ErrorMessage <img src=loading.gif>Required (ENTER)
IN SOURCE PAGE: (BackGround Sound):
--------------------------------------
-------------------------------------
(<asp:RequiredFieldValidator>)(before)
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page73

ErrorMessage=<img src=loading.gif><bgsound src=Amanda.wma>Invalid
(Style=------------------------)(after)
Note: -wma=WindowsMediaAudio file
Note:-
Whenever we are displaying resources as a result of action then we must
ensure that resources are small in size. In our example we have user
Loading.gif which is of 3 KB & .wma file which is of 5 MB nearly. 3KB size is
excellent but not 5MB size because just to display error message it takes 5 min.
in normal internet connected PC & 5 mts no user can wait for ErrorMessage.
When validation groups are present in the form then we have to take separate
ValidationSummary control for each group.

All above Validation Controls perform different Validations. When we require
more then this we have 2 choices to perform.
1. Using AJAX control ToolKit of ASP.NET we can get more user interface &
other things.***
2. Manually write JavaScript to fulfill our requirement. ***
Note:- Captcha Graphic
(Q): - Designing the gmail registration page using ASP.NET?













*** END OF THE DAY ***




Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page74




Dt: 05-05-2010
ASP.NET DataBinding
In List Controls DataBinding example was shown. In DataBinding we prepare 2
objects.
1. Data object: data from various data Sources.
2. Bound Control: presentation Control.
Data object + Bound Control = DataBinding (Effective presentation).
ASP. NET has data Tab in ToolBox which exclusively displays all dataBinding
related controls. In this we have controls that prepare data objects & also
controls that provide presentation.
Apart from this we have one exclusive concept in ASP.NET 4.0 onwards called
Dynamic data. This concept is also for dataBinding with RAD & Rich features.
AJAX, Silver light, WCF are new Concept which are today most used in
application development. All these concepts also provide dataBinding with their
Controls.
In data Tab the controls that prepare data objects are called DataSource
Controls. In data Tab the controls that present data are called Bound Controls.
We can prepare data objects in 2 important ways,
1. Programmatically with N-Tier model.
2. Using DataSource controls in little RAD style.
Different DataSource controls are available for different type of data Sources.
SqlDataSource
- This control is used to prepare data object from all databases that
support ADO.NET (or) SQL.
Ex: -SQL Server, ORACLE, MySql, Sybase, Informix, PostGreSql, Ingres
Call Support Sql.
- Place SqlDataSource control in the form & select Configure DataSource.
In the displayed window provide the connectivity options for
the database available.
In the same window steps also select the table for which
data object is required.
Complete this window steps & result is data object
prepared.
- Place GridView control which is bound control & specify its DataSource
as the created SqlDataSource control.
- Execute the form & Observe dataBinding output.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page75





Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page76


















*** END OF THE DAY ***















Dt: 06-05-2010
Creating our own Databases & providing DataBinding Results:
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page77

Visual Studio provides Server Explorer window which allows user to connect
with local & remote databases.
We can also create our own database using SqlServer Express Edition. This is
one of the SqlServer available & it can be used only in the current project &
also can be handed using VS.NET only.
- SQL Server Enterprise/Professional.
- SQL Server Express.
- SQL Server CE (Compact Edition).
In ASP.NET we have some Special folders for creating Special type files. All
these folders are securedimplicitly, their content is accessible to entire project +
other benefits are also provided. It is recommended to use these folders.
Just Right Click on Solution Explorer & select Add ASP.NET folder folder.
Among these folder App_Data is one folder where we can store data related files
like database files, xml files, text files etc


i. SqlDataSource
ii. LinqDataSource
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page78

iii. EntityDataSource
SqlDataSource is used to get data from databases directly. Which is not
prepared model today from working with databases.To data all applications like
.NET, Java & other follow a model called ORM (object Relational Model). The
main idea behind ORM is to represent data & objects as same. We must have
presented object with represent backend tables. In .NET we have two concepts
which allow user to create ORM.
i. Linq To SQL
ii. Entity Data Model (EDM)
Linq data source & entity data source controls get data from these model
classes instead of getting data from databases (highly recommended Method).


Using Linq to SQL for DataBinding as well as for implementing ORM:

In order to implement ORM we must first creates objects that map to tables. It
is very difficult to create these objects in code & great experience is required to
prepare them. To simplify this .NET provides ORM designer where with drag &
drop approach we can create frontend objects. On our example use add new
item Linq To Sql class template & we will get ORM designer.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page79


Go to Server Explorer and drag & drop tables on to designer.
Result: -objects are created.
- Create a Webform& place LinqDataSource Control. Configure it with
required table.
- Create GridView & assign it to LinqDataSource.





*** END OF THE DAY ***


Dt: 08-05-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page80

How to DataBind using Entity DataSource:
EDM [Entity Data Model] is another ORM model available in .NET using this
model also we can prepare frontend objects for backend tables. EDM is superior
model our Linq to Sql in otherworlds using EDM we cab connect with different
databases unlike Linq to Sql which connect only with Sql server apart from
this another different (or) advantage is you can implement conceptual model
with EDM. Which is again not possible with Linq to Sql. EDM is added in 3.5
service pack. To day almost one preferred way of working with databases.
Diff between Linq to Sql and EDM:-
Linq to Sql only work with only Sql server.
EDM it can do lot of manipulations. Its works with MySql, Oracle, SqlServer,
etc
Astoria is database on clouds.

Steps:-
1. Add new item from App_code folders and select Ado.Net entity Data Model.
This is used to create classes or object in the form of Entities. Once we add
automatically connection to database followed by tables are displayed for
selection. After giving the inputs we will get a designer where we can see as well
as customize our model.
2. Create new form and add Entity DataSource and configure it with created
model.
3. Add Gridview and set its DataSource to created Entity DataSource.
What is this App_code and other ASP.NET folder?
In ASP.NET to support good development and simplified development a concept
called ASP.NET Folders is added. For every special type of files which are more
frequently used in project a separate folder is given. These folders are accessible
to entire project and they are secured by themselves. Apart from this in
development also they give good support.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page81

Two most important Folders in that are App_code. This folder is meant for
writing all code related especially .CS files and some other also. When developed
all content in this folder is automatically converted to a .dll file.
.dll Assembly
.exe executable
App_Data:
This folder is used for storing data related files.
Ex: - XML
How to Add them?
Just Right Click in solution explorer Add ASP.NET Folder (Required
folder)
Note: -
To programmatically prepare data objects we have to write code in the form of
classes and that code we have to write in App_code.
















*** END OF THE DAY ***




















Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page82


Dt: 10-05-2010
Programmatically preparing objects:-
To prepare our own objects especially database oriented content we have to
ADO.NET concept of .NET.
In ADO.NET we have different ways of preparing data objects.
1. Using ADO.NET 2.0
2. Using ADO.NET Linq to Sql
3. Using ADO.NET EDM***
ADO.NET 2.0 [ex: DataBinding] provides DataSet, DataAdapter & Connection
classes using which we can develop our data objects.
Is there any model for writing programs or we can write in any method?
Yes.There is a prepared model & it is highly recommended to write programs in
this method only.
This model includes layers that must be constructed for writing a program.
A program must be written with 3 layers,
1. User Interface Layer:- This layer should contain code related to user
interface.
2. Business Layer: - A layer where we write calculations, logics related to
UI as well as database.
3. Data Layer: -This Layer contains all code to get/send data To/From
database.

ADO.NET 2.0 Objects:-
Connection To establish connection with database.
Adapter ToExecuteSQL Commands.
DataSet To Store the data.
Stepwise Example for Layered Implementation:
1. Go to App_code&create a class called DataHelper.Add New ItemDataHelper.
2. Write code in this class which can get data from database as well as send the
data to database. In general this code is written in generic style which means
works for multiple users.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page83

In Empty class page we write following code:
using System.Data; //DataSet
using System.Data.SqlClient; //Sql Connection & Sql DataAdapter
{
//static means class member invoked with class name
publicstaticDataSet GetData(string sqlstat)
{
//Data Source= ;//Ex:- ROHIT-PC /SQLINDIA,IN..)
SqlConnection cn=new SqlConnection(DataSource=(.));
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(sqlstat, cn);
//sqlstat=what to run; cn=where to run
Da.Fill(ds);
return ds;
}
}

3. Create another class called BLJobs. This will be business layer in our Example.
Write methods in this also to get data from dll & other activities.


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page84

In Empty class page we write following code:
public class BLJobs
{
public DataSet GetJobs()
{
return DataHelper.GetData(Select*from jobs);
}
public BLJobs()
{
}
4. Now create a form & create Button, GridView. In Button write code to get data
using Business Layer & assign the same to GridView.

Code page:
protectedvoid page_Load()
{
}
protected void Button1_click(object.)
{
BLJobs obj=new BLJobs();
GridView1.DataSource=obj.GetJobs();
GridView1.DataBind();
}







*** END OF THE DAY ***






Dt: 11-05-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page85

Linq to Sql & EDM are 2 concepts that are available in .NET to develop ORM
type of applications. In this Linq to Sql is limited to Sql Server & provides
mapping of Database tables to frontend objects.
Where as entity data model works with all databases as it follows provider
model like ADO.NET 2.0
EDM provides not just mapping the DB tables but also allows user to provide
conceptual model implementation.
If we can implement a conceptual model then we can do mapping also in more
rich manner, like creating one or more entities in frontend and map them to
single table/ object in DB-similarly objects in frontend mapping to multiple
tables of backend
ADO.NET Linq to Sql EDM
EDM gives conceptual model means starting Manual Design.

Entity Framework entity Libraries + entity Runtime.

Framework Create objects, that connect to Backend DB.
OOPS Response Objects.
SQL Response SQL Objects.
Linq only Linq
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page86

Object Query / Expend (work with objects to primary) we want to
create that will be response.

Steps:-
1. Start a new website & Create EDM using the template provided.
Add new item Entity Data model
Design the model as required.
2. Go to App_code create a class called BLJobs which is our business layer
& write code using Linq(other also) to get data from crated objects.
3. Go to form crate button GridView & as UI usual write code to get data
from b1.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page87



*** END OF THE DAY ***
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page88

Dt: 12-05-2010
BLJobs of EDM:
In our example we have created EDM objects which provide for creating objects
& their actions. When we create objects in EDM or linq 2 sql we must ensure
that table has primary key defined otherwise EDM objects will not provide
action to the data.
Return type of GEtJobs is List<pubsModel.Job>which is a generic type i.e.,
List<T> (preferred data types for almost all
purposes)(System.Collections.Generic).
pubsModel.Job means a type called Job created in namespace called
pubsModel. EDM always creates its objects in a separate namespace unless
specified & unlike Linq to Sql which by default creates in dame namespace.
This when used List<T> it is collection of objects.
string a; //namespace is a logical collection of object.
List<String>b;
-----------------
pubsModel.Job a;
List<pubsModel.Job>b; //b is collection of job
// no datasets/datardrs
Once return type is a collection of simple or complex type inside method we
have to write code to fill this collection with values & return it. Normal code to
do this job takes lot of lines so from .NET 3.5 we can use LINQ (Language
Integrated Query) & prepare our data easily. In our Example we have return
Linq Query to work with entities & get one or more records.
var x = from n in obj.jobs
selectn;
where obj is EDM & from n.is Linq Query.
X is implicitly declared variable which is provided from C# 3.0 in this example
contains all jobs records. (but not in List formats)
So we have to use ToList<T> method to convert the values into list format as
our return type is List<T>.
return x.ToList<pubsModel.job>();
---------------------------------------------------------------------------------------------------------
public static List<string>GetCourses()
{
var x=from n in Courses select n.CourseName;
return x.ToList<string>();
}









Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page89



2 Windows Right click on edm on edm screen & select Mapping Details. We
can crate multiple entities & also handle current entities mapping with storage.
Model Browser lets user View all the current entities & their storage entities.
Programmatically using ADO.NET 2.0 & Most Important with EDM (our above
examples).
Different presentation control added in .NET 4.0 for presenting data using Data
Binding.
- Chart Control.
This control provides all types of charts for our data. Moreover with data
binding style.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page90

(Q)How is that possible?
Ans: - .NET uses graphics code & draws a chart on ply & saves it as an image or
stream. We can simply present the data to control & ask it to render as page content.
(Normally it is week days module to do in a project like this).
---------------------------------------------------------------------------------------------------------------------
C://demo/.(right click) new form default2.aspx
----------------------------------------------------------------------------------------------------------------------




*** END OF THE DAY ***
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page91

Dt: 14-05-2010
GridView
In all over previous examples we have learn how prepare data objects in simple
ADO.NET 2.0 method and also much prepared e have to plane for presentation
requirements. Among all data Bound controls GridView & ListView are feature-
Rich controls these controls provide Maximum support for providing affective
presentation.
GridView supports features like generating columns Automatically, sorting,
paging, etc... in .NET 4.0 more features are added in sorting & their style of
presentation.
GridView is a structure control & its structure is like table with Rows &
columns. We can produce any tabular presentation using GridView control. Non
tabular and unstructured outputs are difficult using GridView.
GridView Columns:
Chart
DataList
DetailsView
FormView
GridView
ListView
Repeater
The above 7 are presentation Controls. (ListView is a Richest control)
GridView has one property called AutoGenarateColumns:True(d)/false. True
means based on data objects that we assign to GridView it will generate column
information automatically (Not preferred & not important).
When set to false we have to manually generate gridview columns (prepared).

(Q).How to provide GirdView columns information?
Ans:- GridView provides its own collection called columns****. Which is all the
information Required for GridView.
Inside columns gridView provides its own fieldsto provide column information.
We cannot use any other contents directly in gridview columns.
Only fields.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page92

(Q). What GridView Fields are provided for columns presentation?
1) BoundField: - This field is attributebased and it contains different attributes to
produce column information.
- This Field is attribute based and it contains different attributes to
produce column information.
- This Filed is simple in presentation i.e., it can display data in simple text
format only. Limited in providing various options but faster in
presentation because of simplified rendering.
Ex:-<asp:BoundField DataFiled=job_id
HeaderText=Code/>
- In code i.e. using C# code
BoundFiled fld1=new BoundField();
fld1.DataField=job_id;
fld1.HeaderText=code;
..
.
GridView1.Columns.Add(fld1);
Demo:-
Take new form place Button & GridView inside it. In button write code
to get data from business layer & assign it to GridView.
Select GridView & write code for providing columns: false. Go to
SourceView & write code for providing columns information from the
prepared data object.



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page93

Goto Source Page:
<asp:GridViewID=GridView1 runat=Server AutoGenarateColumns=False>
<Columns>
<asp:BoundField=job_id HeadText=code/>
<asp:BoundField=job_desc HeadText=Description/>
<asp:BoundField=Min_lvl HeadText=MinLevel/>
<asp:BoundField=Max_lvl HeadText=MaxLevel/>
</Columns>
Go to Design Page:


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page94

2) TemplateField of GridView(And for All other Rich Bound Controls):
DataBinding Expressions in ASP.NET***
Unlike BoundField, TemplateField is not only attribute based & simple.
It can produce any type of presentation that user wants.****
It is again collection of Templates**(not just attributes).
(Q).What is a Template?
Ans: -
A Template is like container or place holder where we can place any type
of content.
Different templates are available to fulfill different requirements,
a. HeaderTemplate: To Display the heading for a column.
b. FooterTemplate: To Display Footer information for a Column.
c. ItemTemplate:ToDisplay the content of GridView we have to use this
template, it will be repeated for every row of data object. This template
like others can have only content inside it i.e., both data object
related as well as independent content.
Other Templates also:
TemplateField -Collection of Templates
-Header Template
-Footer Template
-Item Template
DataBinding Expressions:-
TemplateField has to no attribute or property to display data object data. To get
data from any other bound object in template field we have to use DataBinding
Expression of ASP.NET
What is DataBinding Expression?
Ans:-An Expression that is evaluated against data object for retrieving data is
called DB Expression.
- We have to write DB Expression in a separate black
<%#DB expression %>
The following expression are supported in ASP.NET
i. <%# DataBinder.Eval(Container.DataItem,<fldname>)%>
Get the job id data from the assigned data object. (its .NET 2.0)

ii. <%# Eval(<fldname>)%>
(add in asp.net 2.0)
(both are same but some Eval not work that 1.0 version will be using).
Ex:-
<%#Eval(job_id)%>
Get the job id data from the assigned data objects. Same as first but
more simplified in writing.
iii. <%# Bind(<fldname>)%>
Get the given field from data object & if conditions match also sets
back the data to data object. It is a 2 way expression.
Ex:-<%# Bind(job_desc)%>
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page95


iv. Performing Calc using DB Expressions.
Ex: -
<%#Convert.ToInt32(Eval(max_lvl))- Convert.ToInt32(Eval(min_lvl))%>
v. Invoking class members from DB Expressions.
Ex:-<%#GetRating()%>

Will invoke the GetRating function written in code window. Whatever this functions
returns it will display in this place.

TemplateField Example:
- Add Newform- place Button & GridView in the form.
- In button write code to bind data to GridView.
- Go to GridView & set AutoGenerateColumns: false
- Go to SourceView & write Columns information using TemplateField this
time.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page96

Go to Source:
<asp: GridView ID=GridView1 runat=server/>
<Columns>
<asp: TemplateField>
<HeaderTemplate>
Job
</HeaderTemplate>
<ItemTemplate>
//(Goto TooBox Drag & Drop CheckBox on this place)
<asp:CheckBox ID=checkBox1 runat=server/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
(i)<HeaderTemplate>Description<br></HeaderTemplate>
//After <Br> Drag & Drop one Image I Solution Explorer

(OR)(ii)<HeaderTemplate>Description<br/>
<img src=image42.jpg height=70 width=70/></HeaderTemplate>
<ItemTemplate>
<%# Eval(job_desc)%>
</ItemTemplate>
</asp: TemplateField>
<asp:TemplateField>
<HeaderTemplate>MaxLevel</HeaderTemplate>
<ItemTemplate>
//Drag &Drop HyperLink& Remove HyperLink Message Data
<asp:HyperLink text=<%# Eval(Max_lvl)%>>
NavigateUrl=~Default.aspx
Target=w1
ID=HyperLink1 <img src=img45.jpg/>runat=Server
</ItemTemplate>
</asp:Template>
</Columns>

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page97


Exercises:-
1. Using BoundField display job id, description, Min level, Max level & one more
column diff. which is MaxLevel MinLevel(using BLJobs & EDM only)
2. Using BoundField (or) TemplateField (any one)display additional column called
Rating for all max_lvl above display a 5 star image.(for above 40 display 4 stars,
30 display 3 stars, 20 display 2 stars).











*** END OF THE DAY ***















Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page98


Dt: 17-05-2010
3) CommandField of GridView & GridView Editing:
GridView not only presents the data but also provides good editing
support. It has not one field called CommandField which is used to
display edit, update, Delete & Cancel Button.
GridView supports editing of data using all its fields like BoundField,
TemplateField, CommandField, etc it has a property called EditIndex.
Whosedefault value is -1 & provides Edit Table Row based on the given
value.
How GridView editing is supported?
Ans:-The key for editing data in GridView is edit index. When we specify
EditIndex value to n, then nth record is set to be Editable record. All
GridView fields react to EditIndex property.
How BoundField React to EditIndex?
Ans:- when EditIndex is -1 which is its default value BoundField displays
all records with simple text (as we have seen)when EditIndex is set to
sum record number then nth record will be display with TextBoxes for
editing & remaining all rows will be displayed in simple text format.
How TemplateField react?
Ans:-TemplateField is also dependent on EditIndex property. It displays
item template content for all the rows & EditItem template for nth row
that is, when EditIndex is changed.
Ex:
publicList<ns.class> GetJobs()
{
ns. entities obj=new..();
var x=from n in obj. table select n;
}
----------------------------------------------------------------------------------------------------------
Note:-
1. What is the important of EditIndex?
2. How BoundField, TemplateField is Dependent on EditIndex?
3. What is the use of CommandField?
--------------------------------------------------------------------------------------------------------
CommandField also reacts of EditIndex value it will display edit & delete
buttons when EditIndex is -1 & displays update Cancel for nth row.
We must provide editing of GridView using the entire above concept.
Demo:-
1. Assuming our EDM objects & BLJobs are present in the project (if not present
create them)add new form & placeButton, GridView inside it.
2. Write code in button to get data from BLJobs & Bind it to GridView.
3. Go to GridView & set AutoGenerateColumns to false. Go to SourceView & write
code for GridView this time along with editing support****. Including
BoundField, TemplateField & CommandField. (New: Read only, EditItem
Template, CommandField).
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page99


Double click on ViewData button & write following code:
BLJobs objjobs=new BLJobs();
GridView1.DataSource=objjobs.GetJobs();
GridView1.DataBind();
Select GridView go to Properties AutoGenerateColumns: False
Go to Source page:-
<asp:GridView..>
<Columns>
<asp:BoundFieldDataFiled=job_id HeaderText=job_id HeaderText=job code
ReadOlny=true/>
<asp:BoundField DataField=job_desc HeaderText=Description/>
<asp:TemplateField>
<HeaderTemplate>Min Level</HeaderTemplate>
<ItemTemplate><%#Eval(min_lvl)%></ItemTemplate>
<EditTemplate>
(//drag & drop List Box)
<asp:ListBox ID=ListBox runat=server>
<asp:ListItem>10</asp:ListItem>
<asp:ListItem>20</asp:ListItem>
<asp:ListItem Text=30 value=30></asp:ListItem>
<asp:ListItem Text=40 value=40></asp:ListItem>
</asp:ListBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField
ShowEditButton=true
ShowCancelButton=true
ShowDeleteButton=true/>
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page100


4) All CommandField controls have their own events with GridView. It is must to
handle them otherwise they will raise an unhandled exception.
Edit RowEditing
Update RowUpdating
Cancel RowCancelingEdit
Delete RowDeleting
All the above event also have Completed task event. i.e., RowDeleted which fires after
deleting the row whereas Row Deleting when user click on Delete.
Select GridView Choose RowEditing from events & write code to
change EditIndex to selected row.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page101

protected void GridView1_RowEditing(object sender.)
{
//e.NewEditIndex selected row index provided by GridView only.
GridView1.EditIndex=e.NewEditIndex;
LinkButton1_Click(sender,e);//Rebinding data
}
(..Select GridView click on Autoformat change to design models)

5) Go to GridView Select RowCancelingEdit event & write code to change EditIndex
default value.
protected void GridView1_RowEditing(object sender.)
{
//cancel
GridView1.EditIndex=-1;
LinkButton1_Click(sender,e);//Rebinding data








*** END OF THE DAY ***
















Dt: 18-05-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page102

Update part of GridView Editing:-
6) Select Row updating event of GridView & write code to perform following tasks,

a) Retrieve data which is modified by user from current Row.
b) Store the modified data in the relevant type & pass it to business layer for
updation. Ass retrievedmethods in business layer that input from UI & update
it with EDM objects.
c) Reset the GridView to its original display. i.e., to EditIndex -1.
Samples:
GridView1.Rows
- All rows of gridview.
GridView1.Rows[0]
- First rows of gridview.
GridView1.Rows[0].Cells
- First rows all Cells
GridView1.Rows[0].Cells[0]
- First rows first Cell
GridView1.Rows[0].Cells[0].Text
- 1
st
Row 1
st
Cell text provided that Cell Contains simple text.
GridView1.Rows[0].Cells[0].Controls
- 1
st
row 1
st
Cell Controls.
GridView1.Rows[0].Cells[0].Controls[0]
- 1
st
Row 1
st
Cell 1
st
Control
Ex:-
1 GridView1.Rows[1].Cells[1].Text
3GridView1.Rows[2].Cells[0].Control
This type of retrieval is used when BoundField implicitly creates a control
because we dont know the name of that implicitly created controls.
If we want to retrieve data from explicitly created controls like in TemplateField
case then we have to use one common method of page object called
FindControl(<id>)***.
This method searches for the given control in the given context & returns
reference. It returns null when there is no control with the given id.
Ex:- GridView1.Rows[0].FindControl(ListBox1);
Searches for ListBox1 in the first row of GridView and returns its reference.
This reference can be used to access the control directly.
GridView1.Row[0].Cells[2].Controls[0]
GridView1.Row[0].FindControl(GridView2).Cells[2].FindControls(Tb2).
GridView x=GridView1.Rows[0].Cells[2].FindControl(GridView2);
ListBox y=x.Rows[0]. FindControl(LB1);
---------------------------------------------------------------------------------------------------------------------
In a row 2 control--- Same name

GridView1. Rows[0].FindControl(Panel1);


protected void GridView1_RowUpdating(object sender,..)
{
string mjobid=GridView1.Rows[e.RowIndex].Cells[0].Text;

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page103



TextBox tjondesc=(TextBox)
GridView1.Rows[e.RowIndex].Cells[1].Controls[0];
ListBox lb1=(LsitBox)
GridView1.Rows[e.RowIndex].FindControls(ListBox1);
//preparing values to pass for Business Layer (BL) .
DB3PMModel.job mjobrec=new DB3PMModel.job();
mjobrec.job_id=int.Parse(mjobid);
mjobrec.job_desc=tjobdesc.Text;
mjobrec.Min_lvl=int.Parse(lb1.SelectValue);
mjobrec.Max_lvl=40;
BLJobs obj=new BLJobs(); //Job is a EDM objects
Obj.UpdateJob(mjobrec);
GridView1.EditIndex=-1;
LinkButton1_Click(Sender, e);
}


public class BLJobs
{
publicBLJobs()..
public List<DB3PMModel.job>GetJobs()
public void UpdateJob(DB3PMEntities obj=new DB3PMModel
DB3PMEntities();
var x=(from n in obj.jobs where n.job_id==mjobrec.job_id select n).FirstOrDefault();
if(x!=null)
{
x.job_id=mjobrec.job_id;
x.job_descmjobrec.job_desc;
x.Min_lvl=mjobrec.Min_lvl;
x.Max_lvl=mjobrec.Max_lvl;
obj.SaveChanges();
//method in EDM to save all changes to DB
}
else
{
throw new Exception(No record id found);
}
}
QUERYS:-
1. What is dataBinding&how dataBinding is a feature in application development?
2. How BoundControl id different than on DataSource control?
3. How to present data in GridView which is added on-fly?
4. What type of outputs we cannot produce using GridView?
5. What will happen if AutoGenerate Columns:true& we provide manually some
Columns?
Ans:-AutoGenerate will display & our Cols also get display.
6. Can we place if button in GridView Columns? Explain?
Ans:-No, only GridView Fields are allowed.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page104

7. Which property of GridView provides Editing of data & how it is related to
GridView Fields?
8. Can we access we have Nested GridViews & if passible how to access outer &
InnerGridViews?




































*** END OF THE DAY ***








Dt: 19-05-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page105

More GridView Tasks:-
GridView has different classes to represent its rows, columns & other things. It
has collections like rows/columns etc which can be navigated using its types
like GridViewRow, GridViewColumn etc
In our editing example we have retrived the current row of gridview & most of
the cases we need to retrieve complete GridView & some selected rows in
GridView. In such cases we have to use some events which firefor every row or
we have to use soe logic for navigation.

Example-1:
In Source page:
<asp: GridView ID=GridView1 runat=server AutoGenaration..>
<Columns> //HeadText=Simple text for Header
<asp:TemplateField HeaderText=Choose>
<ItemTemplate>
Drag & Drop CheckBox
<asp: CheckBox ID=CheckBox1 runat=server/>
</ItemTemplate>
</asp:Template>
<asp:BoundField=Job_desc HeaderText=Description>
<asp:TemplateField HeaderText=Difference>
<ItemTemplate>
<%#Convert.ToInt32(Eval(Max_lvl))-Convert.ToInt32(Eval(Min_lvl))%>
</ItemTemplate>
</asp:Template>
<asp:TemplateField HeaderText=Level>
<itemTemplate>
<%#GetLevel(Eval(job_desc))%>//on GetLevel Right click watch CODE
</ItemTemplate>
</asp:Template>
------------------------------------------------------------------------------------------------------

Go to Code page window:
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page106

protected void Button1_Click(object sender..e)..
public void GetLevel(object jobdesc)
{
//place to write code & generate output
if(jobdesc.ToString.ToUpper().Contains(PROGRAMMER))
return Technical;
elseif(jobdesc.ToString().ToUpper()==MANAGER))
return Manager;
else
return others;
}
protectedvoid Button2_Click()
{
ListBox1.Items.Clear();
foreach(GridViewRow rec in GridView1.Rows)
{
CheckBox c1=(CheckOut)
rec.FindControl(CheckBox1);
if(c1.Checked)
ListBox1.Items.Add(rec.Cells[1].Text);
}
}
protectedvoid Button2_click(..)
{
ListBox1.Items.Clear();
foreach(GridViewRow rec in GridView1.Rows)
{
checkBox c1=(CheckOut)
rec.FindControl(CheckBox1);
if(c1.Checked)
ListBox1.Items.Add(rec.Cells[1].Text);
}
}


Modification of Example-1:
In Source page:
<asp: GridView ID=GridView1 runat=server AutoGenaration..>
<Columns> //HeadText=Simple text for Header
<asp:TemplateField HeaderText=Choose>
<ItemTemplate>
Drag & Drop CheckBox
<asp: CheckBox ID=CheckBox1 runat=server/>
</ItemTemplate>
</asp:Template>
<asp:BoundField=Job_desc HeaderText=Description>
<asp:TemplateField HeaderText=Difference>
<ItemTemplate>
<%#Convert.ToInt32(Eval(Max_lvl))-Convert.ToInt32(Eval(Min_lvl))%>
</ItemTemplate>
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page107

</asp:Template>
<asp:TemplateField HeaderText=Level>
<itemTemplate>
<%#GetLevel(Eval(job_desc))%>//on GetLevel Right click watch CODE
</ItemTemplate>
<FooterTemplate> A
<%#GetTotal()%>
</FooterTemplate>
</asp:Template>

Go to Code page window:
public void .Default3:default
{
int i; 1
}
protected void Button1_Click(object sender..e)..
public void GetLevel(object jobdesc)
{
//place to write code & generate output
i++; 2
if(jobdesc.ToString.ToUpper().Contains(PROGRAMMER))
return Technical;
elseif(jobdesc.ToString().ToUpper()==MANAGER))
return Manager;
else
return others;
}

Output:

in default4.aspx
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page108



protectedvoid Button2_Click()
{
ListBox1.Items.Clear();
foreach(GridViewRow rec in GridView1.Rows)
{
/*for(int i=0; i<GridView1.Count -1; i++)*/
CheckBox c1=(CheckOut)
rec.FindControl(CheckBox1);
if(c1.Checked)
ListBox1.Items.Add(rec.Cells[1].Text);
}
}
protectedvoid Button2_click(..)
{
ListBox1.Items.Clear();
foreach(GridViewRow rec in GridView1.Rows)
{
checkBox c1=(CheckOut)
rec.FindControl(CheckBox1);
if(c1.Checked)
ListBox1.Items.Add(rec.Cells[1].Text);
}
}
public string GetTotal() 3
{
returnTotal:+1.ToString();
}
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page109










*** END OF THE DAY ***












Dt: 20-05-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page110

Repeater & DataList Controls:
These are also DataBind Controls which allow user to provide good
presentation. Unlike GridView these controls are unstructured controls. Which
means user must define the structure as well as the output. The main
advantage of controls bean unstructured is we can defined our own outputs
with own style.
Repeater:
The main advantage of Repeater control is its performance. It is faster in
presenting data.
No builting layers for designing are provided with this control.
No features like sorting, paging & editing is supporting by repeater. If
required we have to manually & logically performed these tasks. Repeater
data list are available from first version of .NET & they have their own
unique features in present in data (Excluding ListView).
The content of Repeater & DataList is based on Templates (no fields only
templates).
HeaderTemplate, ItemTemplate, FooterTemplate, SeparatorTemplate is
all what a repeater has to define its output.
On Example:
- Place Button & Repeater in the form.
- Write code in button to bind the data to repeater.
- Go to SourceView & define repeater content using its Templates****.

Go to Source Page:
<asp:Repeater ID=Repeater1 runat=Server>
<HeaderTemplate>
JOB ID Description MinLevel MaxLevel
</HeaderTemplate>
<ItemTemplate>
<%#Eval(job_id)%>
<%#Eval(job_desc)%>
<%#Eval(Min_lvl)%>
<%#Eval(Max_lvl)%>
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page111

</ItemTemplate>
<SeparaterTemplate>
------------------------------------------------------------------------
</SeparaterTemplate>
Take a new webform name=default.aspx Link button name:ViewData


<asp:Repeater ID=Reperater1 runat=Server>
<HeaderTemplate>
<table>
<th>Job ID</th>
//<th>Descriptiondrag& drop an image on solution Explorer</th>
<th>Description<br/><img src=image.jpg height=70 width=70/></th>
<th>MinLevel</th>
<th>MaxLevel</th> //th means Bold
</HeaderTemplate> //td means Normal
<ItemTemplate>
<tr>
//<td>drag&drop checkBox</td>
<td>
<asp:CheckBox ID=checkBox1
Text=<%#Eval(job_id)%> runat=server/>
</td>
<td>
<%#Eval(job_desc)%>
</td>
<td>
<%#Eval(Min_lvl)%>
</td>
<td>
<%#Eval(Max_lvl)%>
</td>
//<td>Drag& Drop an image in Solution Explorer</td>
<td><img id=m1 src=image.jpg width=100 height=100/></td>
</ItemTemplate>
Repeater Task:-
Create a table called
- SiteInfo
- SiteName
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page112

- Description
- RelatedSite1
- RelatedSite2
- Rating

Design a web form exactly like Google search screen. When user clicks on go take the
keywords typed in textbox & display the relevant sites information same like Google
result.






*** END OF THE DAY ***








Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page113

Dt: 21-05-2010
XML is for limited Storage and No Security
XML File Storing Data
XML Schema Structure
XSLT Presentation
DataList Control: -
The unique feature of DataList is it can produce data in the form of columns
every column will contain a record instead of field like GridView.
Unlike repeater columns task cannot be performed using repeater/GridView
also.
DataList Example:-
- DataList Unique Feature.
- Images Presentation.
- XML File.
1) Add New item and create one XML file. Enter some records information inside it
so that we can present this data using DataList.
<?xml version=1.0 encoding =utf-8?>
<ItemRoot>
<Item>
<id>9177_1</id>
<description>Brand</description>
<feature>Music</feature>
<seller>SunFlower</seller>
<price>3000</price>
<images>~/shlmages/9177_1.pjg</image>
</Item>
<Item></Item>
<Item></Item>
</ItemRoot>
In our data we have one column called Image, this column provides the path of
image where it is located, today almost all web applications use path
maintenances for images.
<images>~
</images>
~Means root directory of project in ASP.NET the other way of maintaining
images is using database BLOBS (Binary Large Objects) today what is Max size
for BLOB?
4GB and can be extended till unlimited for this we have to write code to refries
data from backend into Memory Stream object and present it in image control*.
2) Grate Images folder and place all images which are mentioned in the records.
Right Click New Folder ShImages
3) Create a form and place Button, DataList.
4) In button write code to read data from xml file and bind it to DataList.
Note: - In .NET we can access XML in 3 ways,
a) DataSet
b) System.xml.namespace
c) Linq To xml**
In our example w will use DataSet to read xml data and bind dataset to DataList.
Map path (Items.xml).
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page114

Note:- Map path will cannot logical directory to physical directory and provides the
real path. It is useful method because our files are accessed with virtual name.
C:\\NitApp\EDMBE\Items.xml

Ex:- DataSet Shift+ Alt+ F10 It is used for working class with automatically
namespace is added of that class.
Using System.Data
protected void LinkButton1_Click()
{
DataSet ds=new DataSet();
ds.ReadXml(MapPath(Items.xml));
DataList1.DataSource=ds;
DataList1.DataBind();
}
5) Go to DataList Source View and write code to display image followed by other
information.
<asp:DataList ID=DataList1 runat=server>
<ItemTemplate>
<asp:ImageButton ID=m1 runat=server
ImageUrl=<%#Eval(Image)%> Height=150 Width=150/>
<br/>
<asp:LinkButton ID=link1 runat =server
Text=<%# Eval(description)%>>
</asp:LinkButton>
<br/>
<img src=ShImages/bin.gif/>
<%#Eval(Price)%>
</ItemTemplate>
</asp:DataList>
6) Go to DataList backend set some auto format followed by some properties to
control the layout. CellSpacing, CellPadding, RepeatColumns, RepeatLayout,
RepeatDirection, etcare some useful ones.
Cell Spacing = 2
Cell Padding = 4
RepeatColumns = 3
RepeatDirection= vertical/horizontal.
Repeat Column is unique features of DataList and when we set it to 3 it displays in a
row 3 records RepeatDirection provides the order in which the records should be
displayed.
Are there any content in output to select?
ImageButton and ListButton.
*** END OF THE DAY ***
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page115

Dt: 24-05-2010
In our example to handle selections we have to use a concept called Bubbled Events.
What is a bubbled event* & its Use?
When a container control like GridView, DataList raises an event in response to
post back caused by their child controls is called bubbled event.
They will help user to wire generic code & perform common & specific tasks.
(Bubbled events, routed events are new).
Is RowEditing a bubbled event? YES/NO
YES, for all post back caused inside DataList & Repeater we have
ItemCommand Event. For GridView we have RowCommand Event. We must use
these events & perform all our postback selections.
How to use these Events?
On our example we have ImageButton& LinkButton which can cause a
postback. For these postback controls we have 2 attributes/properties called
CommandName** & CommandArgument** which communicates with bubbled
event or container event.
Add New item web form default.aspx

Go to SourceView & add CommandName, CommandArgument as follows to
postback controls.
<ItemTemplate>
<asp:ImageButton Id=m1 runat=Server
CommandName=m1 CommandArgument=<%#Eval(Image)%>
ImageUrl=<%#Eval(Image)%> Height=150 width=150/>
<br/>
<asp:LinkButton ID=link1 runat=Server
CommandName=l1 CommandArgument=<%#Eval(id)%>
Text=<%#Eval(Description)%>
</asp:LinkButton>
<br/><img src=ShImages/bin.gif/>
<%#Eval(Price)%>
</ItemTemplate>
<selectedItemStyle BackColor=#E2DED6 Font-Bold=True.>
</asp:DataList>
</form>
</body>
Go to DataList & select ItemCommandevent & write the following code:
- protected void DataList1_ItemCommand(object.)
{
if(e.CommandNmae==m1)
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page116

Response.Redirect(Show.aspx?img= e.CommandArgument.toString());
else if(e.CommandName==l1
Response.Redirect(details.aspx?id= +e.CommandArgument.ToString());
}
}
Based on selection mode inside GridView or DataList we have called diff. pages
carrying the current page selection. For ImageButton we have pass the name of
image & for Linkbutton we have pass primary key of table. So that we can
retrieve data from database a way in the new page using primary key value.
When want to interpret data binding process then we can use the events which
are provided the bound control. This requirement is unique & solution to this
also performed in unique way with supported events.
DataList has an event called ItemDataBound & ItemCreated which can be used
to perform this type of action. In our example select DataList & choose
ItemDataBound followed by code to Highlight the total row & also create
control at runtime.
Shop.aspx.cs:
protectedvoid DataList1_ItemDataBound(object sender, DataListItemEventArgs
e)
{ // for every row -- v v Important
if (e.Item.ItemType == ListItemType.Item
|| e.Item.ItemType == ListItemType.AlternatingItem )
{
Label l1 = (Label)e.Item.FindControl("lp1"); // price

if (Convert.ToDouble(l1.Text) < 5000)
{
e.Item.BackColor = System.Drawing.Color.LightGreen;
ImageButton i1 = newImageButton();
// i1.Height=....
i1.ImageUrl = "~/picture1.gif";
e.Item.Controls.Add(i1);
}
}
}
In our demo replace
<%#Eval(price)%> with <asp:Label ID=lp1 runat=server
Text=<%Eval(price)%>/>
// (understand why this change)









*** END OF THE DAY ***

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page117

Dt: 25-05-2010
FormView & DetailsView:-
GridView, Repeater & DataList doesnt provides any inserting option for adding
records. (Which not a drawback).
Normally insert in done using standard & other controls. ( Foster, un-structure
Unique Features)
Still in ASP.NET 2.0 to support inserting for data in DataBinding style we are
provided with FormView & DetailsView.
Both these controls are unique in providing inserting options.
Both these controls are derived from GridView base classes which mean they
support GridView tasks like editing of data, paging of data, etc
Why 2 controls to provides inserting?
Ans:- DetailsView is based OnFields like GridView & FormView is based on
templates like repeaters like Repeater & DataList.
Based on Requirement i.e., if unstructured requirement then FormView
otherwise DetailesView.
Ex:-
These controls are most used with DataSource controls not programmatically. In
some cases we can even use programmatically.
Palce SqlDataSource or any other datasource in the form & configure the
database/ table for it. Ensure that Generate Insert, update & Delete
statements is selected in advanced button option.
Place DetailsView or FormView control & assign DataSource to the created
Control.
In Details View/FormView go to smart tag & enable all the required options like
editing, inserting *, etc



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page118




We can use smart tag EditTemplates options also in order design the layout.
This feature is available for DataList, GridView & these 2 controls.
Ex-2:- A form with all CRUD operations including all types of view.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page119

Ex:- GeidView Design:

Ex:-DetalisView:-


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page120

SqlDataSource with select/Insert/Update/Delete
GridView DataSource as scalds & Enable editing, all
DetailsView DataSource as scalds & Enable only Inserting
Select DetailsView & Set default Mode Property to insert from ReadOnly.

Master / Details output using GridView (can be done with other controls also)
Jobs master table
Employee child table
C: //... (Right click) add a new form webform default3.aspx


Drag & Drop 2 GridView Controls in the default3.aspx





Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page121

GirdView1: (select all enable paging, sorting, selction, updating, deleting)

GridView2: go to properties (EmptyDataText=No Selection Mode)

OUTPUT:-

Note:-EmptyDataText property of gridview displays text when there are no records in
data object***.
Note:-Repeater no editing& also property EditIndex.

*** END OF THE DAY ***
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page122

Dt: 26-05-2010
ListView Control:- (Its new control from 4.0)

ListView Goals:-
- Template list control completes the ASP.NET 2.0 data bound control
family.
- Allows developers to completely control the rendered markup.
- CSS & scripting friendly.
- Full support for data source capabilities.
- Satisfies common client requests.
- Rich design time experience.
- Finally simple to use.

ListView Structure (Little New):
<asp:ListView DataSourceID=MyDS runat=Server>
<LayOutTemplate>------------------------(1)
<Ul>//ul=underline
<asp:Placeholder ID=itemplaceholder runat=server/>
//itempalceholder----------------(3)
</Ul>
</LayOutTemplate>
<ItemTemplate>----------------------------(2)
<li><%#Eval(value)%></li>
</ItemTemplate>
</asp:ListView>


Other familiar Templates:
AlternatingItemTemplate
SelectedItemTemplate
Item SeparatorTemplate
EmptyDataTemplate
In .NET 4.0 we can use ListView without a layout template which is another
feature that it provides.
Conclusion:-
ListView can work like all other Controls***.
ListView can be Templated ***.
ListView need not be Templated ***.
Note:-
(1). Layout Template defines static markup to contain repeated items.
(2). ItemTemplate is repeated for each data object row & contains binding statements.
(3). Layout Template must contain runat=server control\w\itemplaceholder ID

VS.NET 2010 design time view will really make user develop ListView outputs
easily. Because writing layout template for structured & unstructured may not
be very easy for a developer & this is what the design time view helps user. It
helps user to generate layout template for almost all types of presentations.


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page123




Note: - we select one by one then the preview Box see the coding of that particular
task.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page124











*** END OF THE DAY ***















Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page125


Dt: 27-05-2010
ASP.NET Configuration:-
For any application configuration base development is more preferred.
The only reason to avoid configuration is when we have to write lot of additional
code & maintenance.
Most part of .NET is designed based on configuration. CLR based on
configuration & most of the libraries are also based on configuration settings.

Note: -(WCF File)
.NET 1.0/1.1 -- CLR 1.0 /1.1
.NET 2.0 -- BCL + CLR 2.0 *****(Successful version)
.NET 3.0 -- BCL + CLR 2.0 (wpf, wcf, wcs, wf)
CLR 2.0 based on config file
.NET 3.5 -- BCL + CLR 2.0
AJAX, WEF +, EDM, LINQ
.NET 4.0 -- CLR 4.0
(All are supported with settings inside CLR)
Note: - compare to .net 3.5 & 4.0 config file code
Like earlier versions no need to handle config file carefully. Only user defined or
application related settings are required to be given.
In .NET 3.5 we have to maintain config file carefully because it has AJAX
settings as AJAX is first time added as part of .NET in 3.5
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page126

Before 3.5 AJAX was separately installed. Separate AJAX 1.0 is provided in
ASP.NET website for .NET 2.0/VS 2005 people.
How Confn should be implemented?
Ans:-No need to implement on our own we cannot.
How configuration support is provided?
Ans:-All predefined files & settings will be provided- just use them add some--
modify many & complete the process.
Even for custom config files a support is given.
What is that support?
Ans: - confn support is provided with 2 files
i). Machine. Config
ii). Web.Config (For desktops app.Config)
Common paints for confn files:
These are simple text files & can be edited using any simple text editor.
These are xml formatted (case sensitive) & any xml programs can use these files
or they can be directly edited because xml is human readable.
* They are automatically cached on memory for faster retrieval of settings
(Cache memory programmed memory area).
* Processed in hierarchical manner which means every configuration file
inherits its parent configuration file settings. The root for all these files is
Machine.Config.
Also called as configuration inheritance apart from this configuration is also
hierarchical as xml is hierarchical.
Machine.Config points:
It is called per-server basis file. Only one machine.config is allowed for one
runtime/server.
Located .NET framework folder not on our project & all settings are common to
all websites running in that system. * 4 MB (default)(more than 4.0 go to
machine.config one file- change)
Most of the settings are maintained by administrator but not by application
developers.
Web.Config points:
It is called as application Configuration file.
**** It is optional today also to have web.config in our application located in root
& can be created sub folders also. We can create multiple web.configs on our
site maximum is how many folders we have in our project.

*** END OF THE DAY ***
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page127

Dt: 28-05-2010
Configuration Structure:-
<configuration>
<section>
<subsection>
..
</configuration>
A user should know the setting importance the section under which it comes and its
syntax.
i). <appSettings>
In ASP.NET one excellent method to create application wide static variables is using
<appSettings>tag.
In ASP.NET static variables are not recommended dont use them. This setting comes
under configuration i.e., <root>tag.
Syntax:-
<appSettings>
<add key=a value=100/>
..
</appSettings>
System.Configuration is the namespace where all configuration relevant classes
are present in assembly (System.Configuration.dll)
ConfigurationManager(old.ConfigurationSettings) is the class which is used to
retrieve ConfigSettings.
Ex:-create a form and place image/label. Write code in page_load to read
appSettings using the relevant class and its collection.
Add a new aspx.cs
usingSystem.Configuration;
public partial class Default7:System.web.UI.page
{
protected void page_load(object.e)
{
Image1.ImageUrl=configurationManager.AppSettings[logo];
Label1.Text=ConfigurationManager.AppSettings[Title];
}}
A child web.Config file can by default overwrite the parent settings****.
for Ex:-
Create admin folder and create web.config;
Add title appSettings again inside it. All admin pages will get admin web.config
title value but not root value.
We can use appSettings and some other web.Config settings directly in markup
without any coding. (this is a big advantage).
Syntax:-
<%$ Section:key%>
<body>
<form id=form1 runat=server
<asp:Label
Style =fon
Text=<%$AppSettings:Title%>>
</asp:Label>
*** END OF THE DAY ***
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page128

Dt: 29-05-2010
SPECIAL CLASS
AJAX
(Q).Why exactly is AJAX?
AJAX= Asynchronous JavaScript and XML.
AJAX is really a set of technologies working together.
XHTML and CSS for Markup.
DOM for display & interaction.
XML and XSLT for data interchange and Manipulation.
JSON for marshaling objects.
XML Http request for asynchronous communication.
JavaScript for programming it all.
3-Tier Client server Application.
Internet Explorer
With AJAX
Round-trip required? YES
Entire form is not required ****
Partial form is required
Should server read all values? Not Required.
Should server process entire pages? Not Required.
Reducing data during req/response.
Band width effected? YES less bandwidth.
Performance-huge performance.
All browsers started supporting this type of communication. By user 2005 all user/
browsers with drawback also started implementing AJAX..
AJAX------ Asynchronous Communication partial page outputs/processing.

Dis-Advantages:-
1. AJAX is very very very.100 times Difficult to program.
2. JavaScript Skills, 2000 lines of JS code means almost like a big project.
3. Security is issue.
4. Browser involvement is issue.
Security, Browser issues are resolved now.
Microsoft ASP.NET AJAX
- JS required for AJAX is provided by ASP.NET AJAX libraries.

User Role:-
Specify where AJAX is required.
How AJAX is required.
ASP.NET AJAX started in a small way as a separate installation and in .NET
3.5 for 1
st
time MS added AJAX extensions (which is part of complete ASP.NET
AJAX) as part of it.
Started in small way and today in 3.5 /4.0 ASP.NET AJAX is really in high end.





Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page129


ASP.NET AJAX: -

In 3.5 only Server-Side.
In 4.0 both Server-Side and J Query.
Client-Side and AJAX control tool kit should be installed separately.

NOTE:- NagaRaju Sir working this sites.

www.Burton.com
www.GetPivot.com








*** END OF THE CLASS****




****AJAX ***












Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page130


Dt: 31-05-2010
After Continue .28/05-2010
ii). <ConnectionStrings>
To define application wild connectionString it is highly recommended to add it
in web.config file <ConnectionStrings> is the tag which we use to define
connectionStrings. Linq, EDM and other dataSource controls use this section
to maintain their ConnectionString which is preferred solution. If comes under
<configuration> like<appSettings>.
Ex:-
<configuration>
<connectionStrings>
<add name=sql con
connectionString=Data Source=..;
Initial Catalog=DBSPM;
Integrated Security=True
ProviderName=System.Data.SqlClinet
Once defined we can use in the program again with configuration Manager
class.
Example to use it:-
protected void Button1_Click(object..)
{
String constr=ConfigurationManager:ConnectionStrings[sqlcon].ConnectionString;
SqlConnection cn=new SqlConnection(cn str);
cn.open();
Label1.Text=Connnected
}
(Q). what is the difference b/w defining cnstr in appSettings and in
ConnectionStrings?
****iii).<Compilation>
- While developing application we need good debugging support (correcting
errors). VS.NET along with. NET provides so many debugging options, like
debug menu, debug windows, Break Points, etc
- All these options simplified users debugging but at a cost of additional code/
symbols. ***
- When we complete our project we must remove all this additional code and
symbols as it is now error free.
In ASP.NET we can use:
<compilation debug= false>user <system.web>
Which means no debugging code will be written in our source code.
Never upload/distribute projects in debug mode-they run very slow.
- A default debug values are also false.
Start debug mode
Start with out debugging
Right click View in Browser (fastest)
Debug true during developing
Debug false during deployment
Default language VB.NET (not C#.NET)
To set a different default language for all runtime code and for entire project we can
use default language attribute of <compilation> tag.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page131

*** END OF THE DAY ***
Dt: 01-06-2010
<system.web>
<system.net>
<mailsettings>
-----------------------
SMTP Specification
(Simple Mail Transport Protected) an open standard protected.
HTTP is for request/response
SMTP is for sending mails.
Irrespective of type of application all must follow SMTP for sending mails.
SMTP servers are those which implements SMTP specification and which are
softwares used to send mails.
As a .NET user our job is to arrange an SMTP server (or) design our own SMTP
server use .NET SMTP Client Libraries in order to send mail to recipient using
SMTP Server.
IIS which is well known as HTTP server also provides SMTP and FTP
functionality.
As a user after arranging an SMTP server we have to write program by
preparing message and other required things and submit it to SMTP server.
Simple Architecture Diagram:-


Libraries of SMTP Server:-
System.Net.Mail(4.0)(System.web.Mail(2.0))
- Mail Message
To prepare complete mail content.
- SMTPClient**
To communicate as client to SMTP server.
To send message prepared to SMTP server.





Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page132


Example:-

using System.Net;
using System.Net.Mail;
public partial class_Default:system.Web.UI.page
{
MailMessage msgobj;
protected void ImageButton1_click(object..)
{
//send button code
SmtpClient serverobj=new SmtpClient();
serverobj.Credentials =new NetworkCredential(TextBox1.Text,TextBox2.Text);
serverobj.port=587; //25 is default for SMTP
serverobj.Host=smtp.gmail.com;
serverobj.EnableSsl=true;//default is false, secure socket layer
msgobj=new MailMessage();
msgobj.From = new MailAddress
(TextBox1.Text,NIT INFO,System.Text.Encoding.UTF8);
msgobj.To.Add(TextBox3.Text);
//..other properties //msgobj.priority =MailPriority
msgobj.Subject=TextBox4.Text;
msgobj.Body=TextBox5.Text;
msgobj.Attachments.Add (new Attachment(MapPath(bg3.jpg)));
msgobj.deliveryNotificationOptions=DeliveryNotifications.Onfailure;
serverobj.Send(msgobj);
Label6.Text=Mail Sent Successfully;
}
}
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page133

*** END OF THE DAY ***
Dt: 02-06-2010
Web.config:
<system.net>
<mailSettings>
<smtp from=nbende@gmail.com>
<network host=smtp.gmail.compassword=secret port=587 username=nbende/>
</smtp>
</mailSettings>
</configuration>
Note:- by writing settings in web.config we can avoid all the value related in our
program, it is useful because for a project most of the time they are common.
Website Configuration Utility:-
Visual Studio .NET provides a tool or utility called website Administration tool (WAT).
Rich simplify the process of handling Configuration file. We can invoke the tool from
solution Explorer or from website menu option ASP.NET configuration.
..
<trace>tag
It will display or generate all the runtime process information for a request can
be used during debugging as well as after deploying.
It includes lot of information staring from client till server execution everything
can be traced.
By default trace is disabled at application level that at root web.configure can use
<trace>to enable it.
Ex:-<trace Enabled=true/>

protectedvoid Button1_click(object)
{
1).response.write(welcome);
//statement level traceing(OR)
2).Trace.Wrtie(1000 records reachedfirst Breakup);
Trace.Warn(Take beckup DB is full); (OR)
3). if(Trace.IsEnabled)
{
for(int i=0;i<10;i++)
{
Trace.Write(i.ToString());
}}}
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page134


Go to Web.Config
================
<Configuration>
<appSettings>
<addKey=Title value=E.Learning Application123/>
<appSettings>
<system.Web>
i). <trace enabled=truepageOutput=false/>
ii). <trace enabled=truepageOutput=false requestLimit=5/>
iii). <trace enabled=truepageOutput=true WriteToDignosticsTrace=true/>
<compilation debug=true targetFramework=4.0/>
</system.Web>
Other important attributes are:
pageOutput=true/false
- default is false & when set to true appends trace results to the page output.
- If false the meaning is trace is generated but should be viewed with trace
utility not in the same page.
- ***Trace utility means in the url remove.aspx page name & type trace.axd
requestLimit=<n>
default is 10
- which means 10 times trace output will be generated after other that no
trace is generated.
localOnly=true/false
- true menas only in localhost system tracing will be generated for other users
only output will be given.
System.Diagnostics*****(refer)
writeToDiagnosticsTrace=true
- Will redirect all trace result to the mentioned diagnostics file for later
viewing.
- All above trace settings are called Application Level tracing & we have page
level, statement level also.
- As part of page directive we can use trace=false attribute to ignore tracing
for the current page this is called page level tracing.
- In statements we have Trace object which will allow our outputs to be app
ended trace results.
Trace.Write..simple black color
Trace.Warn..like warning in red
Trace.IsEnabled-true if currently means in that page trace is on or not.
.


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page135

*** END OF THE DAY ***
Dt: 03-06-2010
In .NET 4.0 we have a template in VS.NET which automatically provides the
standard security model for project.
ASP.NET security for resources is implemented using 2 processes.
1. Authentication
2. Authorization
.
Note: -
Security content:
- Data Security
- Hackers Security
- Public / private content
- Transport level
a. OS windows server 2008-----1
b. IIS web server-----------2(Data Security, Hackers Security, Transport level)
c. ASP.NET CLR----------3(Public / Private Content)
(.NET)
At ASP.NET / Project level we need to implement security with the provided support
(Good for developer).
..
1. Authentication:
- The process of verifying user credential again a data source is called
Authentication. This process after completing the verification creates &
identity which is also called as security ticket (at browser level it is called
Cookie).
2. Authorization:
- The process of allowing or denying a Requested resource based on users
identity is called authorization.
Both these are provided by ASP.NET & ***As a user we have to understand
their methods/support & implement security.

O/Ss , DataBase servers & in ASP.NET
Security Authentication + Authorization.
(User name+pwd) (whether content will be follows)
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page136

In ASP.NET ----Authentication can be implemented in 3 ways.
i) Windows Authentication***(OR)
ii) Forms Authentication****(OR)
iii) Password Authentication.
i. Windows Authentication:

FLOW:Client makes a request secured page
|
- IIS takes the request & check for identify. If identify is not found stops the
user & redirects a login window.
|
- Client enters the credentials that are required for server & submits back to
IIS.
|
- IIS Checks the given credentials against the O/S configured location & on
successful verification it creates an identity which is called Windows
Identity. It then redirects user to ASP.NET & ASP.NET redirects the secured
page to user.
Anonymous windows / IIS Authentication:
- We can configure a website users as anonymous users @ IIS level. The
meaning of setting Anonymous for a website is when unauthenticated user
makes a request IIS will itself create identify & send user to ASP.NET.
- This is compulsory when we want to implement any other authentication
than windows.
- At IIS Level we will have scope to implement Kerberos, MD5(Message Digest)
& SHA (Secure Hash Algorithm)..Windows authentication.
(Q).ASP.NET doesnt support the following security Concept?
a. Windows Authentication
b. Basic Digest
c.
d. None
Ans:- None
Because ASP.NET support above 1
st
3 options.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page137

*** END OF THE DAY ***
Dt: 04-06-2010
ii. Passport Authentication:
- This is a 3
rd
party authentication service provided by Microsoft. Its
Commonly used for Microsoft related websites & can be used by 3
rd
part
people like us. Because passport is Microsoft service, it is native to .NET
FLOW:
- Client makes a Request for secured webpage.
|
- IIS allows user as anonymous which is compulsory to implement any non-
window authentication.
|
- User enters in to ASP.NET & ASP.NET redirects user to passport website.
Because Authentication ticket is not found.
|
- Passport displays login page to user.
|
- User enters passport credentials & submit then back to passport. Passport
checks credentials again its database & creates an identity called passport
identity. This identity is redirected to secured webpage & IIS again allows
user as anonymous. This time ASP.NET returns secured webpage because
user has requested along with passport identity.

Note: -
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page138

Once passport identity is created then access may be granted to other websites
also which is passport identity.
iii. Forms Authentication:*****
- This authentication is performed by ASP.NET itself along with user
instructions (developer)
- This authentication is most suitable for commercial & portal type of
applications. In other cases user accounts are kept with windows/passport
but not with our site. In this case all user info will be with our site only & we
can sue it for every business idea that we can implement.


(Q).How forms Autehntication works? ***
Ans:-
- client makes a request for secured page
|
- IIS allows user as anonymous which is compulsory
|
- User enters into ASP.NET website & ASP.NET has a separate module called
Forms Authentication Module****. Which checks for forms identity, when
identity is not found then it returns a page called login.aspx(fixed name)
present in root directory of application (fixed). [unless changed they are fixed
to their default behavior].
|
- User enters or fulfills the login requirements & submits back to server.
|
- IIS again allows user as anonymous & ASP.NET execute the login page code-
after successful evaluation it redirects secured page to user.
In this step evaluation / executing code is not which is written by system but it
is something which is written by developer.
Important:-Along with secured page the created forms identity is also
redirected to user. Why? So that further requests mode by user are identified
as authenticated.
In project intranet type of apps ----windows.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page139

Internet ---Forms.
*** END OF THE DAY ***
Dt: 05-06-2010
In .NET 4 we have asp.net website template instead of empty website template
which automatically create all the security related content like user interface,
security tags & other required things. We can use this for security
implementation in our website as it is provided with complete standards only.
Anyhow for complete customized security implementation we can even start
empty website & implement complete security.
(Q). How to implement forms Authentication?
Ans: - A plan is required to implement or add security to the project. In our
example we want to create publicly accessible content i.e., for every user who
enters into our site & private access content also***.
STEPS:-
Start a new website (.NET 4.0) & create homepage i.e., a web form with name
default.aspx
Create a folder called Admin So that we can store registered users or admin
users accessible content here (private).
Create forms in admin folder & design them according to requirement say
add.aspx, delete.aspx as samples.
Go to home page that is default.aspx in page in root & create hyperlinks to
admin page content i.e., 2 hyperlinks for Add & Delete pages.
Imp Point:-At this point of time if we execute our project user will get address to
all the pages of site which is not our requirement.
Why?
Because no security is implemented & default is windows authentication with
access to all files as authorization.
Go to root web.config & use <authentication mode = <forms /passport/
windows>>tag to specify forms authentication.
Go to Admin folder & create another web.config using add new item option. In
this web.config we have to change <authorization>using authorization tag.
This tag contains collection of <allow>&<deny> tags, where we can specify
which user is allowed for this resource & which user is denied for the resource.
Syntax:-
<authorization>
<deny Users=<usernames/*/?/>>
<allow Users=<usernames/*/?>/?
..
..
</authorization>
? Represents unauthenticated user/Anonymous user
* Means all users
Ex:-
i) <authorization>
<deny users=?/>
<allow users=Scott, Smith/>
</authorization>

ii) <authorization>
<allow users=*/>
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page140

<allow users=Scott, Smith>
</authorization>

In solution Explorer Web.config click & write following code:
<configuration>
<system.web>
<authentication mode=Forms>/</authetication>
<compilation debug=true>
Go to Admin (Right click) add new item WebConfiguration file add OK.
In that,
<?xml Version=1.0?>
<configuration>
<system.web>
<authorization>
<deny users=?/>
<allow users=*/>
</authorization>
</system.web>
</configuration>
Run the default.aspx
O/p:

Note:- default authorization window; default authentication allow & users
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page141


*** END OF THE DAY ***
Dt: 07-06-2010
Maintaining users & their details for security purpose as well as for other
registrations.
For this we have to store data in DataBase mainly & if for any reason DB
cannot be used then we can go for XML as 2
nd
alternate & lastly even
Configuration file for storing user credentials (total 3 options)
Now in our example we will use database & implement our login part of
security.
Add login.aspx page in the project root directory. Design the page as for project
requirement code for login page should be written after preparing the data
source & writing the required layers in the project.
Go to DataBase that the project is using & create tables required for user
modules like users, roles, usersinroles, etc In our example we will create a
simple users table with Username, password, remarks columns & enter some
sample data.
[write procedures which are highly recommended for accessing the db
tables***. Like CreateUser, CheckUser, AddUser etc If procedures are not
written also front layers can access the data directly from tables which in 2
nd

option].

Now once DataBase is ready with all requirements we have to prepare our
layers BL, DL &UI. So prepare EDM object for users & other tables (if already
EDM object are present then ensure that users tables are also present).
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page142



Add BL for users & write the required methods & code for it.

App_code/DLUsers.cs
pubilic class BLUsers
{
(+) public BLUser()....
(-) public void ValidateUser(DB3PMModel.user userdetails)
{
DB3PMModel.DB3PMEntities obj=new DB3PMModel.DB3PMEntities
var x=(from n in obj.users
where n.UserName==userdetails.UserName
&& n.Password==userdetails.Password
select n).FirstOrDefault();
if(x!=null)
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page143

return true;
else
return false;
}
public void AddUser(DB3PMModel.user userdetails)
{
//code to add the record in entities
}
Go to login button code of login.aspx & write code to pass userdetails to
blusers from textboxx. get the Boolean result & based on it create forms
authentication ticket.
protected void Button1_click(object....)
{
DB3PMModel.user objuser=new DB3Pmmodel.user();
objuser.UserName=TextBox1.Text;
objuser.Password=TextBox2.Text;
BLUsers blobs=new BLUser();
if(blobj.ValidateUser(objuser))
//create ticket
FormsAuthetication.RedirectFromLoginPage(TextBox1.Text,CheckBox1.Checked);
else
Response.Write("Invalid UserName/Password-Retry");
}
Note:- in login.aspx using System.web.security;//namespace for securtiy

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page144



*** END OF THE DAY ***

Dt: 08-06-2010
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text,CheckBox1.Check
ed);
System.Web.Security is the namespace where we have all security related
content.
FormsAuthentication is one class where we have different methods to maintain
identity.
One useful method in it is RedirectFromLoginPage which takes input as 2
parameters.
1. Identity name
- This name is which we specify in allow-deny options. It need be always
username only-sometimes in our logics we provide groupname, foldername,
filename and also as our identity and write allow denys accordingly***.
Ex:-Users
Username password group/role
Scott tiger manager
Smith 123 manager
Ram 123 call Center

2. Identity should be persistent or not is the second parameter. We indicate
this with a bool value.
If true is specified then the identity will stored in browser location(client)as
persistent value i.e., physically stored. (also called as cookies).
Even when we close our browser & system the identity remains on the dick.
For next visit no login page is displayed because the identity will be sent along
with the request.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page145


If false then also the identity is created & sent to client but stored in memory,
not in disk & persistent as long as user is working with website.

In internet Browser options go to tools internet optionssettings view
files go end Cookies open it.
This method (login page) after taking inputs performs 2 tasks,
a). Creates forms identity & based on true /false sets the storage option with browser.
b).Automatically redirects user to the requested secured page. We have some other
methods like setAuthCookie() also to create identity but they do not redirect
automatically in every situation.
(Q). How FormsAuthentication knows about the secured page from login page?
Ans:-
Login page will be displayed with one query string argument called ReturnUrl
which will contain the secured page name which user requested.
When no returnUrl is present then system will redirect user to home page i.e.,
default.aspx. this situation might occur in many cases & one case directly
requests login.aspx page.
***(4.0) To change the default login.aspx for authentication & home page as
default.aspx for returnUrl case we can use <authentication>tag only and set
like this.
<authentication mode=Forms/>
<forms loginUrl=Valid.aspx defaultUrl=home.aspx/>
</authentication>
Web.config
<configuration>
<system.web>
<authentication mode=Forms>
<forms loginUrl=valid.aspx defaultUrl=inbox.aspx>
</forms>
</authentication>
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page146


Using these options we can change the name of file as well as the location of
file.
*** END OF THE DAY ***
Dt: 09-06-2010
SignOut() Method of FormsAuthentication:-
This method removes the created authentication ticket (both persistent & in
memory) we can use it to SignOut or forget user credentials from our site.

We can use user, identity, Name & other properties can be used to display the
user authenticated ticket name. we can also use separate category controls
called login in ToolBox for some of security implementations.
For example LoginName is one control in login category & it also displays
logged in user name.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page147


In Admin/Add.aspx.cs
Public partial class Admin_add:System.web.UI.page{
protected void page_Load(object..){
Label1.Text=user.Identity.Name; // (or)
Label1.Text=Hi,+Identity.Name;
}}


Write the following code in default.aspx.cs
public particular default:system.web.UI.page
{
Protected void page_load(object.)
{
Label1.Text:User.Idnetity.Name;
}
}
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page148


Drag and Drop one LoginName& LoginStatus in Add.aspx & Default.aspx





Out Put:-
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page149


Next


In default.aspx.cs
protected void..
{
if(User.Identity.IsAuthenticated)
}
Login controls:-
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page150

Login Name
Login Status
Login View
All login controls are originally design for a diff. security concept called
MemberShip. We have use those controls of login which are based on
authentication & can be used for both members ship as well as for request
some manual handling for example login control of login category.

In login.aspx.cs
{
DB3PMModel.User
objuser.UserName=Login1.UserName;
objuser.Password=Login1.Password;
}
In Login.aspx.cs
protected void Linkbutton1_Click(object..)
{
Response.Redirect(~/login.aspx);
}




Note:- C://(RightClick) Add new item web form Register.aspx
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page151


Double click LinkButton write following code:
protected void Button1_Click(object.)
{ // register
DB3PMModel.User objuser=new DB3PMModel.user();
objuser.UserName=TextBox1.Text;
objuser.Password= TextBox2.Text;
objuser.Remarks=textBx3.Text;
BLUsers blobj=new BLUsers();
blobj.AddUser(objuser);
LinkButton1.Text=Registered Successfully-click to Login;
}
}
Open App_code BLUsers.cs (go to BLUsers)
public void AddUser(DB3PMModel.User Userdetails)
{
DB3PMModel.DB3PMEntities obj=new DB3PMModel.DB3PMEntities
// obj.AddToUsers(userdetails);
obj.users AddObject(userdetails);
obj.SaveChanges();
OutPut:-

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page152

try
{
DB3PM..
}
//catch (Exception)
Catch (Exception e)
{
//throw new Exception(user always Exist);
Label1.Text=e1.Message;
}
}
In Register.aspx

OutPut:-

In our users table add hintqn, hintan, email columns & provide same while
registering.
In admin folder create another page called changepassword.aspx design it &
accordingly write code user EDM layers.
In login page provide forgot password then Recover Linkbutton & Design
separate form where user can recover password based on hintqn & answer.
Password should be sent to registered emailid.



*** END OF THE DAY ***
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page153

Dt: 10-06-2010
Identity/Ticket will travel between every request & response. It is very
important to understand how it travels & in what mode the identity travels.
By default server uses HTTP Cookies to make this identity travel because
cookies have the functionality of making values travels between
request/response.
(Q). Why forms Identity is created as Cookie by Server?
Ans: -Because identity needs to travel between request/response which cookies
has.
Problem here is Cookies are owned/maintained by browser & browser can
reject/disable cookies. In such cases our authentication will not work server is
dependent on click Browser.
Internet Browser Tools Internet options
1. security custom level default levelmedium to drag high.
2. Pri. change to block all cookies OK.
One option is to ask user for enabling cookies & display the content normally.
Other option is maintaining identity without cookies. In ASP.NET version 2.0
CookieLess sessions & Cookieless authentication is provide. Using this we can
pass identity information with URL of Browser, but it will be visible to the user.
To do this we have one attribute for forms tag called Cookieless.
<forms Cookieless=>
Where we can specified how authentication ticket should be maintained.
Note:-
1. HTTP Traffic Tools.
2. Internet browser Tools web development helper
Open new web form web location:HTTP selected.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page154

Web.config
<authentication mode=Forms>
<forms Cookieless=UseUri>
</forms>
</authentication>

















*** END OF THE DAY ***








Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page155

Dt: 11-06-2010
Web.config
<authentication mode=Forms>
<formscookieless=AutoDetect require SSL=true></forms>
<authentication>
Cookieless=autoDetect
- Use cookies if enabled or use URI.
RequireSSL=true/false
- http://...
- http-SSL



requireSSL=true/false
- Means the communication for security should be performed in SSL mode for
which both client & server should support SSL.
Protection =All(d)/Encrypted/validated
<forms requireSSL=true protection =All>
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page156

- Protection by default forms Authentication identity is encrypted and
validated. If we want to reduce this level of security we can say only
encryption or totally avoid it none. It is highly recommended to use All
only.
Note:- web.config
<forms requireSSL=true protection=>//(.it will be taken default all)
- All the aboveoptions transport level security options that ASP.NET, IIS
integratedlly provide to user. These all security mechanisms are popular &
provided successfully in web security with all these we can make our
website as secured website.
- Another recommended options in forms tag to change is name attribute.
(Q).What is this name attribute?
Ans: - what we pass for creating authentication ticket is value but not variable
name.
Variable name a=10 validation
?=Scott
.aspxauth = Scott
.aspxauth is the default variable name which ASP.NET uses in order to store
the value. It is recommended to change this, otherwise it may lead to conflicts.
<forms name=prjsecure>
Note:-
ASP.NET web site template will by default create all security implementation to
the project which includes,
- DB creation
- Procedures writing
- Data Layer /Business Layers
- User interface with changes
- Etc
Empty website as its name says doesnt create any file and everything user
must configure which is more recommended.
For an Empty website also we can ass membership manually on our own also.
For this we have to use ASP.NET configuration tool & security tab in it. This is
also well known as ASP.NET Membership.
Note: - SQL Server Express Edition.



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page157

QUERYS:-
1. What is Rendering?
2. Why Rendering?
3. Types of Authentication? Passport Authentication?
4. Static Constructor? C#
5. Backup?....Ado.Net 2.0,.
6. Types of inheritance? Explain two?
Ans:- interface inheritance, implementation inheritance
7. Abstract class?
8. About Singleton?
9. What is stored procedure? (Execution process)
10. SQL Server?





















*** END OF THE DAY ***



















Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page158

Dt: 14-06-2010

STATE MANAGEMENT IN ASP.NET

Web Application irrespective of platform & other environments they are
stateless. Which means every request is identified as new request. Application
today provide high-level of state management with good performance &
simplicity earlier that in first generation of web. We have only database & one
or two objects that support (or) which where used for providing state. Today so
many new method, objects & services are provided which help in state
management. ASP.NET has good support expressly with .NET 4.0 we can do all
sorts stateful activities.
Web applications stateless (HTTP) (Use:- performance)
Small website Stateful.
ASP.NET has very good support for implementing state because many
Microsoft products are attached to this environment & which makes stateful
applications like,
- Virtualization in 2008, velocity as service & other.

(Q). WhatSTATEFULL ACTIVITIES are Required?

1. During request & response for a page our control values should be retained.
2. Some behavior for all objects/variables that we use in our page is also
required.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page159


3. Values of one page controls as well as variables & objects should be
available in other pages also for every individual user.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page160

4. Values of one page / variables when created should be accessible to all
users of application. Ex:- News


5. Values / Data of one site should be accessible to other websites also in
universal accessible method. (other sites are called SOA(Service Oriented
Architecture )-Distributed Environment).
Ex:- amazon.com, yahoo.com, fliker.com, google maps, mail..

ASP.NET SOLUTIONS:
QueryString
Server.Transfer
CrossPage PostBack
ViewState Object****
CookiesHTTP Concept****
Sessions/Profiles***
Application***
Cache**
WebServices/WCF***
Velocity***
All above concepts/ objects are support provided by ASP.NET to fulfill state
requirements & some of them are implicitly maintained. Where our job is just to
understand them & some of them are explicitly implicitly for business
requirements.
- Server.Transfer(<page>, true).






Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page161







*** END OF THE DAY ***























Dt: 15-06-2010
i. Retaining control values during request/response
In ASP.NET controls & page stage is implicitly provided o need of writing any
additional code for maintaining control state. We also have options to enable,
disable & also inherit the state management feature to controls. In .NET 4.0
this new support of enabling, disabling & inhering is provided.
How state is provided by ASP.NET for its Controls?
With a concept called ViewState.
When a client, makes a request for an aspx page, it will be processed at
server & all the result produced is concatenated as a single string along with
some hash values in it.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page162


These concatenated values are converted into base 64 format***. These base 64
values are stored in one or more hidden fields*** by server sent to client along
with other from contents.
User adds/modifies the content & resubmits the form to server. Server first
reads the hidden field values so that it retains the last given values (act as
stateful) &responds the same process with new repeated as long as user is
working with current page....

Some controls doesnt need state only some controls few properties only need
state very few controls need complete set as state.
All these are maintained by ASP.NET only.
This work is done onlyfor ASP.NET controls but not for variables & objects that
we declare in code window of the page.
Every page one property called ViewState using which we can store our data
also as partof asp.net concatenated string.
ViewState is of type called StateBag class which is of type object. Because of
type object ViewState can store any type of data inside it- the only condition is
the content should be Serializable***.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page163









Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page164





*** END OF THE DAY ***

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page165

Dt: 16-06-2010
C:// .(right click) add a new item web form default.aspx

Default.aspx


Default.aspx.cs
publicpartialclass_Default : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) //1st Request
ListBox1.Items.Add("JAVA");
protectedvoid TextBox1_TextChanged(object sender, EventArgs e)
{
}
Output:-

Drag and Drop TextBox in design page


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page166


publicpartialclassDefault2 : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) //1st Request
ListBox1.Items.Add("JAVA");
TextBox1.Text = "Hello";

}



publicpartialclassDefault2 : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) //1st Request
ListBox1.Items.Add("JAVA");
TextBox1.Text = "Hello";
Label1.Text = "Welcome";
}
in source:
<%@Page EnableViewState=false Language=C#%>


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page167



Design-

When we execute this form we will get new values add at run time in page load
first Request. When we past back the form newly added values are loss
because we have set view state mode property to disable.
The default value for view state mode is inherited which means it will take the
setting of its parent control. Because of this option we can really handle view
state data according to our versions. This property also makes ASP.NET control
more valuable as in old cases they were pointed out as Heavy data & traffic
control.
More Advanced options of ViewState:
(Q). Is ViewState data Secured? How can we secure it?
No some time we want to secure ViewState data also. To do this we have one
property / attribute for page called EnableViewStateMac=true/false(d).
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page168

Mac here points machine key validation which is one encryption provided by
ASP.NET. When set to true every value will be encrypted & sent between
request & response.
To further customize this encryption in web farming & other levels of
encryption.We can use <machinekey>tag of web.config which has various
options.
(Q). Can use secured ViewState data?
Ans:- Yes.
Distributing one project to two PCs called web forming.

Web farm:project in multiple machines.
(Q). Does ViewState has on impact on server?
What type of data we can store inside ViewState?
Ans:- Normally server should have no load/impact because server doesnt store
any data related to client w.r.t ViewState but when complex types like DataSet
is used then server has to undergo every time Serialization & Deserialization
which is a load to server. So use ViewState but with less complex types.
Note: - serialization
In program Menu Test windows.
Any type of data but Serialiazabledata. In .NET very few objects are not
Serialiazable.
We can also restrict the size of ViewState data using configuration settings.
This setting will help user to accidentally increase the size of ViewState & make
the load.
Ex:-
try
{
ViewState [ds1]=dsjobs; //jobs 400 records
}
Catch()
{

}





*** END OF THE DAY ***


Dt: 17-06-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page169

MULTIPLE PAGES STATE

With ViewState we can provides only current page state which means once
user navigates to other page the current page ViewState is lost. Also if browser
is closed or redirected to other site etc will lose the ViewState.
If we want multiple pages state i.e., a value created in one page accessible to
other pages then we have different options to do it.
Some basic or limited usage options are QueryString, Server.Transfer &
CrassPage PostBack.
Some very important & also most used options are HTTP Cookies***,
Sessions** & others.
QueryString, Server.Transfer & CrossPage PostBack need some code from user
or they are limited to 2 pages state whereas Cookies, Sessions are not limited
& also provide automatic state between multiple pages of site.

HTTP Cookies

A concept of HTTP which every web related user can use.
(Q). what is a Cookie?
It is a name=value pair just like variable which travels automatically
between every request & response.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page170


Cookies are based on domain where we created them.
Cookies only maintained by browsers. It is browser which decides to accept
a cookies or not & also to send cookies to different Servers.
Cookies are of 2 types,
1. In-Memory Cookies
2. Persistent Cookies

1. In Memory Cookies:
It is developer who decides whether cookie should be persistent or In-Memory.
(Q). what is In-Memory Cookies?
Ans:- A Cookie which is available as long as user is working with current
session is called In-Memory Cookie. It is also called as Session Cookie.
2. Persistent Cookies:
A cookie which is stored in client physical location is called persistent cookies.
These types of Cookies are available online as well as offline***.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page171


Client, server will be closed then the CK Result(stored hard disk) will be
available
.
(Q). Websites developed using Cookies are dependent on client (Y/N)?
Ans: YES.Because Browser has the right to deny Cookies.

(Q). Can we create any No. of Cookies per domain? Is there a limitation on
size of Cookies and type of data?
Ans:- NO, -- Browsers limit the no. of Cookies per domain (20) 1MB.
Only simple type of data can be stored not complex types like dataset,
employee etc
Username, preferred color, shopping cart items etc are the most used
Cookies.

(Q). How to create Cookies in ASP.NET?
2 ways to create a Cookie.
Old method (or) ASP method
-----------------------------------------------
Response.Cookies[<cookiename>]=<value>.
Response.Cookies[<ckname>].prop=value;


Preferred & Type-safe method
------------------------------------------------
Using HttpCookie***class of System.web namespace.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page172




*** END OF THE DAY ***


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page173

Dt: 18-06-2010
Example for persistent Cookies:


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page174


OutPut:-


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page175



Note:-All state Management options (not cookies)starting from ViewState till
application are not reliable, So write code to check for their presence & perform action.
More Cookie Points:-
Cookies are not safe is one reason to avoid cookies for eritial information like
credit cord details, bank details, passwords etc

Because cookies travel in plain textual format in the form of Http headers.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page176

(Q). cant we make cookies secured?
Ans:-YES. We can encrypt a value & store it inside a cookie so that if user reads
it it will not be readable. (Or) cookies have a property called secure which can
be set to true.
ckobj.Secure=true
When set to true cookie value will be encrypted in SSL format (automatic
supported by client & server).
In Change.aspx
Labels.Text=Request.Cookies[country].value;
system.web.Security.formsAuthentication...
Single valued & multi Valued Cookies***.
HttpCookie ckobj=new HttpCookie(user);
ckobj.value=100; //single valued cookies
ckobj.values[name]=SCOTT;
ckobj.values.[email]=scott@gmail.com;
Response.Cookies.Add(ckobj);
To read
string s =Request.Cookies[user][name]
(or)
HttpCookie ckobj=Request.Cookies[user];
string s=ckobj.values[name];
In a Multivalued cookie if one value is changed all other values are last.
Still if we want to change then logically we have to transfer first existing
values and modify followed by re-transfer.
How to remove a cookie? How to find whether cookies are supported by
browser or not?
There is no command to remove a cookie. The only one to delete a cookie is
to specify expiry time which is expired.
Ex:- ckobj.Expires=DateTime.Now.AddDay(-1);
To find whether cookies are supported or not request object has a method
but again it want be accurate. The only way to check whether browser
supports cookies are not is to create and read cookie. If unable to read
conclude as not supported.
Response.Cookies.Add(ckobj);
If(Request.Cookies[ckobj]==null) //not supported
Has Cookies completely supported the multilevel page state?
Ans: - NO,
Security
Complex types
Unlimited size as well as Numbers.
To farther implement multiple pages state we have to go for server side
options. All server side options are secured.



*** END OF THE DAY ***



Dt: 19-06-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page177

SERVER SIDE STATE MANAGEMENT:
Application object of ASP.NET
Session object of ASP.NET[profiles(its dependent on SQL Server)]
Cache object of ASP.NET
Application object of ASP.NET:-
All ASP.NET applications are hosted under IIS.
Cassini (it is use temp) is standalone not production development.
IIS hosted applications will have many features of IIS starting from
application pool allocation till the priority of apages execution.
WCF Question-
One of the good features of IIS is automatic startup& automatic Shutdown of
application.
Any project we start, when we put under it, then IIS is automatically start,
and automatically shutdown of applications.
Ex:- consol, cloud

Automatically IIS work with this project
(Q).Which application?
Ans:-Any type of application.
(Q).Imp Question:- Can we restrict the Cookie for particular portion of a
project?
Ans:-YES,
ckobj.path=dir1 > under change.aspx(under button)
(. Path=string)
So all asp.net apps start automatic and shutdown automatic.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page178


.NET tell us, threads are not use in ourprojects.
Cmd.Execute non-Query();
Cmd.Begin Execute Non-Query(); //thread
These 2 are same.
In ADO.NET, Remoting, windows etc that has normal method and thread
method also there, but we use normal method.


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page179


Here O/S doesnt know there is one app is there. But is maintain by CLR.
Here one App didnt crash then CLR kills that App and restart same app newly
but not affect other applications.
In that time media player run under COM when problem occursthen also here
CLR also affected. So rectify this problem media player also developed under
.NET.


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page180


One App domain is not communicating with other App Domain; this is only
done by Virus.
So CLR rectify this problem do remotting means communicating two
AppDomain.
(Q).Any application split into many app domain Yes or No?
Ans:- YES,
(Q). When ASP.NET application (appdomain)starts?
Ans:- When first user makes a request for a resource in application then starts for
further users same application email be served which means it want start again for
every user.

(Q). What is dll hell in .NET?
Ans:-No registry concept for .NET assemblies.
(Q). When ASP.NET application ends?
Ans:-when all users of the site leave and all resources allocated are destroyed then
ASP.NET application ends.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page181


Application object of ASP.NET allows a user/developer to refer this created
process.
Application. refers to the created process.
This is one reason to call ASP.NET project as an application.
App started for every user not for particular use.
Once application is started for every user another process is started (by default
within the application) called exclusively for identifying user and his
requirements.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page182

One millions users have one millions sessions in one application.
Session is used for uniquely identify the every user.
Ex:-
Authentication
Ticket
Persistent
Cookie
Session Id





*** END OF THE DAY ***






Dt: 21-06-2010
Application/Session objects use: -
Which developing a web application we can use that objects in 3 diff. ways (in .NET
4.0)
1. In use form of events:-these are provided by ASP.NET only & help greatly &
also uniquely to write some tasks of application.
2. For state Management: -To store data @ server in the form of private as well as
public we can use these objects.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page183


3. Configuring the default behaviors (4.0): -
All applications/ session events cannot be written in any location that we want
whereas application/session data can be created/used in any part of executable
statements.
Special file called GLOBAL.aspx is provided by asp.net to handle app/session
events primarily.
This file is not assed by default in empty website & in some other web sites but
in most of the new topics / concepts this file is automatically added like MVC,
Dynamic Data etc
In is highly recommended to use this file & write some logics related to
application.
A project can have only 1 global.aspxfile only.
It is configured to reject direct requests.
For any request this file is executed first & then the other process. (reason to
call it as application file).

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page184



(Q). what global.aspx contains?
Ans: -It contains all events related to application / session & also it can be used to
create older COM components which are accessed again globally.
So many Application events are available & some common i.e., most used are
already provided inside this file. We have to just write code here.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page185



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page186






*** END OF THE DAY ***



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page187

Dt: 22-06-2010
Session Variables & their Settings

1. Where we can create application Variables?
Anywhere in the application.
2. What is the scope of application variable?
Accessible to all users of application, irrespective of the user who created it.
3. What type of data can be stored in application variables?
Any type of data because they are of type object.
4. Any limitation in app variables & its size?
No limitation but load on server should be considered.

All session variables are accessible to current user only.
Session variable are also of type object which means they can store any type of
data (Load on server should be considered).
Session data will be stored @ server only & only session id travels. This data
will be available as long as session is preserved by server. Sessions are normally
ended based on timeout***. In ASP.NET by default 20 mins it the timeout (idle
timeout) using configuration settings as well as programmatically with session
object we can change this default time.
A session can be ended programmatically also. Session object has a method
called Abandon () which kills the current session.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page188


In Submit Button write following code:


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page189

Go to default.aspx & run it
Output:-

Example figure:

Ex:-2in default.aspx

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page190

OutPut:-

Note:-<SessionState TimeOut=n> under <system.web>
Tariff.aspx

OutPut:-


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page191

After 1 min refresh

Note:-Before 1 min we will refresh that. It cannot change, but also it will be
taken 1 min again.
Go to web.config
<configuration>
<system.web>
<SessionState timed=10></SessionState>
<compilation debug=true targetFramework=4.0/>
</system.web>
</configuration>

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page192



Ex:-http://ebay.in/ using this in slaved above example.







*** END OF THE DAY ***












Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page193

Dt: 23-06-2010
In Process & Out Process Sessions
1. Session Data & Application data which one is secured?
Ans: - Both are secured.
----------------------------------------------------------------------------------------------------------------------

In process means sessions are crated within the application process. This is
default in ASP.NET & Fastest, because data will be located in single server
only. When heavy load is faced by server then it would affect the execution.

Note:- Sessions are stored within the application it will be called InProcess.
ASP.Net provides 2 out process options. Out Process means storing sessions in
a separate process. Application can be located in other process or in other
system. To maintain sessions in a separate process we can use.
1. ASP.NET State Server Service.
2. SQL Server.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page194


Out Process (in our words):
- Session maintain separately, separate under ASP.NET State Server (or) SQL
Server.
(Q). How to implement Out Process using State Server?
Ans:-Go to services & start ASP.NET State Server. This Service is installed along with
.NET only & no separate installation is required.
- (CP(control Panel) Admin Tools Services)
(Net start <service name> from cmd prompt)
Start Run cmd
C:..>
C:/>net start aspservice
C:/>net stop aspservice

Go to the project where we want to maintain Out Process & add configuration
to implement Out Process sessions.
<sessionState>
Web.Config
<configuration>
<system.web>
<sessionState mode=StateServer>stateNetworkTimeout=120
stateConnectionString= 192.168.100.1:42424>
</sessionState>
Note: - Because system server is bezy then Hoe long will be wait that will be declared
stateNet WorkTimeout(network time out).
<configuration debug=true targetFramework =4.0/>
</system.web>
</Configuration>
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page195


Ex:-
<sessionStatemode:StateServer StateConnectionString=127.0.0.1></SessionState>
Note: - 127.0.0.1 our system act as another system
Note: - LoopBack Adapter IP Address =127.0.0.1

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page196







With SQL Server
In this option the maintain session that is out process session using SQL
Server. The main advantage of going to SQL Server is we can track the data &
also make it persistent.
How to implement?
Install SqlState.Sql is one file which installed again with. Net & provided in
.NET framework folder.
Note:-
<sysyetm.web>
<SessionState mode=SQLServer SqlConnectionString=dataSource.>
SqlCommandTimeout= ></SessionState>
<compilation debug=true targetFramework=4.0/>
</syste.web>
In sessionState change mode & other required things.
StateServer fast
Uninstallsqlstate.sql is another file which will cleanup all tables/procedures
from sqlserver to state.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page197









*** END OF THE DAY ***







Dt: 24-06-2010
Problems with Out Process Environment:-
Serialization / Deserialization In Out Process Session data needs to move
from one place to other place because they are in web-form environment or in
multiple systems.
In .NET 3.5 & below the only solution for this was to reduce complex types and
plan some other logic.
In .NET 4.0 a new compression feature is asses using which we can
compress/decompress data during travelling with this feature we can maximum
use complex type of data & also give good performance.
Web.config
<configuration>
<system.web>
<SessionState mode=SQL Server compressionEnabled =true
sqlCommandString=data Source. sqlCommandTimeout= >
</SessionState>
<compilation dubug=true targetFramework=4.0/>
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page198

</system.web>
</configuration>
Shop.aspx
Using System.IO.Compression;

CookieLess Sessions

Will Session Id Travel yes/No Yes. (Client identified that only).
Will Session Data travel Yes/NO No.(it should not travel).

(Q).How Session id travels?
Ans:- ASP.NET by default creates a Cookie because session id should travel
between every Request/Response.
But with cookies we always have problems & in ASP.NET we have a very good
feature added in Version 2.0 using which we can make session id travel without
cookies.
In web.config
<sessionState Cookieless=true></SessionState>

Anyhow URL based sessions or authentications are not completely safe.
Note:-
SC Session Id
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page199

FC form Authentication
Session ID Cookie can be in memory only it cannot be persistent.
Note:- Scope Application Accessible for all
ASP.NET Cache Object
Cache objects is also similar to application object***(all users means
cache)(or)(cache means all users).
In Todays web and other model of applications performance & power are 2
considerable issues.
Cache Programmed Memory Area.
- Kernel Level Caching
- ASP.NET Level Caching ***
(Q). How caching works & how it gives good performance?
Ans: -Caching always stores the processed result because for further requests it will
avoid processing & directly give result to user. Requesting in good performance but
affecting integrity. It is user job to use caching property & provide performance as well
as integrity****.
ASP.NET supports caching in 3 different ways,
1. Page Output Caching
2. Data Caching
3. Fragment caching (or) Partial page Output Caching
Based application type we have to choose the type of caching.
Note: - EX:- Cricket Score
Most used type of caching is data caching because of its customized use.
Every caching method which ASP.NET supports provides in different way &
user objective is to understand each type & provide Good performance with
integrity.


*** END OF THE DAY ***
Dt: 25-06-2010
1. Page Output Caching:
In this type of caching the entire processed page result is cached. Duration
must be specified for this cached result is cached. Duration must be specified
for this cached result.
(Q). How to Implement?
Ans: - using %@OutputCache......% directive.
This directive has some important attributes Duration=<n >where n is no.of
seconds.
VaryByParam=<param.none>: -
Using this we can specify to vary cache outputs for a single page based on the given
parameter. i.e., for every parameter it will store a separate result.
Other options like VaryByHeader, VaryByCustom etc are also used to cache based to
cache based on these parameters.
Note: -
Velocity is a Service exclusive for .NET
memcached -this people 2rd party people using business caching.
In .NET 4.0 we can customize the caching provider so that we can cache our
data not only in ASP.NET environment but also in separate environment.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page200



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page201



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page202

If we want to cache a single value / multiple values which are purely
programmatic i.e. independent of ui/ page etc then we can go to for data
caching. Data caching is implemented using cache object. This object is
equivalent to application object in scope.***
Application[a]=10;
Cache[b]=10;
Are same in scope.
In.NET it is highly recommended to use cache object instead of application
object when global scope is required.
One simple reason is cache is maintained by system whereas application is
maintained by user.









*** END OF THE DAY ***


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page203

Dt: 28-06-2010
Data Caching:
Implemented using cache object & can store any type of data.
Both application & cache store data with same scope i.e., accessible to all.
Cache is more recommendedbecause it gives more features than application
object & also eliminates the problems of application object.
Both application & code may lead to inconsistency when accessed
simultaneously.
To overcome this application variables & other will be in queue till unlock is
issued.
Advantage: -Consistent.
This results in other problems are,
Locking all variables with Lock. Restricts user to create few variables with
application with application scope.
The time between Lock() & UnLock() should be less & it is dependent on
programmer or developer.

Ex:-
Application.Lock();
..

.

Application.UnLock();
Cache data is self-locking data(Time gaps are reduced)
Cache locks only specific consumed data but not all the data inside it.
Some more features of Cache,
Time Based Expiry
- In this time we create cache data on time. Once time elapses the cache data
will be expired. We can also specify lease-based time or relative mode of
time.
Dependency Based Expiry
- In this mode we can create one object based on other object which can be a
variable, file or even a table in Sql Server (only Sql server).
- Once the dependent object is modified or deleted then cache data will be
expired.
Ex: -
- Create one web form & place GridView with Button.
- Crate one .xml file Say scores.xml
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page204

Open new website (right click) add a new item web Form
(name:scores.xml)

<?xmlversion ="1.0"encoding="ASMO-708"?>
<scoredata>
<score>
<over>1</over>
<runs>4</runs>
</score>
<score>
<over>2</over>
<runs>1</runs>
</score>
<score>
<over>3</over>
<runs>9</runs>
</score>
<score>
<over>4</over>
<runs>12</runs>
</score>
<score>
<over>5</over>
<runs>15</runs>
</score>
<score>
<over>6</over>
<runs>20</runs>
</score>
<score>
<over>7</over>
<runs>9</runs>
</score>
<score>
<over>8</over>
<runs>10</runs>
</score>
</scoredata>
In Button write code to read data from scores.xml & present it in GridView.
C://.(Right click) add a new item web form name:default.apsx

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page205

In default.aspx.cs write following code:
publicpartialclass_Default : System.Web.UI.Page
{
DataSet ds;
protectedvoid Page_Load(object sender, EventArgs e)
{

}
protectedvoid LinkButton1_Click(object sender, EventArgs e)
{
if (Cache["dsscore"] != null) //present
{
ds = (DataSet)Cache["dsscore"];
}
else
{
ds = new DataSet();
ds.ReadXml(MapPath("scores.xml"));
Cache["dsscore"] = ds;
}
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
Out Put:- open default.aspx & run it

Go to saving folder and select scores file (right click open in notepad add one
more over & score and save it).
Ex:-

<?xmlversion ="1.0"encoding="ASMO-708"?>
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page206

<scoredata>
<score>
<over>1</over>
<runs>4</runs>
</score>
<score>
<over>2</over>
<runs>1</runs>
</score>
<score>
<over>3</over>
<runs>9</runs>
</score>
<score>
<over>4</over>
<runs>12</runs>
</score>
<score>
<over>5</over>
<runs>15</runs>
</score>
<score>
<over>6</over>
<runs>20</runs>
</score>
<score>
<over>7</over>
<runs>9</runs>
</score>
<score>
<over>8</over>
<runs>10</runs>
</score>
<score>
<over>9</over>
<runs>25</runs>
</score>
</scoredata>
Open default.aspx run it but output will not be change & open one more
internet explorer paste default.aspx path and run it out put not be changed.
Write following modifications in default.aspx.cs
publicpartialclass_Default : System.Web.UI.Page
{
DataSet ds;
protectedvoid Page_Load(object sender, EventArgs e)
{
}
protectedvoid LinkButton1_Click(object sender, EventArgs e)
{
if (Cache["dsscore"] != null) //present
{
ds = (DataSet)Cache["dsscore"];
}
else
{
ds = new DataSet();
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page207

ds.ReadXml(MapPath("scores.xml"));
// Cache["dsscore"] = ds;
Cache.Insert("dsscore", ds,
newsystem.Web.Caching.CacheDependency(MapPath("scores.xml")));
}
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
Go to asp.net development server & stop that,

Go to default.aspx & run it.

Write following modifications in default.aspx.cs
ds = new DataSet();
ds.ReadXml(MapPath("scores.xml"));
// Cache["dsscore"] = ds;
//Cache.Insert("dsscore", ds, new system.Web.Caching.CacheDependency(MapPath("scores.xml")));
Cache.Insert("dsscore", ds, null, DateTime.Now.AddMinutes(2), TimeSpan.Zero);
//TimeSpan means fixed interval
Note: - Then SCORE will be changed every 2 minutes.


*** END OF THE DAY ***
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page208

Dt: 29-06-2010
Fragment Caching:*****
Fragment Caching means partial page Output caching. In this type of caching
we cache only some part of the page. This implemented with a Concept, but not
using any new commons (or) directives.
(Q). How to implement fragment Caching?
Ans:-
1. Create web user control.*** which is called as user defined control in ASP.NET.
A web user control will be with extension.ascx (active servercontrol)& will be
with <%@ Control%>directive instead of <%@page directive%>.
A control file doesnt contain any page related code like <html>, <head>,
etcbecause it cannot be executed independently & it is placed inside a page. A
control contains markup & code which is only its content.

2. Design the control according to requirement & write code the same. We can
design a control like page only no difference in working.

3. Add<%@ OutputCache..........%> directive to the created control. This step
results in fragment caching when we consume the control in page. If we omit
this step the nit results in a simple user defined control.
4. Go to.aspx page where we want to consume this control. In ASP.NET if we want
to consume a user defined control then we must register it first using <%@
Register %> directive.
We Registera control by providing tagname, tagprefix, filename & sometimes the
assembly (.dll) name also. Once Registered.
<asp:Button
Tagprefix, Tagname

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page209




Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page210




Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page211


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page212




The other way we can create we user control is using ASP.NET server template
in File New Project web.
This control is difficult to design as it has to build from scratch with good
component concepts.
This control can have all user friendly features & can be deployed to client as a
.NET assembly instead of file. All AJAX controls are developed as server controls
using this template only. This control is also called as custom control.***
In normal projects we design a web user control & consume it within our
project.



*** END OF THE DAY ***
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page213

Dt: 30-06-2010

WEB USER CONTROL:
In an application web user controls are useful when Existing controls did not
fulfill our requirement. When a control is create it should be reusable to other
applications & also simplify, manageable to the existing project, let us create
one user control which can be used in multiple forms of our application & also
use them in-side master pages.
1. C://(Right click) add a new item web user control
name:TopMenu.ascx
2. Design the control according to requirement.

3. We want the control to be completely dynamic which means it should
present its data from a different source if a small setting/value then
configuration would be better & if many values then a dataSource like
xml/db and today service oriented only.
In our Example for label i.e., Title, Logo & Banner needs a single value so we
can use configuration supports for it.In web.configuration create
appSettings entries for these controls.
Web.config
<configuration>
<appSettings>
<add key=Title value=E-Learning/>
<add key=Logo value=elearn.jpg/>
<add key=Banner value=ad1.jpg/>
Note:-Content Management system(CMS) software DotNet value, Joomla.
4. We want to display menu type output as part of our control. For this we
create an xml file & all the menu choices will be entered as records here.
C://(RC) add a new item xml file menu.xml
<?xml version=1.0 encoding =utf-8?>
<TopMenu>
<MenuInfo>
<Img>1.jpg</Img>
<Title>Home</Title>
<loc>~/Default.aspx</loc>
</MenuInfo>
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page214


<MenuInfo>
<Img>2.jpg</Img>
<Title>Services</Title>
<loc>~/Default2.aspx</loc>
</MenuInfo>
<MenuInfo>
<Img>3.jpg</Img>
<Title>Gallery</Title>
<loc>~/Default3.aspx</loc>
</MenuInfo>
<MenuInfo>
<Img>4.jpg</Img>
<Title>DownLoad</Title>
<loc>~/Default4.aspx</loc>
</MenuInfo>
<MenuInfo>
<Img>5.jpg</Img>
<Title>ContactUs</Title>
<loc>~/Default5.aspx</loc>
</MenuInfo>
</TopMenu>

5. Now write code the attach sources created to the control.
Page_Load
protected void page_load(object.)
{
if(!IsPostBack) // first request
{
Label1.Text=ConfigurationManager.AppSettings[Title];
Label1.ImageUrl=ConfigurationManager.AppSettings[Logo];
Label2.ImageUrl=ConfigurationManager.AppSettings[Banner];
DataSet ds=new DataSet();
ds.ReadXml(MapPath(menus.xml));
DataList1.DataSource=ds;
DataList2.DataBind();
}
}
6. Because DataList cannot display data automatically we must write markup
for presentation. Go to SourceView & write the markup for displaying data.
<asp:DataList ID=dataList1 runat=server>
//<asp:DataList ID=dataList1 runat=server RepeateColumn=5>
<ItemTemplate>
<table>
<td><asp:HyperLink ID=h1 runat=server
Text=<%#Eval(Title)%>
NavigateUrl=<%#Eval(loc)%>></asp:HyperLink>
</td>
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page215




Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page216


Web.config
<configuration>
<appSettings>
<add key=Title value=E-Learning/>
<add key=Logo value=logo.jpg/>
<add key=Banner value=banner.jpg/>



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page217



Note: - Use chat button also

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page218

*** END OF THE DAY ***
Dt: 02-07-2010

SERVICE ORIENTED APPLICATIONS USING XML WEB SERVICES

Two Types: - web app returns HTML i.e., data + presentation.
Web Services: - web app returns XML just the raw data.



Developing for application for another user:
(Q). what is Oriented?
Ans:-They are all set of rules defined by open standard communities for developing
applications for other application user.
Normal Application End user (Browser).
SOA Application Other Application Users.

Distributed applications is not a new concept where 2 applications interact with
each other presenting in different locations.
But according to SOA distributed programming on web (or) in Heterogeneous
environment means an applications should be available on internet to all types
of users independent of platform, hardware, location etc
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page219


This idea is old but because of many considerations like Bandwidth, Security &
other infrastructure SOA came into market in year 2000.
Successfully implemented thru another open standard specification called XML
Web Services around 2003-2005.
(Q). What is an XML Web Service?
Ans: - This is also defined by W3 org which provides an implementation of service
oriented applications. Any language can follow these rules to result their applications
as service oriented applications.
SOAP Simple Object Access Protocol.
Program my own idea SOAApp WCF
WCF Window communication Foundation.





*** END OF THE DAY ***
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page220

Dt: 03-07-2010
Mobile Applications.

In frontend parts of application one of the most important & also essential is
mobile application.

.NET has any good (little confused) environment for developing mobile
applications.
Form starting version there is always some mobile development in .NET.
Taking all of them we can say mobile applications as of today (july-2010) in
.NET in 2 ways.
1. Server Side Mobile Applications.
2. Client Side Mobile Applications.

Server Side Mobile Applications:

(Q).What are Server Side Mobile Apps?
Ans: -
These are just like Web Applications & they reside @ Server as mobile web
pages.
Normal web pages target a rich browser in all aspects.
Mobile web pages target a down level (lowing features Ex: - JavaScript, HTML,
etc.) Browser where features are limited.
These applications are accessible to all types of mobiles which contain a
browser & which has a means to connect with web.
Note:- A Server side app doesnt expect any resources from client starting from a
lower level user to higher level user So develop server side applications so that
they are accessible by one who can & also today BlackBerry, Apple iphone, Android
(Google), windows Phones are providing full fledged browsers.


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page221

Rich Client Side Development:
.NET from version 2.0 focused lot on client centric mobile applications.
(Q).What are client centric mobile applications in .NET?
Ans: - An application which is developed with separate .NET Framework called
Microsoft .NET Compact Framework (Its a separate Framework).
This compact framework can be installed only on windows powered devices.
Today we have many windows powered devices in the market available in all ranges
with all features. Most importantly windows mobile parts (libraries) can access non
windows applications like Java applications, latest web & SOA (Just like Desktop
applications).














*** END OF THE DAY ***


























Dt: 05-07-2010
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page222

Server Side Mobile Applications:
.NET provides MMIT (Microsoft Mobile Internet Toolkit) that contains various
classes to develop mobile based applications.
VS 2008/2010 doesnt support development of these applications. If we want
we can develop them without help of designer, toolbox, etclike normal source
view working.
VS 2005 has good support for developing these apps & it can be used to develop
.NET server side mobile apps. After developing we can add it to our 2008/2010
project & use it with other parts.
File new project XNA Game studio windows phone Games
Name: WindowsPhoneGame.
We develop this mobile app using Microsoft Visual Studio 2005 software.
To Download & install Microsoft Mobile Explorer 3.0
(Q). How to develop Server Side Mobile Apps using VS 2005?
Ans: -
- Start VS 2005
- New website
- Delete default.aspx which is web page
- Add a new item mobile web form
- Design the form just like any other form & write code in similar way (unified
model).
- Start Microsoft Mobile Explorer & type the address of website
3
rd
party mobile Explorers
- openwave.com
- wap.nokia.com nokia wap toolkit
- blackberry.com
etc

Start File New website ASP.NET web site OK.
File system, C:\\demos\mobiledemo





Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page223

Default.aspx


Note: design page
Build Re-Build
Note:- Mobile Explorer 3.0 software
View Designer simple.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page224


Server Side Example:-
Start File New website ASP.NET web site OK.
C:\\demos\demomobile


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page225



In default.aspx design page open & select command1



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page226




Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page227





Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page228



Double Click on SUBMIT Button & write on following Code:
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page229




Run it & go to build Re Build it
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page230


Note:-Http://www.simpletraining.net






*** END OF THE DAY ***



















Dt: 06-07-2010
.NET Client Side Mobile Applications:
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page231

We mainly target Pocket PCs***, PDAs & Smart Phones *** for this type of
applications. Pocket PCs means a PC kind of device with mobile capabilities,
where ad Smart Phone & PDAs (Personal Data Assistant) contain mobile
features more then PCs functionality (in terms of processor memory & all other
hardware).
Windows mobile is software /SDK/OS provided by Microsoft for developing
applications for windows powered devices.
The latest & the riches mobile version today is windows mobile 7.0
Prior to this the current running windows mobile versions 5.0/6.0/6.5
VS 2008 is the most recommended IDE for these versions but VS 2008 cannot
to used for windows mobile 7.0
VS 2010 also doesnt support win mobile 7.0 version a separate VS 2010
express along with win mobile/game SDK is available for developing windows
mobile 7.0 applications.
How to work with VS 2008? (5.0/6.0/6.5)
By default we get 5.0 with VS 2008 we can also install 6.0/6.5 SDK from
website.
Note: - 6.0/6.5 cannot do in VS 2010
Demo 1: Environmet
Using Visual studio 2008(software)


protected void Linklable1_click(object sender..)
{
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page232

label2.Text=welcome +textBox1.Text;
}
Note:- Tools Device Emulator Manager (Click) window Mobile 5.0
SmartPhone (RC) Connect
USA windows Mode 5.0 smartphone R.2 QVGA Emulater
run form1.cs(Design)


Out put:-





Demo2:Changing Platflom (adv of windows mobile unified libralties)
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page233



Output:-

Demo 3: Real Device
Note: -
XP (System) Active Sync (Software)
Vista/7 windows mobile device center (software)


*** END OF THE DAY ***

Dt: 07-07-2010

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page234





Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page235




Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page236


OutPut:-

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page237


OutPut:-

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page238



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page239



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page240

OutPut:-

Example-2:-




Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page241

OutPut:-














*** END OF THE DAY ***















Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page242

Dt: 08-07-2010





Note: -
XML Web Services 2006
WCF XML WS + Remoting + Lot More
According to XML web services we have to design our application in the given
architecture.
XML, SAOP & WSDL are the key protocols or format for running an XML web
service.
FLOW: -
1. Client makes a request to proxy which should already prepared by client
only in client language (normally).
(Q). What is a Proxy?
Ans: - It is also a class (1-Tier (all layers have connect to or commbaind
one palce only that is 1-Tier)- relation between client & Proxy ) which
should be prepared by client based on the web service. Proxy should
know about webservice otherwise it cannot be created. Proxy coding will
be to own without a tool is very very complex.
Note: - ORB Object Request Broker
(Q). Why is Serialization>
(Q). what is Serialization?

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page243

2. Proxy takes the request & converts the request into SOAP Message.
(Q). what is SOAP?
Ans: -Simple Object Access Protocol
The most initial & starting protocol which was designed by MS, IBM
mainly for communication purpose. The same is used by webservices for
communication. SOAP is derived from XML means it is XML itself (Refer XML &
XML derived techmologies).
Note: -JSON JavaScript Object Notation
AJAX No SOAP Only JSON
One of the draw of SOAP is its Size.
3. Web service takes the SOAP takes the SOAP request & converts it into
native object format. Executes the same request & produces result. This
result is send back to client after converting it as SOAP response format.
4. Proxy takes it & provides it to application & application formats &
displays the results to its client.
....
Microsoft /Oracle/Sun has followed these rules & provided,
MS --- ASP.NET Web Service libraries
Oracle --- PL/SQL Web Service libraries
JAVA --- J2EE Web Services /XML Web Services
As a .NET user we use ASP.NET web service libraries class to develop services.
System.Web.Services is the namespace which ishaving WebService class &
WebMethod class. To build we have to create a class extending WebService
class & writing WEbMethods* inside it.
This is lost supported in .NET 3.5
VS 2008 everywhere we can see ASP.NET Web Service. VS 2010 NET 3.5 &
below only because .NET 4.0 CLR under stands WEF XML Web Service model.
Using VS2010 start new website select .NET 3.5 from versions & choose
ASP.NET Web Service. A sample WebMethod is also written just check it.










*** END OF THE DAY ***



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page244

Dt: 09-07-2010
CREATING AN ASP.NET WEB SERVICE:

Start a new website & select ASP.NET web service (platform 3.5)
In the WebMethod class write methods & convert them to WebMethod. Writing
method is just like any other i.e. function but to make it as WebMethod we
must add an attribute*** called [WebMethod].
--------------------------------------------------------------------------------------------------
VS.NET provides a good environment for testing web services. Simply run the
service test environment is displayed provide inputs & get the results.
Once testing of web services is completed we have to build the application &
provide URL to client.
.
Asmx Active Server Methods.
Normal method using with in the service.
Web method using all services.

App_code/service.cs** (service.asmx)

[WebMethod (Description=a method to get Job Description)]
pubile string GetJobDescription (int jobid) //Best WebMethod
{
SqlConnection cn=new SqlConnection(@Data Source=ROHIT-PC\SQLINDIA;Initial
Catalog=pubs;Integrated..)
cn=Open();
SqlCommand cmd=new SqlCommand(select Job_desc from Jobs where
job_id=+jobid,cn);
SqlDataReader dr=cmd.ExecuteReader();
if(dr.Read())
return dr[0].ToString();
else
return -1;
}
[WebMethod(Description=A method to get job Description)]
public DataSet GetAllJobs() //very poor method not recommended proprietary
object
{
SqlConnection cn=new SqlConnection(@Data Source=ROHIT-PC\SQLINIDA;Initial
Catalog=pubs;.)
DataSet ds=new DataSet();
SqlDataAdapter ds=new SqlDataAdapter(select* from Jobs,cn);
ds.Fill(ds,jobs);
return ds;
}
[WebMethod(BufferREsponse=true,CacheDuration=30,EnableSession=true)]
public Job GetJobInfo(int Jobid)//good method in SOA
{
SqlConnection cn=new SqlConnection(@Data Source=ROHIT-PC\SQLINDIA;Initial
Catalog=pubs;.)
cn.Open();
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page245

SqlCommand cmd=new SqlCommand(select*from jobs where job_id=jobId,cn);
SqlDataReader dr=cmd.ExecuteReader();
Job obj=new Job();
if(dr.Read())
{
obj.JobId=Convert.ToInt32(dr[0]);
obj.Description=dr[1].ToString();
obj.MinLevel=Convert.ToInt32(dr[2]);
obj.MaxLevel=Convert.ToInt32(dr[3]);
}
else
{
obj.JobId=-1;
}
cn.Close();
return obj;
}
In solution Explorer
|
C:\\......
|
App_Code (RightClick) Add a New item (name: Job.asmx)
|
Job.asmx
In App_Code/Job.cs** (Job.cs)
public class Job
{
public Job()(..) //Pro & Tab
public int JobId{get;set;}
public int Description{get;set;}
public int MinLevel{get;set;}
public int MaxLevel{get;set;}
}
Note:- (@ page.Buffer=false..)
Then the output not stop, it will be run fast.
(@ page.Buffer=True..)
Till the method is completed for the form.
EnableSession=true
Using List<Job>Multiple Jobs

*** END OF THE DAY ***





Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page246

Dt: 10-07-2010
CONSUMING WEB SERVICES:
In the previous example we have develop a web service which is one role in real
world related to web services.
Another row for web services is consuming web services which are more critical
than developing web services.
We have to crate proxy here to consume a web service.
To create a proxy what user needs?
Complete information about WebService is required but web service
developers cannot provide the source code & so many other reasons. XML web
services have another protocol or language where users can describe about
their services in xml format & i.e. WSDL (Web Service Description Language).
WebService developer should produce WSDL file & for .NET we need not
separately write any code just add? WSDL @ the end of url result
automatically WSDL will be created/displayed
Note:- http://localhost:2250/SOA3/Service.asmx?wsdl
Example to consume a WebService?
- Start a new website or any other type of project.
- Before we start any form/coding we must create a proxy. .NET provides a
command line tool called WSDL.EXE which takes service or service wsdl file
& creates a proxy in required .NET language. Another method which we
more use is VS.NET adds web Reference option displays a dialog window
where we have to type the url of web service.


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page247



Another type.



Note:- Dont close service.asmx.cs page & open another website


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page248



Proxy is ready and knows we can consume design the form according to the
method that we want to use. On our 1
st
example we will consume GetAllJobs so
we will create button & GridView.
In button write code to use the created proxy & fill the GridView with data.
C://demo/(Right Click) Add a new item Webform default.aspx

Run it
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page249










OutPut:-
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page250



EX-3:



OutPut:-
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page251













*** END OF THE DAY ***





Dt: 12-07-2010

ASP.NET UI Feature:-
- One of the ASP.NET UI Feature is Master page.
Master Pages:-
Consist of two pieces, the master pages it self & one or more content
pages.
Can also nest master pages.
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page252

Is an ASP.NET file with the extension .master (for example,
MySite.master) with a predef. Layout that can include static, text, HTML
elements and server controls.
Is identified by a special @ Master directive that replaces the @ page
directive.
Master Page Architecture:


Example:
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page253



C://demos/mpages3/(RightClick)add a new item Web form
default.aspx
And click to the place code & select master page & click on OK button.


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page254




C://demos/mpages3/(RightClick)add a new item Web form
services.aspx
And click to the place code & select master page & click on OK button.

Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page255



Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page256





Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page257








Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page258




Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page259












*** END OF THE DAY ***












Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page260

Dt: 13-07-2010
ASP.NET DEPLOYMENT

The process of distributing or delivering a developed application is called Deployment.
.NET is RADD (Rapid Application Development & Deployment) using its IDEs separate
installation technologies.
Web Applications development is done using ClickOne (desktop) environment & also
other web related installers.
Microsoft web platform installer in one new software which provides web based
installations for web & other applications. (Visual Studio 2010 more recommended).
Publishing style of deployment is what we do & we publish our app to show many but
some important locations are these 3.
1. Into a Local Drive
2. Directly to a Web Server.
3. To an ftp server***

For all type of deployments only one requirement is set the project debug mode to
false**.
Compile the project correct error & select publish project from build menu or right
click on Solution Explorer & select publish.

Note:-
Znetindia.com
Pucharging Domain only Name 500/-
Purchage space for Domain (Hosting) 500/- to 1 lakh(annum)
Control Panel Details
ftp details
sitename: ftp://simpletraining.net

*** END OF THE CLASS***
Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Hari Page261

nbende@gmail.com (Nagaruju Sir)
http://nbende.wordpress.com
http://www.asp.net
www.w3schools.com
www.codeproject.com
www.nikhilk.net
www.getpivot.com
www.ebay.in
www.xmethods.net
www.znetindia.com
www.tempuri.org










All the Best for all NAGARUJU Sir STUDENTS

Thanks you,

Yours

HARI.D
(Nagaruju Sir Student)
Haribabu708@gmail.com

Anda mungkin juga menyukai