0% found this document useful (0 votes)
757 views

Asp Net

The document provides an introduction to ASP.Net and .Net Framework. It discusses that ASP.Net is a server-side technology that is part of the .Net Framework. The .Net Framework allows development of different types of applications across platforms using common languages and libraries. It also summarizes that web applications developed using ASP.Net with languages like C# provide a unified development model and are universal since they can be accessed over the internet without installation. Finally, it outlines the basic web architecture involving a server OS, web server like IIS, and browsers along with the HTTP protocol.

Uploaded by

niit cts
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
757 views

Asp Net

The document provides an introduction to ASP.Net and .Net Framework. It discusses that ASP.Net is a server-side technology that is part of the .Net Framework. The .Net Framework allows development of different types of applications across platforms using common languages and libraries. It also summarizes that web applications developed using ASP.Net with languages like C# provide a unified development model and are universal since they can be accessed over the internet without installation. Finally, it outlines the basic web architecture involving a server OS, web server like IIS, and browsers along with the HTTP protocol.

Uploaded by

niit cts
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 274

Naga Raju Sri Sai Ram

ASP.Net --

INTRODUCTION

Dt: 29-03-2010

ASP.Net:- Active Server Page for .Net. It’s 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.

Naresh Tech. Class Notes Srikrishna Page1


Naga Raju Sri Sai Ram
ASP.Net --

 ………….(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).
 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 it’s 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

Naresh Tech. Class Notes Srikrishna Page2


Naga Raju Sri Sai Ram
ASP.Net --

 .Net + Language = Application


 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, etc…But 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.

Naresh Tech. Class Notes Srikrishna Page3


Naga Raju Sri Sai Ram
ASP.Net --

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

- All web servers take request only from their client software’s.
- HTTP-Hyper Text Transfer Protocol.
- Protocol is a set of rules, it’snot software.

Naresh Tech. Class Notes Srikrishna Page4


Naga Raju Sri Sai Ram
ASP.Net --

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 ***

Dt:02-04-2010
 Server Model of Operating System.
 Web Server –One or more web sites.
 Browser.
 HTTP

Naresh Tech. Class Notes Srikrishna Page5


Naga Raju Sri Sai Ram
ASP.Net --

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>

Naresh Tech. Class Notes Srikrishna Page6


Naga Raju Sri Sai Ram
ASP.Net --

 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?


 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:
 The .Net framework allows developers to use the same set of skills to rapidly build great
applications fort he web, devices services & more.

Naresh Tech. Class Notes Srikrishna Page7


Naga Raju Sri Sai Ram
ASP.Net --

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.

Naresh Tech. Class Notes Srikrishna Page8


Naga Raju Sri Sai Ram
ASP.Net --

- 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 today’s wanted dynamic web pages.
 Sample HTML program along with its Structure:

Naresh Tech. Class Notes Srikrishna Page9


Naga Raju Sri Sai Ram
ASP.Net --

 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.


<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 ***

Dt: 05-04-2010
Authentication Required: - Message that is getting displayed….

Naresh Tech. Class Notes Srikrishna Page10


Naga Raju Sri Sai Ram
ASP.Net --

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?

Naresh Tech. Class Notes Srikrishna Page11


Naga Raju Sri Sai Ram
ASP.Net --

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

 If we don’t given the new port no. it will be taken default port no. 80
--------------------------------------------------------------------------------------------------
 IIS .NET
 For html/JavaScript (www.w3schools.com)
 For ASP.Net –BOOK—Unleashed ASP.Net --- Stephen Walther(Author)
 Sitehttp://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>
Naresh Tech. Class Notes Srikrishna Page12
Naga Raju Sri Sai Ram
ASP.Net --

Here type means the control that we want.


Name is to refer programmatically.
Value is for appearance.

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

Naresh Tech. Class Notes Srikrishna Page13


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***

Dot: 06-04-2010
 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

Naresh Tech. Class Notes Srikrishna Page14


Naga Raju Sri Sai Ram
ASP.Net --

(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.

(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.

Naresh Tech. Class Notes Srikrishna Page15


Naga Raju Sri Sai Ram
ASP.Net --

- 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>
<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:-
Naresh Tech. Class Notes Srikrishna Page16
Naga Raju Sri Sai Ram
ASP.Net --

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
 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:-

Naresh Tech. Class Notes Srikrishna Page17


Naga Raju Sri Sai Ram
ASP.Net --

 It’s 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.

Naresh Tech. Class Notes Srikrishna Page18


Naga Raju Sri Sai Ram
ASP.Net --

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:-
<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

Naresh Tech. Class Notes Srikrishna Page19


Naga Raju Sri Sai Ram
ASP.Net --

</script>
<h2>Back to HTML</h2>
</body>
</html>
Output:-

Example-3:- <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 ***


Naresh Tech. Class Notes Srikrishna Page20
Naga Raju Sri Sai Ram
ASP.Net --

Dt: 08-04-2010
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,

Naresh Tech. Class Notes Srikrishna Page21


Naga Raju Sri Sai Ram
ASP.Net --

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
<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”>

Naresh Tech. Class Notes Srikrishna Page22


Naga Raju Sri Sai Ram
ASP.Net --

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>
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)

Naresh Tech. Class Notes Srikrishna Page23


Naga Raju Sri Sai Ram
ASP.Net --

 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>
OutPut:-

Naresh Tech. Class Notes Srikrishna Page24


Naga Raju Sri Sai Ram
ASP.Net --

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>

Naresh Tech. Class Notes Srikrishna Page25


Naga Raju Sri Sai Ram
ASP.Net --

</html>
OutPut:-

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

*** END OF THE DAY ***


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;

Naresh Tech. Class Notes Srikrishna Page26


Naga Raju Sri Sai Ram
ASP.Net --

$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.

 The above functions all are objects.Ex: - frame, documents,…..checkbox.


Example:- <html>
<body>
<h1>Java Script DOM</h1>
Naresh Tech. Class Notes Srikrishna Page27
Naga Raju Sri Sai Ram
ASP.Net --

<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
 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:-

Naresh Tech. Class Notes Srikrishna Page28


Naga Raju Sri Sai Ram
ASP.Net --

 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. It’s 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>.

Naresh Tech. Class Notes Srikrishna Page29


Naga Raju Sri Sai Ram
ASP.Net --

 <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
<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; //2ndmethod 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:-

Naresh Tech. Class Notes Srikrishna Page30


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***


Dt: 15-04-2010
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. It’s classed as worker process which manages
the entity ASP.NET page execution & provides results to clients.

Naresh Tech. Class Notes Srikrishna Page31


Naga Raju Sri Sai Ram
ASP.Net --

 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……….?
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.

Naresh Tech. Class Notes Srikrishna Page32


Naga Raju Sri Sai Ram
ASP.Net --

(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

Naresh Tech. Class Notes Srikrishna Page33


Naga Raju Sri Sai Ram
ASP.Net --

 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:
 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,
Naresh Tech. Class Notes Srikrishna Page34
Naga Raju Sri Sai Ram
ASP.Net --

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 software’s 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 software’s from other Benders like Photoshop, Dreamweaver, Corel
Draw, etc...which are good in designing, but doesn’t 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: -
1. Start a new website using File  New website option.
2. Lot of templates in the window Select ASP.NET empty website. This templatedoesn’t
create any file in the project except a Configuration file called web.config
3. We have another template called asp.net website which by default creates some pages
along with Security added to our project.
4. More importantly when we start a new website we have an option to select the target
framework which is a very important entry.
5. Microsoft.com/azure
--- Operating System(O/S) on clouds

Naresh Tech. Class Notes Srikrishna Page35


Naga Raju Sri Sai Ram
ASP.Net --

6. In Visual Studio .Net aspx page is called webform.


7. Add new item  webform (aspx page).
8. 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.
9. 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).

Naresh Tech. Class Notes Srikrishna Page36


Naga Raju Sri Sai Ram
ASP.Net --

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:
 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: -

Naresh Tech. Class Notes Srikrishna Page37


Naga Raju Sri Sai Ram
ASP.Net --

 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
Working with ASP.NET Controls: -
 Normally web application interface is developed using HTML Controls. These Controls are not
highly feature oriented as well as doesn’t 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.

Naresh Tech. Class Notes Srikrishna Page38


Naga Raju Sri Sai Ram
ASP.Net --

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

Naresh Tech. Class Notes Srikrishna Page39


Naga Raju Sri Sai Ram
ASP.Net --

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 go’s 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

Naresh Tech. Class Notes Srikrishna Page40


Naga Raju Sri Sai Ram
ASP.Net --

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 ***

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)

