Asp Net
Asp Net
ASP.Net --
INTRODUCTION
Dt: 29-03-2010
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.
Important Points:
Why. Net?
What .Net languages are?
What is ASP.Net? Why?
Dt: 30-03-2010
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.
Client:-A program which is return to make requests and gets results or which is written to run as
standalone is called Client Program.
- 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.
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.
Dt:02-04-2010
Server Model of Operating System.
Web Server –One or more web sites.
Browser.
HTTP
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.
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
- 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.
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.
Dt: 05-04-2010
Authentication Required: - Message that is getting displayed….
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.
---------------------------------------------------------------------------------------------------
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)
Sitehttp://www.asp.net (official site)
In this side we have videos/articles/ demos
One are more (alternative site)--- www.codeproject.com
Class room slides & some articles http://nbende.wordpress.com
(for NIT students).
HTML Forms:-
In HTML all graphical elements are designed as form elements. If we want to create this
graphical element then we must write <form>tag followed by graphical elements like Button,
Checkbox, radio button etc…
Form is the important media of communication b/w client & server. When we submit the form
all form elements will travel to server.
To create a Button we use,
<input type=button name=b1 value=demo>
Naresh Tech. Class Notes Srikrishna Page12
Naga Raju Sri Sai Ram
ASP.Net --
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
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
(Q).How to write client side scripting & which scripting language is preferred?
Ans: - In HTML we have <script> tag to write client side scripting. This tag indicates Browser that we are
writing code & needs to be executed with interpreter.
- Language =<language> or
- Type=<text/language> is an attribute of script tag to specify particular language.
- We must close the opened script tag otherwise all content will be taken as script only.
- Inside <script>tag we must write only relevant language code but not any other code.
Ex: - <script type=text/javascript>
………js code………
</script>
Example:-1.<html>
<head><title>JavaScript Demo</title></head>
<body>
<h1>Java Script Demo</h1>
<h2>This is HTML</h2>
<script language=”javascript”>
Document.Write(“this is javascript”);
</script>
<h2>Back to HTML</h2>
</body>
</html>
Output:-
Example:-2.<html>
<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:-
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.
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
</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:-
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.
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”>
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)
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:-
Note: - Objects---2
Events--- 2
Functions---1
We can call functions with different objects and different events also. They need not be similar
object/similar events.
To write multiple Events for single objects just write it another attribute i.e., provide space after
one event and write another event.
Ex:-4 <html>
<body onload=ShowMsg(10)> demo4.html
<h1>JavaScript Events</h1>
<form name=”frm”>
User Name<input type=text name=t1>
<br>
Emain Id<input type=text name=t2>
<br>
<input type=button name=b1 value=Submit onclick=ShowMsg(“Welcome”)>
<input type=button name=b2 value=Help onclick=ShowMsg(“No-Help”)
onmouseover=ShowMsg(“cannot-click-Me”)>
<script language=”JavaScript”>
function ShowMsg()
{
alert(x);
}
</script>
</form>
</body>
</html>
OutPut:-
Note: - Objects---3
Events--- 4
Functions---1
$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.
<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()………)
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>.
<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:-
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.
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.
(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>
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
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: -
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.
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.
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.
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.
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.
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: -
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”;
}
<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
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;
}
Code:-
Protected void Button1_Click (Object Sender, EventArgs e)
{//and button feature
CheckBox1.Items Add (TextBox1.Text);
}
Protected void CheckBox1_SelectedIndexChanged (Object Sender, EventArgs e)
{
Label1.Text=CheckBox1.SelectedValue;
}
Select CheckBox Properties AutoPostBack =True
Remove Label1.Text=ListBox1.SelectedValue;
And write following code:
Protected void CheckBox1_SelectedIndexChanged (Object Sender, EventArgs e)
{
if(CheckBox1.SelectedValue==”10”)
{
Label1.Text=”Web Developed”;
}
else if (CheckBox1.SelectedValue==”20”)
{
Label1.Text=”.Net language: prepared”;
}
else if (CheckBox1.SelectedValue==”30”)
{
Label1.Text=”.Net language”;
}
else
Label1.Text=CheckBox1.SelectedValue;
}
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.
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)
{
ArrayList Courses=GetCourses(); //courses is DataObject
ListBox1.DataSource=Courses;
ListBox1.DataBind();
DropDownList1.DataSource=Courses;
DropDownList1.DataBind();
CheckBoxList1.DataSource=Courses;
CheckBoxList1.DataBind();
RadioButtonList1.DataSource=Courses;
RadioButtonList1.DataBind();
BulletedList1.DataSource=Courses;
BulletedList1.DataBind();
}
publicArrayListGetCourses() //prepared
{
ArrayList obj=new ArrayList();
obj.Add(“ASP.NET 4.0”);
obj.Add(“C#.NET 3.0”);
obj.Add(“VB.NET 3.0”);
obj.Add(“SQL Server”);
obj.Add(“Biztalk Server”);
return obj;
}
OutPut:-
EX-2:-
Code:-
using System;
using Syste.Collections.Genaric;
…………………………………………..
………………………………………….
………………………………………….
(Add) using System.Collections; //public partial class default
----------------------------------------------------------------------------------------
protected void Page_Load(object sender, EventArgs e)(………)
------------------------------------------------------------------------------------------
protected void Button2_Click(object sender, EventArgs e)
{
List<string> Courses=GetCourses(); //courses is DataObject
ListBox1.DataSource=Courses;
ListBox1.DataBind();
DropDownList1.DataSource=Courses;
DropDownList1.DataBind();
CheckBoxList1.DataSource=Courses;
CheckBoxList1.DataBind();
RadioButtonList1.DataSource=Courses;
RadioButtonList1.DataBind();
BulletedList1.DataSource=Courses;
BulletedList1.DataBind();
}
public List<string> GetCourses() //prepared
{
List<string> obj=new List<string>();
obj.Add(“ASP.NET 4.0”);
obj.Add(“C#.NET 3.0”);
obj.Add(“VB.NET 3.0”);
obj.Add(“SQL Server”);
obj.Add(“Biztalk Server”);
return obj;
}
Some Advantages of this Programming is:
- No need to write logics with loops & fill values in controls.
- Scalable application because data object can be modified independent of control.
- We also get relation between control & data i.e., if we reflects with that & viceversa…..
Some advanced List controls are TreeView &Menu under Navigation tab.
This controls also support same behavior like List controls i.e. Design time, runtime,
dataBinding ….
Add new item Webform home.aspx
Go to ToolBox Navigation Menu(Drag & Drop)- edit Menu Item
We add items click (+) button added item billow process.
We add sub items also select contact Us and click (+) button added sub item same as process.
After we select Auto format:
Dt:26-04-2010
Navigating Multiple forms:
The process of moving user from one form to another form within the application as well as
outside the applications is called Navigating between forms.
Asp.Net provides varies options to navigate between forms.
1. Using Response.Redirect(<Url>)method.
- With this option we can take from one page to other page within the side as well as
outside the site. Redirect 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
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:-
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.
---------------------------------------------------------------------------------------------
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.
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
-------------------------------------------------------------------------------------------------
In default7.aspx added one more TextBox(drag &drop)
Write the code from default8.aspx page select Page_Load & double click, write code:
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)
This view Button drag & drop inside the tag only, because drag& drop to the outside & run
it ERROR will be occur.
MultiView1.ActiveViewIndex=2;
}
Dt: 28-04-2010
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.
JS – Complex
- Time consuming
- ASP.NET Validation controls generates JavaScript for users, so that we need not write
explicitly JavaScript.
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.
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/….
Dt: 29-04-2010
In our example RangeValidator has not displayed any errorMessage when no value is entered. To avoid
this problem we have to create another required field validator performs null value checking.
There is one common property for all validation controls called “display”.
Display: static (d)/dynamic/none.
Static means the place for displaying error message will be reserved.
Dynamic means only when error occurs, it creates place for message & display
it.
None means no display of error message.
3. CompareValidator:
Used to perform validations which are comparison based 3 types compression can be done.
a) Control with another control
ControlToValidate
ControlToCompare
ErrorMessage
Operator
Type
b) Control-Value:
- ControlToValidator:Text
- ValueToCompare : 10
- Type : Integer
- Operator : Greater then
- ErrorMessage : Min 10 (or) above 10
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.
.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.
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.
CustomValidatorClient 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.
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.
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.
Client Targeting:
(Q).which validation always gets performed irrespective of client levels i.e.
UpLevel/DownLevel?
Ans:- Server side.
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:
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.
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?
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.
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).
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.
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.
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.
Code page:
protectedvoid page_Load(………)
{
}
protected void Button1_click(object………….)
{
BLJobs obj=new BLJobs();
GridView1.DataSource=obj.GetJobs();
GridView1.DataBind();
}
*** END OF THE DAY ***
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.
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.
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).
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
----------------------------------------------------------------------------------------------------------------------
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).
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.
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>
(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>
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).
Dt: 17-05-2010
3) CommandField of GridView & GridView Editing:
GridView not only presents the data but also provides good editing support. It has not
one field called CommandField which is used to display edit, update, Delete & Cancel
Button.
GridView supports editing of data using all its fields like BoundField, TemplateField,
CommandField, etc… it has a property called EditIndex. Whosedefault value is -1 &
provides Edit Table Row based on the given value.
How GridView editing is supported?
Ans:-The key for editing data in GridView is edit index. When we specify EditIndex value
to n, then nth record is set to be Editable record. All GridView fields react to EditIndex
property.
How BoundField React to EditIndex?
Ans:- when EditIndex is -1 which is its default value BoundField displays all records with
simple text (as we have seen)when EditIndex is set to sum record number then nth
record will be display with TextBoxes for editing & remaining all rows will be displayed in
simple text format.
How TemplateField react?
Ans:-TemplateField is also dependent on EditIndex property. It displays item template
content for all the rows & EditItem template for nth row that is, when EditIndex is
changed.
Ex:
publicList<ns.class> GetJobs()
{
ns. entities obj=new…..();
var x=from n in obj. table select n;
}
----------------------------------------------------------------------------------------------------------
Note:-
1. What is the important of EditIndex?
2. How BoundField, TemplateField is Dependent on EditIndex?
3. What is the use of CommandField?
--------------------------------------------------------------------------------------------------------
CommandField also reacts of EditIndex value it will display edit & delete buttons when
EditIndex is -1 & displays update Cancel for nth row.
We must provide editing of GridView using the entire above concept.
Demo:-
1. Assuming our EDM objects & BLJobs are present in the project (if not present create them)add
new form & placeButton, GridView inside it.
2. Write code in button to get data from BLJobs & Bind it to GridView.
3. Go to GridView & set AutoGenerateColumns to false. Go to SourceView & write code for
GridView this time along with editing support****. Including BoundField, TemplateField &
CommandField. (New: Read only, EditItem Template, CommandField).
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.
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.
Dt: 18-05-2010
Update part of GridView Editing:-
6) Select Row updating event of GridView & write code to perform following tasks,
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
3GridView1.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”);
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);
}
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?
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…
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 --
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>
}
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
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 --
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
<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.
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>
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
{
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
}
}
}
In our demo replace
<%#Eval(“price”)%> with <asp:Label ID=”lp1” runat=”server”
Text=’<%Eval(price)%>’/>
// (understand why this change)
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:-DetalisView:-
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
OUTPUT:-
Note:-EmptyDataText property of gridview displays text when there are no records in data object***.
Note:-Repeater no editing& also property EditIndex.
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.
<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.
Note: - we select one by one then the preview Box see the coding of that particular task.
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.
<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:-
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: -
NOTE:- NagaRaju Sir working this sites.
www.Burton.com
www.GetPivot.com
****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);
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.
using System.Net;
using System.Net.Mail;
public partial class_Default:system.Web.UI.page
{
MailMessage msgobj;
protected void ImageButton1_click(object…………..)
{
//send button code
SmtpClient serverobj=new SmtpClient();
serverobj.Credentials =new NetworkCredential(TextBox1.Text,TextBox2.Text);
serverobj.port=587; //25 is default for SMTP
serverobj.Host=”smtp.gmail.com”;
serverobj.EnableSsl=true;//default is false, secure socket layer
msgobj=new MailMessage();
msgobj.From = new MailAddress
(TextBox1.Text,”NIT INFO”,System.Text.Encoding.UTF8);
msgobj.To.Add(TextBox3.Text);
//…..other properties //msgobj.priority =MailPriority
msgobj.Subject=TextBox4.Text;
msgobj.Body=TextBox5.Text;
msgobj.Attachments.Add (new Attachment(MapPath(“bg3.jpg”)));
msgobj.deliveryNotificationOptions=DeliveryNotifications.Onfailure;
serverobj.Send(msgobj);
Label6.Text=”Mail Sent Successfully”;
}
}
*** 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>
</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());
}}}
………………………………………………………………………………………………………………
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.
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.
…………………………………………………………………………………………………………….
(.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.
i. Windows Authentication:
Note: -
Once passport identity is created then access may be granted to other websites also which is
passport identity.
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>
<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 that,
<?xml Version=”1.0”?>
<configuration>
<system.web>
<authorization>
<deny users=”?”/>
<allow users=”*”/>
</authorization>
</system.web>
</configuration>
Run the default.aspx
O/p:
[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.
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;
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.
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>
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;
}}
Out Put:-
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.
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
try
{
DB3PM…………..
}
//catch (Exception)
Catch (Exception e)
{
//throw new Exception(“user always Exist”);
Label1.Text=e1.Message;
}
}
In Register.aspx
OutPut:-
In our users table add hintqn, hintan, email columns & provide same while registering.
In admin folder create another page called changepassword.aspx design it & accordingly write
code user EDM layers.
In login page provide “forgot password then Recover” Linkbutton & Design separate form
where user can recover password based on hintqn & answer. Password should be sent to
registered emailid.
*** END OF THE DAY ***
Dt: 10-06-2010
Identity/Ticket will travel between every request & response. It is very important to understand
how it travels & in what mode the identity travels.
By default server uses HTTP Cookies to make this identity travel because cookies have the
functionality of making values travels between request/response.
(Q). Why forms Identity is created as Cookie by Server?
Ans: -Because identity needs to travel between request/response which cookies has.
Problem here is Cookies are owned/maintained by browser & browser can reject/disable cookies.
In such cases our authentication will not work server is dependent on click Browser.
Internet Browser Tools Internet options
1. security custom level default levelmedium to drag high.
2. Pri…. change to block all cookies OK.
One option is to ask user for enabling cookies & display the content normally. Other option is
maintaining identity without cookies. In ASP.NET version 2.0 CookieLess sessions & Cookieless
authentication is provide. Using this we can pass identity information with URL of Browser, but it
will be visible to the user. To do this we have one attribute for forms tag called Cookieless.
<forms Cookieless=……>
Where we can specified how authentication ticket should be maintained.
Note:-
1. HTTP Traffic Tools.
2. Internet browser Tools web development helper
Open new web form web location:HTTP selected.
Web.config
<authentication mode=”Forms”>
<forms Cookieless=”UseUri”>
</forms>
</authentication>
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
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 --
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?
Dt: 14-06-2010
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.
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***
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).
These concatenated values are converted into base 64 format***. These base 64 values are
stored in one or more hidden fields*** by server sent to client along with other from contents.
User adds/modifies the content & resubmits the form to server. Server first reads the hidden
field values so that it retains the last given values (act as stateful) &responds the same process
with new repeated as long as user is working with current page....”
Some controls 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***.
Dt: 16-06-2010
C:// ………….(right click) add a new item web form default.aspx
Default.aspx
Default.aspx.cs
publicpartialclass_Default : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) //1st Request
ListBox1.Items.Add("JAVA");
protectedvoid TextBox1_TextChanged(object sender, EventArgs e)
{
}
Output:-
publicpartialclassDefault2 : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) //1st Request
ListBox1.Items.Add("JAVA");
TextBox1.Text = "Hello";
}
publicpartialclassDefault2 : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) //1st Request
ListBox1.Items.Add("JAVA");
TextBox1.Text = "Hello";
Label1.Text = "Welcome";
}
in source:
<%@Page EnableViewState=”false” Language=”C#”%>
Design-
When we execute this form we will get new values add at run time in page load first Request.
When we past back the form newly added values are loss because we have set view state mode
property to disable.
The default value for view state mode is inherited which means it will take the setting of its
parent control. Because of this option we can really handle view state data according to our
versions. This property also makes ASP.NET control more valuable as in old cases they were
pointed out as Heavy data & traffic control.
More Advanced options of ViewState:
(Q). Is ViewState data Secured? How can we secure it?
No – some time we want to secure ViewState data also. To do this we have one property /
attribute for page called EnableViewStateMac=true/false(d).
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.
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
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***.
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.
Dt: 18-06-2010
Example for persistent Cookies:
OutPut:-
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;
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.
Dt: 19-06-2010
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.
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.
Dt: 21-06-2010
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.
A session can be ended programmatically also. Session object has a method called Abandon ()
which kills the current session.
Example figure:
Ex:-2in default.aspx
OutPut:-
Tariff.aspx
OutPut:-
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>
Dt: 23-06-2010
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.
Go to the project where we want to maintain Out Process & add configuration to implement
Out Process sessions.
<sessionState…………>
Web.Config
<configuration>
<system.web>
<sessionState mode=”StateServer”>stateNetworkTimeout=”120” stateConnectionString=
”192.168.100.1:42424”>
</sessionState>
Note: - Because system server is bezy then Hoe long will be wait that will be declared stateNet
WorkTimeout(network time out).
<configuration debug=”true” targetFramework =”4.0”/>
</system.web>
</Configuration>
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”
Dt: 24-06-2010
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
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>
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”.
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.
Data Caching:
Implemented using cache object & can store any type of data.
Both application & cache store data with same scope i.e., accessible to all. Cache is more
recommendedbecause it gives more features than application object & also eliminates the
problems of application object.
Both application & code may lead to inconsistency when accessed simultaneously.
To overcome this application variables & other will be in queue till unlock is issued.
Advantage: -Consistent.
This results in other problems are,
Locking all variables with Lock. Restricts user to create few variables with application with
application scope.
The time between Lock() & UnLock() should be less & it is dependent on programmer or
developer.
Ex:-
Application.Lock();
……………..
………………
Application.UnLock();
Cache data is self-locking data(Time gaps are reduced)
Cache locks only specific consumed data but not all the data inside it.
Some more features of Cache,
Time Based Expiry
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>
<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
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
{
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,
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.
2. Design the control according to requirement & write code the same. We can design a control
like page only – no difference in working.
3. Add<%@ OutputCache..........%> directive to the created control. This step results in fragment
caching when we consume the control in page. If we omit this step the nit results in a simple
user defined control.
4. Go to.aspx page where we want to consume this control. In ASP.NET if we want to consume a
user defined control then we must register it first using <%@ Register ………%> directive.
We Registera control by providing tagname, tagprefix, filename & sometimes the assembly (.dll)
name also. Once Registered.
<asp:Button
Tagprefix, Tagname
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.
Dt: 30-06-2010
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”/>
<MenuInfo>
<Img>2.jpg</Img>
<Title>Services</Title>
<loc>~/Default2.aspx</loc>
</MenuInfo>
<MenuInfo>
<Img>3.jpg</Img>
<Title>Gallery</Title>
<loc>~/Default3.aspx</loc>
</MenuInfo>
<MenuInfo>
<Img>4.jpg</Img>
<Title>DownLoad</Title>
<loc>~/Default4.aspx</loc>
</MenuInfo>
<MenuInfo>
<Img>5.jpg</Img>
<Title>ContactUs</Title>
<loc>~/Default5.aspx</loc>
</MenuInfo>
</TopMenu>
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>
Web.config
<configuration>
<appSettings>
<add key=”Title” value=”E-Learning”/>
<add key=”Logo” value=”logo.jpg”/>
<add key=”Banner” value=”banner.jpg”/>
Dt: 02-07-2010
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…
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.
Mobile Applications
In frontend parts of application one of the most important & also essential is mobile application.
.NET has any good (little confused) environment for developing mobile applications.
Form starting version there is always some mobile development in .NET.
Taking all of them we can say mobile applications as of today (july-2010) in .NET in 2 ways.
1. Server Side Mobile Applications.
2. Client Side Mobile Applications.
Dt: 05-07-2010
Default.aspx
Note:-Http://www.simpletraining.net
Demo 1: Environmet
Using Visual studio 2008(software)
Out put:-
Output:-
Dt: 07-07-2010
OutPut:-
OutPut:-
OutPut:-
Example-2:-
OutPut:-
Dt: 08-07-2010
Note: -
XML Web Services 2006
WCF XML WS + Remoting + Lot More…
According to XML web services we have to design our application in the given architecture.
XML, SAOP & WSDL are the key protocols or format for running an XML web service.
FLOW: -
1. Client makes a request to proxy which should already prepared by client only in client
language (normally).
(Q). What is a Proxy?
Ans: - It is also a class (1-Tier (all layers have connect to or commbaind one palce only
that is 1-Tier)- relation between client & Proxy ) which should be prepared by client
based on the web service. Proxy should know about webservice otherwise it cannot be
created. Proxy coding will be to own without a tool is very very complex.
Note: - ORB Object Request Broker
(Q). Why is Serialization>
(Q). what is Serialization?
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.
……………………………………………………………………………………………………………....
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.
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)
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;
}
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”………..)
Dt: 10-07-2010
Another type.
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
Run it
OutPut:-
EX-3:
OutPut:-
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:
Example:
Dt: 13-07-2010
ASP.NET DEPLOYMENT
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)
Thanks you,
Your’s
KRISHNA.K
(Nagaruju Sir Student)
[email protected]