Naresh Tech. Class Notes Srikrishna Page41


Naga Raju Sri Sai Ram
ASP.Net --

 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”;
}
// 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.

Naresh Tech. Class Notes Srikrishna Page42


Naga Raju Sri Sai Ram
ASP.Net --

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 ***


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.


Naresh Tech. Class Notes Srikrishna Page43
Naga Raju Sri Sai Ram
ASP.Net --

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”;
}
}

Output: -

Naresh Tech. Class Notes Srikrishna Page44


Naga Raju Sri Sai Ram
ASP.Net --

 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.

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

Naresh Tech. Class Notes Srikrishna Page45


Naga Raju Sri Sai Ram
ASP.Net --

Image Map Control:

In that rectangleHotSpot we fill the following steps:

Naresh Tech. Class Notes Srikrishna Page46


Naga Raju Sri Sai Ram
ASP.Net --

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:


*** END OF THE DAY ***
Dt: 21-04-2010

Naresh Tech. Class Notes Srikrishna Page47


Naga Raju Sri Sai Ram
ASP.Net --

<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

Naresh Tech. Class Notes Srikrishna Page48


Naga Raju Sri Sai Ram
ASP.Net --

 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)
{
if(ListBox1.SelectedValue==”10”)
{

Naresh Tech. Class Notes Srikrishna Page49


Naga Raju Sri Sai Ram
ASP.Net --

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;
}

Naresh Tech. Class Notes Srikrishna Page50


Naga Raju Sri Sai Ram
ASP.Net --

Add one more webform  default7.aspx


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”;

Naresh Tech. Class Notes Srikrishna Page51


Naga Raju Sri Sai Ram
ASP.Net --

}
else
Label1.Text=CheckBox1.SelectedValue;
}

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.

Naresh Tech. Class Notes Srikrishna Page52


Naga Raju Sri Sai Ram
ASP.Net --

(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. It’s 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;

Naresh Tech. Class Notes Srikrishna Page53


Naga Raju Sri Sai Ram
ASP.Net --

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)
{
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;
}

Naresh Tech. Class Notes Srikrishna Page54


Naga Raju Sri Sai Ram
ASP.Net --

OutPut:-

EX-2:-

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();

Naresh Tech. Class Notes Srikrishna Page55


Naga Raju Sri Sai Ram
ASP.Net --

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
 Go to ToolBox Navigation  Menu(Drag & Drop)- edit Menu Item
 We add items click (+) button added item billow process.

Naresh Tech. Class Notes Srikrishna Page56


Naga Raju Sri Sai Ram
ASP.Net --

 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)propertiesOrientation


Vertixal(default)
(or)
Horizantal.

*** END OF THE DAY ***

Dt:26-04-2010
Navigating Multiple forms:

Naresh Tech. Class Notes Srikrishna Page57


Naga Raju Sri Sai Ram
ASP.Net --

 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 doesn’t 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: -

Naresh Tech. Class Notes Srikrishna Page58


Naga Raju Sri Sai Ram
ASP.Net --

protected void Button1_Click(object sender, EventArgs e)


{
// 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:-

Naresh Tech. Class Notes Srikrishna Page59


Naga Raju Sri Sai Ram
ASP.Net --

 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)

Naresh Tech. Class Notes Srikrishna Page60


Naga Raju Sri Sai Ram
ASP.Net --

---------------------------------------------------------------------------------------------
 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

Naresh Tech. Class Notes Srikrishna Page61


Naga Raju Sri Sai Ram
ASP.Net --

 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 ***
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 doesn’t 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

Naresh Tech. Class Notes Srikrishna Page62


Naga Raju Sri Sai Ram
ASP.Net --

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:

 Then go to default7.aspx design page Run it.

3. Using CrossPage*PostBack concept

Naresh Tech. Class Notes Srikrishna Page63


Naga Raju Sri Sai Ram
ASP.Net --

 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.
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)

Naresh Tech. Class Notes Srikrishna Page64


Naga Raju Sri Sai Ram
ASP.Net --

 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;
}
 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)
{

Naresh Tech. Class Notes Srikrishna Page65


Naga Raju Sri Sai Ram
ASP.Net --

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 ***

Dt: 28-04-2010

ASP.NET Validation Controls:

Naresh Tech. Class Notes Srikrishna Page66


Naga Raju Sri Sai Ram
ASP.Net --

 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.

Naresh Tech. Class Notes Srikrishna Page67


Naga Raju Sri Sai Ram
ASP.Net --

In order Button Double click write following code:


protected void Button1_Click(object sender, EventAgrs e)
{
Response.Redirect(“Thanks.aspx”);
}

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

Naresh Tech. Class Notes Srikrishna Page68


Naga Raju Sri Sai Ram
ASP.Net --

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)

 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 don’t generate any JavaScript code & doesn’t perform validation in client. Only
after submitting the form validation is performed @ server side.

Naresh Tech. Class Notes Srikrishna Page69


Naga Raju Sri Sai Ram
ASP.Net --

 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.
Don’t use it for string type of data.
- MinimumValue
- MaximumValue
- Type:Integer/Date/….

*** END OF THE DAY ***

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.

Naresh Tech. Class Notes Srikrishna Page70


Naga Raju Sri Sai Ram
ASP.Net --

 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:
 Used to perform validations which are comparison based 3 types compression can be done.
a) Control with another control
ControlToValidate
ControlToCompare

Naresh Tech. Class Notes Srikrishna Page71


Naga Raju Sri Sai Ram
ASP.Net --

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”

Naresh Tech. Class Notes Srikrishna Page72


Naga Raju Sri Sai Ram
ASP.Net --

Type =”integer”/>
c) Control-Data Types:

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

*** 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.

Naresh Tech. Class Notes Srikrishna Page73


Naga Raju Sri Sai Ram
ASP.Net --

.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)

Add one more textBox8 & RegularExpressionValidator

Naresh Tech. Class Notes Srikrishna Page74


Naga Raju Sri Sai Ram
ASP.Net --

6. CustomValidator:
 Which developing application, if all above four validation controls doesn’t 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.

CustomValidatorClient side:
 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.

Naresh Tech. Class Notes Srikrishna Page75


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***

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.

Naresh Tech. Class Notes Srikrishna Page76


Naga Raju Sri Sai Ram
ASP.Net --

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs


Args)
{
if(int.Parse(args.Value)%5==0)
args.IsValid=true;
else
args.IsValid=false;
}

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

Naresh Tech. Class Notes Srikrishna Page77


Naga Raju Sri Sai Ram
ASP.Net --

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**
- 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.

Naresh Tech. Class Notes Srikrishna Page78


Naga Raju Sri Sai Ram
ASP.Net --

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,

Naresh Tech. Class Notes Srikrishna Page79


Naga Raju Sri Sai Ram
ASP.Net --

%@page ClientTarget=”DownLevel” Language=”C#”...........


- This setting is applicable for entire webpage validation controls.

*** 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 2nd 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:

Naresh Tech. Class Notes Srikrishna Page80


Naga Raju Sri Sai Ram
ASP.Net --

 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 1st RequiredFieldValidator goto Preperties write,
ErrorMessage <img src=loading.gif>Required (ENTER)
IN SOURCE PAGE: (BackGround Sound):
--------------------------------------
-------------------------------------
(<asp:RequiredFieldValidator>)(before)
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.

Naresh Tech. Class Notes Srikrishna Page81


Naga Raju Sri Sai Ram
ASP.Net --

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 ***


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.

Naresh Tech. Class Notes Srikrishna Page82


Naga Raju Sri Sai Ram
ASP.Net --

 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.

Naresh Tech. Class Notes Srikrishna Page83


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***


Dt: 06-05-2010
Creating our own Databases & providing DataBinding Results:
 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…

Naresh Tech. Class Notes Srikrishna Page84


Naga Raju Sri Sai Ram
ASP.Net --

i. SqlDataSource
ii. LinqDataSource
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).

Naresh Tech. Class Notes Srikrishna Page85


Naga Raju Sri Sai Ram
ASP.Net --

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.

 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.

Naresh Tech. Class Notes Srikrishna Page86


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***


Dt: 08-05-2010
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
otherworld’s 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.

Naresh Tech. Class Notes Srikrishna Page87


Naga Raju Sri Sai Ram
ASP.Net --

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.
 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 ***


Dt: 10-05-2010
Programmatically preparing objects:-
 To prepare our own objects especially database oriented content we have to ADO.NET concept
of .NET.

Naresh Tech. Class Notes Srikrishna Page88


Naga Raju Sri Sai Ram
ASP.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 ItemDataHelper.
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.

Naresh Tech. Class Notes Srikrishna Page89


Naga Raju Sri Sai Ram
ASP.Net --

 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;
}
}

Naresh Tech. Class Notes Srikrishna Page90


Naga Raju Sri Sai Ram
ASP.Net --

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.

 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(………)
{

Naresh Tech. Class Notes Srikrishna Page91


Naga Raju Sri Sai Ram
ASP.Net --

}
protected void Button1_click(object………….)
{
BLJobs obj=new BLJobs();
GridView1.DataSource=obj.GetJobs();
GridView1.DataBind();
}
*** END OF THE DAY ***

Linq to Sql & EDM


Dt: 11-05-2010
 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.

Naresh Tech. Class Notes Srikrishna Page92


Naga Raju Sri Sai Ram
ASP.Net --

 Framework Create objects, that connect to Backend DB.


OOPS  Response Objects.
SQL  Response SQL Objects.
Linq  only Linq
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.

Naresh Tech. Class Notes Srikrishna Page93


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page94


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***


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

Naresh Tech. Class Notes Srikrishna Page95


Naga Raju Sri Sai Ram
ASP.Net --

 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>();
}

 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).

Naresh Tech. Class Notes Srikrishna Page96


Naga Raju Sri Sai Ram
ASP.Net --

 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.
(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
----------------------------------------------------------------------------------------------------------------------

Naresh Tech. Class Notes Srikrishna Page97


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***


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).

Naresh Tech. Class Notes Srikrishna Page98


Naga Raju Sri Sai Ram
ASP.Net --

 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.
(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:-

Naresh Tech. Class Notes Srikrishna Page99


Naga Raju Sri Sai Ram
ASP.Net --

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.

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:

Naresh Tech. Class Notes Srikrishna Page100


Naga Raju Sri Sai Ram
ASP.Net --

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

Naresh Tech. Class Notes Srikrishna Page101


Naga Raju Sri Sai Ram
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”)%>

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()%>

Naresh Tech. Class Notes Srikrishna Page102


Naga Raju Sri Sai Ram
ASP.Net --

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.

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>

Naresh Tech. Class Notes Srikrishna Page103


Naga Raju Sri Sai Ram
ASP.Net --

//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>

Naresh Tech. Class Notes Srikrishna Page104


Naga Raju Sri Sai Ram
ASP.Net --

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 ***

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?

Naresh Tech. Class Notes Srikrishna Page105


Naga Raju Sri Sai Ram
ASP.Net --

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).

Naresh Tech. Class Notes Srikrishna Page106


Naga Raju Sri Sai Ram
ASP.Net --

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

Naresh Tech. Class Notes Srikrishna Page107


Naga Raju Sri Sai Ram
ASP.Net --

ShowEditButton=”true”
ShowCancelButton=”true”
ShowDeleteButton=”true”/>

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.

protected void GridView1_RowEditing(object sender………….)


{
//e.NewEditIndex  selected row index provided by GridView only.
GridView1.EditIndex=e.NewEditIndex;

Naresh Tech. Class Notes Srikrishna Page108


Naga Raju Sri Sai Ram
ASP.Net --

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
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.

Naresh Tech. Class Notes Srikrishna Page109


Naga Raju Sri Sai Ram
ASP.Net --

GridView1.Rows[0].Cells
- First rows all Cells
GridView1.Rows[0].Cells[0]
- First rows first Cell
GridView1.Rows[0].Cells[0].Text
- 1st Row 1st Cell text provided that Cell Contains simple text.
GridView1.Rows[0].Cells[0].Controls
- 1st row 1st Cell Controls.
GridView1.Rows[0].Cells[0].Controls[0]
- 1st Row 1st Cell 1st Control

Ex:-
1 GridView1.Rows[1].Cells[1].Text
3GridView1.Rows[2].Cells[0].Control
 This type of retrieval is used when BoundField implicitly creates a control because we don’t
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”);

Naresh Tech. Class Notes Srikrishna Page110


Naga Raju Sri Sai Ram
ASP.Net --

protected void GridView1_RowUpdating(object sender,………..)


{
string mjobid=GridView1.Rows[e.RowIndex].Cells[0].Text;

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)
{

Naresh Tech. Class Notes Srikrishna Page111


Naga Raju Sri Sai Ram
ASP.Net --

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.
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
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…

Naresh Tech. Class Notes Srikrishna Page112


Naga Raju Sri Sai Ram
ASP.Net --

 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>
------------------------------------------------------------------------------------------------------
Naresh Tech. Class Notes Srikrishna Page113
Naga Raju Sri Sai Ram
ASP.Net --

Go to Code page window:


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)

Naresh Tech. Class Notes Srikrishna Page114


Naga Raju Sri Sai Ram
ASP.Net --

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>
</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

Naresh Tech. Class Notes Srikrishna Page115


Naga Raju Sri Sai Ram
ASP.Net --

}
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

Naresh Tech. Class Notes Srikrishna Page116


Naga Raju Sri Sai Ram
ASP.Net --

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);
}
}
Naresh Tech. Class Notes Srikrishna Page117
Naga Raju Sri Sai Ram
ASP.Net --

public string GetTotal()  3


{
return”Total:”+1.ToString();
}

*** END OF THE DAY ***


Dt: 20-05-2010

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.

Naresh Tech. Class Notes Srikrishna Page118


Naga Raju Sri Sai Ram
ASP.Net --

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 field’s 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”)%>
</ItemTemplate>
Naresh Tech. Class Notes Srikrishna Page119
Naga Raju Sri Sai Ram
ASP.Net --

<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>
Naresh Tech. Class Notes Srikrishna Page120
Naga Raju Sri Sai Ram
ASP.Net --

<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
- 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 ***


Dt: 21-05-2010
XML is for limited Storage and No Security
XML File  Storing Data

Naresh Tech. Class Notes Srikrishna Page121


Naga Raju Sri Sai Ram
ASP.Net --

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:-
o DataList Unique Feature.
o Images Presentation.
o 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 BLOB’S (Binary Large Objects) today what is Max size for BLOB?

Naresh Tech. Class Notes Srikrishna Page122


Naga Raju Sri Sai Ram
ASP.Net --

 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”).
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>

Naresh Tech. Class Notes Srikrishna Page123


Naga Raju Sri Sai Ram
ASP.Net --

<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, etc…are 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 ***
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

Naresh Tech. Class Notes Srikrishna Page124


Naga Raju Sri Sai Ram
ASP.Net --

 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:
o protected void DataList1_ItemCommand(object…………….)

Naresh Tech. Class Notes Srikrishna Page125


Naga Raju Sri Sai Ram
ASP.Net --

{
if(e.CommandNmae==”m1”)
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);

Naresh Tech. Class Notes Srikrishna Page126


Naga Raju Sri Sai Ram
ASP.Net --

}
}
}
 In our demo replace
<%#Eval(“price”)%> with <asp:Label ID=”lp1” runat=”server”
Text=’<%Eval(price)%>’/>
// (understand why this change)

*** END OF THE DAY ***


Dt: 25-05-2010

FormView & DetailsView:-


 GridView, Repeater & DataList doesn’t 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

Naresh Tech. Class Notes Srikrishna Page127


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page128


Naga Raju Sri Sai Ram
ASP.Net --

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.

Ex:- GeidView Design:

Ex:-DetalisView:-

Naresh Tech. Class Notes Srikrishna Page129


Naga Raju Sri Sai Ram
ASP.Net --

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

Naresh Tech. Class Notes Srikrishna Page130


Naga Raju Sri Sai Ram
ASP.Net --

Drag & Drop 2 GridView Controls in the default3.aspx

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

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

Naresh Tech. Class Notes Srikrishna Page131


Naga Raju Sri Sai Ram
ASP.Net --

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 ***


Dt: 26-05-2010

ListView Control
ListView Control:- (Its new control from 4.0)

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

ListView Structure (Little New):


<asp:ListView DataSourceID=”MyDS” runat=”Server”>

Naresh Tech. Class Notes Srikrishna Page132


Naga Raju Sri Sai Ram
ASP.Net --

<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.

Naresh Tech. Class Notes Srikrishna Page133


Naga Raju Sri Sai Ram
ASP.Net --

Note: - we select one by one then the preview Box see the coding of that particular task.

Naresh Tech. Class Notes Srikrishna Page134


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***

ASP.NET Configuration

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.

Naresh Tech. Class Notes Srikrishna Page135


Naga Raju Sri Sai Ram
ASP.Net --

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
 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.
Naresh Tech. Class Notes Srikrishna Page136
Naga Raju Sri Sai Ram
ASP.Net --

 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.config’s on our site
maximum is how many folders we have in our project.

*** END OF THE DAY ***


Dt: 28-05-2010
Configuration Structure:-

Naresh Tech. Class Notes Srikrishna Page137


Naga Raju Sri Sai Ram
ASP.Net --

<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 don’t 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:-

Naresh Tech. Class Notes Srikrishna Page138


Naga Raju Sri Sai Ram
ASP.Net --

 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 ***
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

Naresh Tech. Class Notes Srikrishna Page139


Naga Raju Sri Sai Ram
ASP.Net --

 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
o 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.
 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.

Naresh Tech. Class Notes Srikrishna Page140


Naga Raju Sri Sai Ram
ASP.Net --


NOTE:- NagaRaju Sir working this sites.

 www.Burton.com
 www.GetPivot.com

*** END OF THE CLASS****

****AJAX ***

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);

Naresh Tech. Class Notes Srikrishna Page141


Naga Raju Sri Sai Ram
ASP.Net --

cn.open();
Label1.Text=”Connnected”
}
(Q). what is the difference b/w defining cnstr in appSettings and in ConnectionStrings?
****iii).<Compilation>
o 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…
o All these options simplified users debugging but at a cost of additional code/ symbols. ***
o 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.
o 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.
*** END OF THE DAY ***
Dt: 01-06-2010
<system.web>
<system.net>
<mailsettings>
-----------------------
SMTP  Specification
(Simple Mail Transport Protected) an open standard protected.

Naresh Tech. Class Notes Srikrishna Page142


Naga Raju Sri Sai Ram
ASP.Net --

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 software’s 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))
o Mail Message
To prepare complete mail content.
o SMTPClient**
To communicate as client to SMTP server.
To send message prepared to SMTP server.
Example:-

using System.Net;
using System.Net.Mail;
public partial class_Default:system.Web.UI.page

Naresh Tech. Class Notes Srikrishna Page143


Naga Raju Sri Sai Ram
ASP.Net --

{
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”;
}
}
*** END OF THE DAY ***
Dt: 02-06-2010
Web.config:
<system.net>
<mailSettings>
<smtp from=”[email protected]”>
<network host=”smtp.gmail.com”password=”secret” port=”587” username=”nbende”/>
</smtp>
</mailSettings>

Naresh Tech. Class Notes Srikrishna Page144


Naga Raju Sri Sai Ram
ASP.Net --

</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 reached…first Breakup”);
Trace.Warn(“Take beckup DB is full”); (OR)
3). if(Trace.IsEnabled)
{
for(int i=0;i<10;i++)
{
Trace.Write(i.ToString());

Naresh Tech. Class Notes Srikrishna Page145


Naga Raju Sri Sai Ram
ASP.Net --

}}}
………………………………………………………………………………………………………………
Go to Web.Config
================
<Configuration>
<appSettings>
<addKey=”Title” value=”E.Learning Application123”/>
<appSettings>
<system.Web>
i). <trace enabled=”true”pageOutput=”false”/>
ii). <trace enabled=”true”pageOutput=”false” requestLimit=”5”/>
iii). <trace enabled=”true”pageOutput=”true” WriteToDignosticsTrace=”true”/>
<compilation debug=”true” targetFramework=”4.0”/>
</system.Web>
Other important attributes are:
 pageOutput=”true/false”
o default is false & when set to true appends trace results to the page output.
o If false the meaning is trace is generated but should be viewed with trace utility not in the
same page.
o ***Trace utility means in the url remove.aspx page name & type “trace.axd”
 requestLimit=<n>
default is 10
o which means 10 times trace output will be generated after other that no trace is generated.
 localOnly=true/false
o true menas only in localhost system tracing will be generated for other users only output
will be given.
 System.Diagnostics*****(refer)
writeToDiagnosticsTrace=”true”
o Will redirect all trace result to the mentioned diagnostics file for later viewing.
o All above trace settings are called Application Level tracing & we have page level, statement
level also.

Naresh Tech. Class Notes Srikrishna Page146


Naga Raju Sri Sai Ram
ASP.Net --

o As part of page directive we can use trace=false attribute to ignore tracing for the current
page this is called page level tracing.
o 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.
…………………………………………………………………………………………………………….

*** 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:
o Data Security
o Hackers Security
o Public / private content
o 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)

Naresh Tech. Class Notes Srikrishna Page147


Naga Raju Sri Sai Ram
ASP.Net --

(.NET)
At ASP.NET / Project level we need to implement security with the provided support (Good for
developer).
……………………………………………………………………………………………………………..
1. Authentication:
o 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:
o 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/S’s , DataBase servers & in ASP.NET


 Security  Authentication + Authorization.
(User name+pwd) (whether content will be follows)
 In ASP.NET ----Authentication can be implemented in 3 ways.
i) Windows Authentication***(OR)
ii) Forms Authentication****(OR)
iii) Password Authentication.

i. Windows Authentication:

Naresh Tech. Class Notes Srikrishna Page148


Naga Raju Sri Sai Ram
ASP.Net --

FLOW:Client makes a request secured page


|
o IIS takes the request & check for identify. If identify is not found stops the user & redirects a
login window.
|
o Client enters the credentials that are required for server & submits back to IIS.
|
o 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:
o 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.
o This is compulsory when we want to implement any other authentication than windows.
o At IIS Level we will have scope to implement Kerberos, MD5(Message Digest) & SHA (Secure
Hash Algorithm)……..Windows authentication.
(Q).ASP.NET doesn’t support the following security Concept?
a. Windows Authentication
b. Basic Digest
c. …………
d. None
Ans:- None

Naresh Tech. Class Notes Srikrishna Page149


Naga Raju Sri Sai Ram
ASP.Net --

Because ASP.NET support above 1st 3 options.

*** END OF THE DAY ***


Dt: 04-06-2010

ii. Passport Authentication:


o This is a 3rd 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:
o Client makes a Request for secured webpage.
|
o IIS allows user as anonymous which is compulsory to implement any non- window
authentication.
|
o User enters in to ASP.NET & ASP.NET redirects user to passport website. Because
Authentication ticket is not found.
|
o Passport displays login page to user.
|
o 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.

Naresh Tech. Class Notes Srikrishna Page150


Naga Raju Sri Sai Ram
ASP.Net --

Note: -
Once passport identity is created then access may be granted to other websites also which is
passport identity.

iii. Forms Authentication:*****


o This authentication is performed by ASP.NET itself along with user instructions (developer)
o 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.

Naresh Tech. Class Notes Srikrishna Page151


Naga Raju Sri Sai Ram
ASP.Net --

(Q).How forms Autehntication works? ***


Ans:-
o client makes a request for secured page
|
o IIS allows user as anonymous which is compulsory
|
o 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].
|
o User enters or fulfills the login requirements & submits back to server.
|
o IIS again allows user as anonymous & ASP.NET execute the login page code-after successful
evaluation it redirects secured page to user.
o In this step evaluation / executing code is not which is written by system but it is something
which is written by developer.
o 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.
o In project intranet type of apps ----windows.
o Internet ---Forms.
*** END OF THE DAY ***

Naresh Tech. Class Notes Srikrishna Page152


Naga Raju Sri Sai Ram
ASP.Net --

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 user’s 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>

Naresh Tech. Class Notes Srikrishna Page153


Naga Raju Sri Sai Ram
ASP.Net --

<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=”*”/>
<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.

Naresh Tech. Class Notes Srikrishna Page154


Naga Raju Sri Sai Ram
ASP.Net --

 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

*** 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 2nd 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.

Naresh Tech. Class Notes Srikrishna Page155


Naga Raju Sri Sai Ram
ASP.Net --

 [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
user’s tables are also present).

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

Naresh Tech. Class Notes Srikrishna Page156


Naga Raju Sri Sai Ram
ASP.Net --

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)
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 textbox’x.
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;

Naresh Tech. Class Notes Srikrishna Page157


Naga Raju Sri Sai Ram
ASP.Net --

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

*** END OF THE DAY ***

Dt: 08-06-2010
 FormsAuthentication.RedirectFromLoginPage(TextBox1.Text,CheckBox1.Checked);
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.
Naresh Tech. Class Notes Srikrishna Page158
Naga Raju Sri Sai Ram
ASP.Net --

1. Identity name
o 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 deny’s 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.

 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 optionssettings  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.

Naresh Tech. Class Notes Srikrishna Page159


Naga Raju Sri Sai Ram
ASP.Net --

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>

Naresh Tech. Class Notes Srikrishna Page160


Naga Raju Sri Sai Ram
ASP.Net --

 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.

 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;
}}

Naresh Tech. Class Notes Srikrishna Page161


Naga Raju Sri Sai Ram
ASP.Net --

 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;
}
}

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

Naresh Tech. Class Notes Srikrishna Page162


Naga Raju Sri Sai Ram
ASP.Net --

Out Put:-

Naresh Tech. Class Notes Srikrishna Page163


Naga Raju Sri Sai Ram
ASP.Net --

Next

In default.aspx.cs
protected void……..
{
if(User.Identity.IsAuthenticated)
}
Login controls:-
 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.

Naresh Tech. Class Notes Srikrishna Page164


Naga Raju Sri Sai Ram
ASP.Net --

 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

Naresh Tech. Class Notes Srikrishna Page165


Naga Raju Sri Sai Ram
ASP.Net --

 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:-

Naresh Tech. Class Notes Srikrishna Page166


Naga Raju Sri Sai Ram
ASP.Net --

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

OutPut:-

Naresh Tech. Class Notes Srikrishna Page167


Naga Raju Sri Sai Ram
ASP.Net --

 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 ***
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 levelmedium 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.

Naresh Tech. Class Notes Srikrishna Page168


Naga Raju Sri Sai Ram
ASP.Net --

<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.

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

Naresh Tech. Class Notes Srikrishna Page169


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***

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

Naresh Tech. Class Notes Srikrishna Page170


Naga Raju Sri Sai Ram
ASP.Net --

 requireSSL=true/false
o 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”>
o 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
Naresh Tech. Class Notes Srikrishna Page171
Naga Raju Sri Sai Ram
ASP.Net --

<forms requireSSL=”true” protection=””>//(….it will be taken default all)


o 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.
o 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,
o DB creation
o Procedures writing
o Data Layer /Business Layers
o User interface with changes
o Etc…
 Empty website as its name says doesn’t 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”.

Naresh Tech. Class Notes Srikrishna Page172


Naga Raju Sri Sai Ram
ASP.Net --

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 ***

Naresh Tech. Class Notes Srikrishna Page173


Naga Raju Sri Sai Ram
ASP.Net --

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,
o 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.

Naresh Tech. Class Notes Srikrishna Page174


Naga Raju Sri Sai Ram
ASP.Net --

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

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****
 Cookies—HTTP Concept****
 Sessions/Profiles***

Naresh Tech. Class Notes Srikrishna Page175


Naga Raju Sri Sai Ram
ASP.Net --

 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.
o Server.Transfer(<page>, true).

*** 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.

 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.

Naresh Tech. Class Notes Srikrishna Page176


Naga Raju Sri Sai Ram
ASP.Net --

 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 doesn’t 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***.

Naresh Tech. Class Notes Srikrishna Page177


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page178


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***

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)
{
}

Naresh Tech. Class Notes Srikrishna Page179


Naga Raju Sri Sai Ram
ASP.Net --

Output:-

 Drag and Drop TextBox in design page

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

}

Naresh Tech. Class Notes Srikrishna Page180


Naga Raju Sri Sai Ram
ASP.Net --

 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#”%>

Design-

Naresh Tech. Class Notes Srikrishna Page181


Naga Raju Sri Sai Ram
ASP.Net --

 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).
 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 PC’s called web forming.

Naresh Tech. Class Notes Srikrishna Page182


Naga Raju Sri Sai Ram
ASP.Net --

 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 doesn’t 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

MULTIPLE PAGES STATE

Naresh Tech. Class Notes Srikrishna Page183


Naga Raju Sri Sai Ram
ASP.Net --

 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.

Naresh Tech. Class Notes Srikrishna Page184


Naga Raju Sri Sai Ram
ASP.Net --

 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***.

Naresh Tech. Class Notes Srikrishna Page185


Naga Raju Sri Sai Ram
ASP.Net --

 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.

Naresh Tech. Class Notes Srikrishna Page186


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***

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

Naresh Tech. Class Notes Srikrishna Page187


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page188


Naga Raju Sri Sai Ram
ASP.Net --

OutPut:-

Naresh Tech. Class Notes Srikrishna Page189


Naga Raju Sri Sai Ram
ASP.Net --

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.
(Q). can’t 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;

Naresh Tech. Class Notes Srikrishna Page190


Naga Raju Sri Sai Ram
ASP.Net --

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”]=”[email protected]”;
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.

Naresh Tech. Class Notes Srikrishna Page191


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***

Dt: 19-06-2010

SERVER SIDE STATE MANAGEMENT:


Application object of ASP.NET
Session object of ASP.NET[profiles(it’s 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.

Naresh Tech. Class Notes Srikrishna Page192


Naga Raju Sri Sai Ram
ASP.Net --

.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.

Naresh Tech. Class Notes Srikrishna Page193


Naga Raju Sri Sai Ram
ASP.Net --

Here O/S doesn’t know there is one app is there. But is maintain by CLR.
Here one App didn’t 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.

Naresh Tech. Class Notes Srikrishna Page194


Naga Raju Sri Sai Ram
ASP.Net --

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.

Application object of ASP.NET allows a user/developer to refer this created process.

Naresh Tech. Class Notes Srikrishna Page195


Naga Raju Sri Sai Ram
ASP.Net --

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.

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: -

Naresh Tech. Class Notes Srikrishna Page196


Naga Raju Sri Sai Ram
ASP.Net --

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.

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).

Naresh Tech. Class Notes Srikrishna Page197


Naga Raju Sri Sai Ram
ASP.Net --

(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.

Naresh Tech. Class Notes Srikrishna Page198


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page199


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***


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 min’s it the timeout (idle timeout) using configuration settings as well as
programmatically with session object we can change this default time.

Naresh Tech. Class Notes Srikrishna Page200


Naga Raju Sri Sai Ram
ASP.Net --

A session can be ended programmatically also. Session object has a method called Abandon ()
which kills the current session.

In Submit Button write following code:

Go to default.aspx & run it


Output:-

Naresh Tech. Class Notes Srikrishna Page201


Naga Raju Sri Sai Ram
ASP.Net --

Example figure:

Ex:-2in default.aspx

OutPut:-

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

Naresh Tech. Class Notes Srikrishna Page202


Naga Raju Sri Sai Ram
ASP.Net --

Tariff.aspx

OutPut:-

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>
Naresh Tech. Class Notes Srikrishna Page203
Naga Raju Sri Sai Ram
ASP.Net --

</configuration>

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

*** END OF THE DAY ***

Dt: 23-06-2010

Naresh Tech. Class Notes Srikrishna Page204


Naga Raju Sri Sai Ram
ASP.Net --

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.

Naresh Tech. Class Notes Srikrishna Page205


Naga Raju Sri Sai Ram
ASP.Net --

 Out Process (in our words):


o 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.
o (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”/>

Naresh Tech. Class Notes Srikrishna Page206


Naga Raju Sri Sai Ram
ASP.Net --

</system.web>
</Configuration>

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”

Naresh Tech. Class Notes Srikrishna Page207


Naga Raju Sri Sai Ram
ASP.Net --

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.

*** END OF THE DAY ***

Dt: 24-06-2010

Problems with Out Process Environment:-

Naresh Tech. Class Notes Srikrishna Page208


Naga Raju Sri Sai Ram
ASP.Net --

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”/>
</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.

Naresh Tech. Class Notes Srikrishna Page209


Naga Raju Sri Sai Ram
ASP.Net --

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
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 Today’s web and other model of applications performance & power are 2 considerable issues.
Cache  Programmed Memory Area.
o Kernel Level Caching
o 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

Naresh Tech. Class Notes Srikrishna Page210


Naga Raju Sri Sai Ram
ASP.Net --

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.

Naresh Tech. Class Notes Srikrishna Page211


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page212


Naga Raju Sri Sai Ram
ASP.Net --

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.

Naresh Tech. Class Notes Srikrishna Page213


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***


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.

Naresh Tech. Class Notes Srikrishna Page214


Naga Raju Sri Sai Ram
ASP.Net --

 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
o 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
o 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).
o Once the dependent object is modified or deleted then cache data will be expired.
Ex: -
o Create one web form & place GridView with Button.
o Crate one .xml file Say scores.xml
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>

Naresh Tech. Class Notes Srikrishna Page215


Naga Raju Sri Sai Ram
ASP.Net --

<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>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

Naresh Tech. Class Notes Srikrishna Page216


Naga Raju Sri Sai Ram
ASP.Net --

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

Naresh Tech. Class Notes Srikrishna Page217


Naga Raju Sri Sai Ram
ASP.Net --

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"?>
<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>
Naresh Tech. Class Notes Srikrishna Page218
Naga Raju Sri Sai Ram
ASP.Net --

<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
{

Naresh Tech. Class Notes Srikrishna Page219


Naga Raju Sri Sai Ram
ASP.Net --

ds = (DataSet)Cache["dsscore"];
}
else
{
ds = new DataSet();
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();
Naresh Tech. Class Notes Srikrishna Page220
Naga Raju Sri Sai Ram
ASP.Net --

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 ***


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 doesn’t contain any page related code like <html>, <head>, etc…because 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.

Naresh Tech. Class Notes Srikrishna Page221


Naga Raju Sri Sai Ram
ASP.Net --

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

Naresh Tech. Class Notes Srikrishna Page222


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page223


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page224


Naga Raju Sri Sai Ram
ASP.Net --

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 ***

Naresh Tech. Class Notes Srikrishna Page225


Naga Raju Sri Sai Ram
ASP.Net --

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”/>

Naresh Tech. Class Notes Srikrishna Page226


Naga Raju Sri Sai Ram
ASP.Net --

<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>

<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>

Naresh Tech. Class Notes Srikrishna Page227


Naga Raju Sri Sai Ram
ASP.Net --

</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>

Naresh Tech. Class Notes Srikrishna Page228


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page229


Naga Raju Sri Sai Ram
ASP.Net --

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

Naresh Tech. Class Notes Srikrishna Page230


Naga Raju Sri Sai Ram
ASP.Net --

Note: - Use chat button also

Dt: 02-07-2010

Naresh Tech. Class Notes Srikrishna Page231


Naga Raju Sri Sai Ram
ASP.Net --

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…

Naresh Tech. Class Notes Srikrishna Page232


Naga Raju Sri Sai Ram
ASP.Net --

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 ***


Dt: 03-07-2010

Mobile Applications

Naresh Tech. Class Notes Srikrishna Page233


Naga Raju Sri Sai Ram
ASP.Net --

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 doesn’t 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.

Naresh Tech. Class Notes Srikrishna Page234


Naga Raju Sri Sai Ram
ASP.Net --

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” (It’s 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

Server Side Mobile Applications:


.NET provides MMIT (Microsoft Mobile Internet Toolkit) that contains various classes to develop
mobile based applications.
VS 2008/2010 doesn’t support development of these applications. If we want we can develop
them without help of designer, toolbox, etc…like 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: -
o Start VS 2005
o New website
o Delete default.aspx which is web page

Naresh Tech. Class Notes Srikrishna Page235


Naga Raju Sri Sai Ram
ASP.Net --

o Add a new item  mobile web form


o Design the form just like any other form & write code in similar way (unified model).
o Start Microsoft Mobile Explorer & type the address of website
3rd party mobile Explorers
o openwave.com
o wap.nokia.com  nokia wap toolkit
o blackberry.com
etc…

Start  File  New website  ASP.NET web site  OK.


File system, C:\\demos\mobiledemo

Default.aspx

Naresh Tech. Class Notes Srikrishna Page236


Naga Raju Sri Sai Ram
ASP.Net --

Note: design page


Build  Re-Build
Note:- Mobile Explorer 3.0 software
View  Designer  simple….

Naresh Tech. Class Notes Srikrishna Page237


Naga Raju Sri Sai Ram
ASP.Net --

Server Side Example:-


Start  File  New website  ASP.NET web site  OK.
C:\\demos\demomobile

Naresh Tech. Class Notes Srikrishna Page238


Naga Raju Sri Sai Ram
ASP.Net --

In default.aspx design page open & select command1

Naresh Tech. Class Notes Srikrishna Page239


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page240


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page241


Naga Raju Sri Sai Ram
ASP.Net --

Double Click on SUBMIT Button & write on following Code:

Run it & go to build Re Build it

Naresh Tech. Class Notes Srikrishna Page242


Naga Raju Sri Sai Ram
ASP.Net --

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

*** END OF THE DAY ***


Dt: 06-07-2010

.NET Client Side Mobile Applications:


We mainly target Pocket PC’s***, PDA’s & Smart Phones *** for this type of applications. Pocket
PC’s means a PC kind of device with mobile capabilities, where ad Smart Phone & PDA’s
(Personal Data Assistant) contain mobile features more then PC’s 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 doesn’t 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
Naresh Tech. Class Notes Srikrishna Page243
Naga Raju Sri Sai Ram
ASP.Net --

Demo 1: Environmet
Using Visual studio 2008(software)

protected void Linklable1_click(object sender……..)


{
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:-

Naresh Tech. Class Notes Srikrishna Page244


Naga Raju Sri Sai Ram
ASP.Net --

Demo2:Changing Platflom (adv of windows mobile unified libralties)

Output:-

Naresh Tech. Class Notes Srikrishna Page245


Naga Raju Sri Sai Ram
ASP.Net --

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

Naresh Tech. Class Notes Srikrishna Page246


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page247


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page248


Naga Raju Sri Sai Ram
ASP.Net --

OutPut:-

OutPut:-

Naresh Tech. Class Notes Srikrishna Page249


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page250


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page251


Naga Raju Sri Sai Ram
ASP.Net --

OutPut:-

Example-2:-

Naresh Tech. Class Notes Srikrishna Page252


Naga Raju Sri Sai Ram
ASP.Net --

OutPut:-

Naresh Tech. Class Notes Srikrishna Page253


Naga Raju Sri Sai Ram
ASP.Net --

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

Naresh Tech. Class Notes Srikrishna Page254


Naga Raju Sri Sai Ram
ASP.Net --

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?

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.

Naresh Tech. Class Notes Srikrishna Page255


Naga Raju Sri Sai Ram
ASP.Net --

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 ***


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())

Naresh Tech. Class Notes Srikrishna Page256


Naga Raju Sri Sai Ram
ASP.Net --

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();
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;
}

Naresh Tech. Class Notes Srikrishna Page257


Naga Raju Sri Sai Ram
ASP.Net --

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 ***

Naresh Tech. Class Notes Srikrishna Page258


Naga Raju Sri Sai Ram
ASP.Net --

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?
o Start a new website or any other type of project.
o 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.

Naresh Tech. Class Notes Srikrishna Page259


Naga Raju Sri Sai Ram
ASP.Net --

Another type.

Note:- Don’t close service.asmx.cs page & open another website

Naresh Tech. Class Notes Srikrishna Page260


Naga Raju Sri Sai Ram
ASP.Net --

Proxy is ready and knows we can consume – design the form according to the method that we
want to use. On our 1st 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

Naresh Tech. Class Notes Srikrishna Page261


Naga Raju Sri Sai Ram
ASP.Net --

Run it

OutPut:-

Naresh Tech. Class Notes Srikrishna Page262


Naga Raju Sri Sai Ram
ASP.Net --

EX-3:

OutPut:-

Naresh Tech. Class Notes Srikrishna Page263


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***


Dt: 12-07-2010

ASP.NET UI Feature:-
o 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.
 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:

Naresh Tech. Class Notes Srikrishna Page264


Naga Raju Sri Sai Ram
ASP.Net --

Example:

Naresh Tech. Class Notes Srikrishna Page265


Naga Raju Sri Sai Ram
ASP.Net --

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.

Naresh Tech. Class Notes Srikrishna Page266


Naga Raju Sri Sai Ram
ASP.Net --

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.

Naresh Tech. Class Notes Srikrishna Page267


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page268


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page269


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page270


Naga Raju Sri Sai Ram
ASP.Net --

Naresh Tech. Class Notes Srikrishna Page271


Naga Raju Sri Sai Ram
ASP.Net --

*** END OF THE DAY ***

Dt: 13-07-2010

Naresh Tech. Class Notes Srikrishna Page272


Naga Raju Sri Sai Ram
ASP.Net --

ASP.NET DEPLOYMENT

The process of distributing or delivering a developed application is called Deployment.


.NET is RADD (Rapid Application Development & Deployment) using its IDE’s 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)

Naresh Tech. Class Notes Srikrishna Page273


Naga Raju Sri Sai Ram
ASP.Net --

 Control Panel Details


 ftp details
 sitename: ftp://simpletraining.net

*** END OF THE CLASS***


[email protected] (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,

Your’s

KRISHNA.K
(Nagaruju Sir Student)
[email protected]

Naresh Tech. Class Notes Srikrishna Page274

You might also like