Está en la página 1de 21

ASP.

NET
Overview of ASP.NET and Web Forms
Microsoft® ASP.NET is the next generation technology for Web application development. It
takes the best from Active Server Pages (ASP) as well as the rich services and features provided
by the Common Language Runtime (CLR) and add many new features. The result is a robust,
scalable, and fast Web development experience that will give you great flexibility with little
coding.

Web Forms are the heart and soul of ASP.NET. Web Forms are the User Interface (UI) elements
that give your Web applications their look and feel. Web Forms are similar to Windows Forms in
that they provide properties, methods, and events for the controls that are placed onto them.
However, these UI elements render themselves in the appropriate markup language required by
the request, e.g. HTML. If you use Microsoft Visual Studio® .NET, you will also get the familiar
drag-and-drop interface used to create your UI for your Web application.

Web Forms are made up of two components: the visual portion (the ASPX file), and the code
behind the form, which resides in a separate class file.

Browser

IIS

ASP.NET
Web Forms NET Language
Web Controls VB, C#
The Purpose of Web Forms

Web Forms and ASP.NET were created to overcome some of the limitations of ASP. These new
strengths include:

• Separation of HTML interface from application logic

• A rich set of server-side controls that can detect the browser and send out appropriate markup
language such as HTML
• Less code to write due to the data binding capabilities of the new server-side .NET controls

• Event-based programming model that is familiar to Microsoft Visual Basic® programmers

• Compiled code and support for multiple languages, as opposed to ASP which was interpreted
as Microsoft Visual Basic Scripting (VBScript) or Microsoft Jscript®

Types of Controls
1. Server Controls
AdRotator
DataGrid Control
DataList Control

2. Validation Controls
CompareValidator
CustomValidator
RangeValidator
RegularExpressionValidator
RequiredFieldValidator

3. HTML Controls
4. Data Controls.
ASP.NET Server applications are

IIS - Internet Information Server 5.0 (Microsoft Networking) - Windows NT4.0 ,


Windows 2000

PWS - Personal Web Server (PC'S) - Window 95,Windows 98


ChilliSoft - Windows NT
Apache Tomcat -> Windows NT, Windows 2000

By using any one of the above mentioned servers, we can perform ASP.NET Page
validations. If there is a Server, we have to start the server. But ASP.NET Servers (both IIS and
PWS) can automatically start and run when the system switched on.

ASP.NET Objects

Response - Used to send information to the client. (Server to Browser)

Request - Used to retrieve Information included with the request from the client.
(Browser to Server)

Server - Used to communicate with the server.

Application - Used to store(cache) information about your application.

Session - Used to cache information about specific browser instance.

ObjectContext - Used to initiate and control transactions and create new objects
through Microsoft Transaction Server.

ASPError - Used to obtain information about the errors that occur while the ASP
engine processes a script.
Response Object

Used to send information to the client

Response.Write Method
Response.Cookies Collection
Response.AddHeader Method
Response.Redirect Method
Response.Status Property
Response.End Method
Response.Flush Method

Response.Write Method
Used to write data to client

Response.Write(“<h1 align=center> Hello World </h1>”);

Response.Cookies Collection

Storage of values temporarily. Keeping a variable values between the pages. Storing
values between the pages is called maintaing state.

Response.Cookies[“variable”] .value = value

Response.AddHeader Method

Used to add some Header values in the HTTP Header

Eg:

Page_Load()

Response.AddHeader("Refresh","5;url=redipage.aspx");
Response.Write("This page has been redirected after <span id='jtime'> 5 </span> seconds");

<script language=”vbscript”>
window.setTimeout "changeval()",1000,"vbscript"
sub changeval()
dim time
time = document.all.item("jtime").innerText
time = time - 1
document.all.item("jtime").innerText = time
if time > 0 then
window.setTimeout "changeval()",1000,"vbscript"
End if
End Sub
<script>

Response.Redirect Method

Used to redirect another file

Response.Redirect(“filename.aspx”);

LinkButton1_click
{
Response.Redirect("http://localhost/MyAsp/CookieMgmt/Inbox.aspx");
}

Response.Status Property

Eg:
Page_Load()
string ipaddr;
ipaddr = Request.ServerVariables["REMOTE_ADDR"];
Response.Write(ipaddr);
if (!ipaddr.Equals("127.0.0.1"))
{
Response.Status="403 Access Forbidden";
Response.Write(Response.Status);
Response.End();
}
Response.Write("<HTML>");
Response.Write("<BODY>You have accessed this page through the IP Address of
127.0.0.1 </BODY> </HTML>");

Request Object

The request object contains the information that the browser sends to the server. For
every request, the browser include some additional information for communication like
IPAddress, the type of information required, all form content, QueryString variables, browser
type information Etc. Use the request object to read that information.

Five different Collection of infomations


1. ClientCertificates - Contains security information (Passing via HTTPS Protocol)
2. Cookies - Contains cookie values sent by the browser.
3. Form - Contain information the user enters into input controls and information your
application stored in form variables.
4. QueryString - Contains information sent with the URL.
5. ServerVariables - Contains information that the server automatically parses for every request.

Request.ServerVariables Collection
This contains standard information automatically sent by the browser for every request.
Some Important Values
APPL_PHYSICAL_PATH - The Physical path of your application. Does not include the
name of the requested file. This value is useful, because you should never hard-code a path in-
your application, if possible.
LOCAL_ADDR - The IPAddress of the server hosting your application.
LOGON_USER - The network username of the browser requesting this resource
PATH_INFO - The Full physical path to the requested file. This value is useful for
redirect.

SERVER_NAME - The name of the server requested by the user. Note that all servers
support localhost.
SERVER_PORT- The IP port number - Usually 80 for HTTP Servers.
HTTP_USER_AGENT - The make and version of the requesting Browser
SessionID - SessionID of the Specific browser

Eg:
Page_Load()
Response.Write("<h2> Request ServerVariables List </h2>");
Response.Write("Application Physical Path : " +
Request.ServerVariables["APPL_PHYSICAL_PATH"] + "<BR>");
Response.Write("Local Addr : " + Request.ServerVariables["LOCAL_ADDR"] + "<br>");
Response.Write("Path Info : " + Request.ServerVariables["PATH_INFO"] + "<br>");
Response.Write("Server Name : " + Request.ServerVariables["SERVER_NAME"] + "<br>");
Response.Write("Server Port : " + Request.ServerVariables["SERVER_PORT"] + "<br>");
Response.Write("Http User Agent : " + Request.ServerVariables["HTTP_USER_AGENT"] +
"<br>");

Request.Cookies Collection
The response.Coookies is write-Only.
The request.Cookies is Read-only
If you set a Response.Cookie, it will appear in the next request from the client browser.
Maximum 1024 Character data's are stored
Syntax
variable = Request.Cookies["variable"].Value
Eg:
Login.aspx
Label -> Username
Label -> Password
TextBox1 -> txtUname
TextBox2 -> txtPword
Button -> btnSubmit -> Submit
Codings
Using System.Data.SqlClient;
SqlConnection con = new SqlConnection("server=server;Database=master;User
id=sa;Password=killer");
string qry = "Select * from UserLogin where username='" + txtUname.Text + "' and pword='" +
txtPword.Text + "'";
SqlCommand cmd = new SqlCommand(qry,con);
cmd.Connection.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Response.Cookies["username"].Value = txtUname.Text;
Response.Cookies["password"].Value = txtPword.Text;
Response.Redirect("http://localhost/MyAsp/CookieMgmt/Links.aspx");
}
else
Response.Write("Invalid Username and PAssword");
cmd.Connection.Close();

Links.aspx
LinkButton1 -> Inbox
LinkButton2 -> Compose

codings
LinkButton1_click
{
Response.Redirect("http://localhost/MyAsp/CookieMgmt/Inbox.aspx");
}
LinkButton2_Click
{
Response.Redirect("http://localhost/MyAsp/CookieMgmt/Compose.aspx");
}

Inbox.aspx
Page_Load
{
Response.Write("<h1 align=center> Inbox </h1>");
Response.Write("Username : " + Request.Cookies["username"].Value + "<br>");
Response.Write("Password : " + Request.Cookies["password"].Value);
}

Compose.aspx
Page_Load
{
Response.Write("<h1 align=center> Compose </h1>");
Response.Write("Username : " + Request.Cookies["username"].Value + "<br>");
Response.Write("Password : " + Request.Cookies["password"].Value);
}

Application Object
To store global data.
Application object provide our application with global data or information that applies to
all users for our application.
There is only one Application object for all users of your Application.

Introduction to Threads
Web Servers must handle simultaneous request from multiple Users. Sometimes, usage is
slow. To Keep track of request, the web servers puts them in a queue. A queue is a list in which
you add items at on end and remove them at the other end.
Of course, it will not handle multiple threads simultaneously. It uses a time slice method
for equal time sharing for the users.
The ASP.NET Engine, by default starts with three initial threads. It can be increased
based on the processor speed.

Application.Lock Method
Application.UnLock Method
Application Lock / Unlock Method
There's only one application object, shared among multiple users. Any sessions can
access values in the Application Object, but you need to ensure that only one session has
permission to change values at any given time. To do that, You lock the Application before
changing the value and unlock it when you finished your modifications.
Eg:
global.asax.cs
Application_Start()
{
Application["page1"] = 0;
}

WebForm1.aspx.cs
Response.AddHeader("Refresh","5");
int pagecount;
Application.Lock();
Application["page1"] = Int32.Parse(Application["page1"].ToString()) + 1;
pagecount = Int32.Parse(Application["page1"].ToString());
Application.UnLock();
Response.Write("This page has been visited " + pagecount + " times");

Server Object
This Object gives high-level access to the Server.
Using this properties and Methods we can
1. Execute other ASP Files
2. Translate Virtual path to Physical path
3. Perform Server-Side Redirects

Server.ScriptTimeout Property
Server.HtmlEncode Method
Server.Execute Method
Server.Transfer Method
Server.MapPath Method

Server.ScriptTimeOut Property
Specifies the amount of runtime in seconds for a script before it terminates.

Response.Write(Default Timeout : " + Server.ScriptTimeout + “<br>");


Server.ScriptTimeout = 150;
Response.Write("After Changed : " + server.ScriptTimeout);

Server.HtmlEncode Method
Response.Write(Server.HtmlEncode("<html>"));

Server.MapPath Method
This will map the Physical path of the file.
string physicalAppPath;
physicalAppPath = Server.MapPath("/myasp");
Response.Write("The Physical path is : " + physicalAppPath + "<br>");

Session Object
An ASP.NET Sessions begins at a browser's First request for any ASP.NET page in a
directory marked as an IIS application. The server immediately redirects the user to a file called
global.asax.
Global.asax
Application onStart
Session onStart
Session onEnd
Application onEnd

SessionID Cookie
The server gives the browser a unique token in response to its first request so the browser
can identify itself to the server for subsequent request.

There are five ways to end a session


1. Length of interval time with the Session.TimeOut Property
2. Using Session.Abandon command
3. You can shut down the IIS
4. You can modify the global.asa
5. The brower can refuse the SessionID cookie

Steps performs in global.asax File


1. The first person to request a file from your application causes ASP.NET to find the
gloabal.asax file in the application's root directory. The server performs the same steps whether
or not the global.asax file exists
2. Immediately after it creates the Application object, ASP.NET calls the
Application_OnStart Event.
3. When the Application OnStart Event completes - the ASP.NET engine creates a new
SessionID, writes the SessionID cookie header, then creates a new Session object and starts the
Session.Timeout Timer.

4. Immediately after creates the new Session object, ASP.NET Calls the Session_OnStart
Event
5. When the session times out or you issues the Session.Abandon command, the
ASP.NET engine calls the Session_onEnd event procedure., then destroys the Session Object

6. After the ASP engine destroys the last session object, it calls the Application_OnEnd
event procedure

Session.Abandon Example
global.asax.cs
Application _Start()
{
Application["counter"] = 0
}

Session_Start()
{
Application["counter"] = Int32.parse(Application["counter"].ToString()) + 1
}

WebForm1.aspx.cs
Response.Write("<h1 align=center> Session Abandon Example </h1>");
Response.Write("Your Session ID is : " + Session.SessionID + "<br>");
Response.Write("Application[counter] : " + Application["counter"]);
Session.Abandon();
Response.Write("<p> Your session has been abandoned. Make a note of your SessionID,then
referesh your browser. Each time you referesh this page, you should get a new SessionID.</p>");

Validation Controls
RequiredFieldValidator
Properties
ID -> Name of the Validator
ControlToValidate
ErrorMessage

RegularExpressionValidator
Properties
ID
ControlToValidate
ErrorMessage
Text
ValidationExpression - \d{1,} [0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}

AdRotator Component
Banner.xml
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl> http://localhost/shoba/AdComponent/se_01.gif </ImageUrl>
<NavigateUrl> http://localhost/shoba/CSC/WebForm1.aspx </NavigateUrl>
<AlternateText> The Order Online Form for Webshoppe </AlternateText>
<Impressions> 1 </Impressions>
</Ad>
<Ad> <ImageUrl> http://localhost/shoba/AdComponent/Flowers.gif </ImageUrl>
<NavigateUrl> http://localhost/shoba/CSC/Registration.aspx </NavigateUrl>
<AlternateText> This page is used for Registration </AlternateText>
<Impressions> 2 </Impressions>
</Ad>
</Advertisements>

Distributed Computing
* Improve Performance
* Components are compiled separately -> Business Logic
* Code Reusability
Distributed Technology
1. Sockets
2. RPC -> Remote Procedure call
3. RMI
4. CORBA
5. DCOM

Sockets -> Berkely Software Division


Client /Server Technology model
-> Networking (Chatting, File Transfering, Data transferring)
Socket -> Establish connection
Packet -> Data Container (byte Data,size of data, destination IP Address)
Issues
* Supports only primitive type(data types like integer, float, char) communication
* Image, object and method invocation is not possible
* Doesn't have auto marshalling and demarshalling

Marshalling -> Convert Object to byte


Demarshalling -> Convert byte to object

Server Client

Connect
Listen

Accept

Send Receive

Receive Send
RPC -> Remote Procedure Call
* RPC is a layer
* One more layer in OSI model.
* It supports Method invocation
* The data are send and received as a string format
* It doesn't support object transfer.

RMI/CORBA/DCOM
* Enhancement of RPC
* Object transfer is possible.

RMI -> Remote Method Invocation


* Language Dependent
* Platform Independent
* Communication between two objects.
* The two objects must be developed in Java
* Supports all type of communication
*RMI Registry
JNDI -> Java Naming and Directory Index
JRMP -> Java Remote Method Protocol

Client / Java Server / Java

RMI Registry

Stub Skeleton

Network
CORBA -> Common Object Request Broker Architecture
* Language Independent
* Platform Independent
* Communication two different objects present in two different machines
* IIOP -> Internet Inter ORB Protocol
* COS Registry and COS Naming Service

DCOM -> Distributed Component Object Model.


* Language Independent
* Platform Dependent
* Communication between two objects developed using Windows based application.
* ORPC -> Object Remote Procedure call.
* Windows Registry

RMI / CORBA / DCOM Issues


* Publishing
* Naming Service
* Network
Protocols
Port

B2B(Business to Business) Integration is not possible

Web Services

SOAP -> Simple Object access Protocol


* Developed by W3Consortium
* Based on XML
* Instead of COM / DCOM webservices are developed.
XML
Extensible Markup Language
Meaning for content
XSL -> Extensible Style sheet Language (XML with CSS (Cascading Style Sheet))

Eg:
Document Object Model (DOM)
Parsing XML document to VB or any other application

DSO -> Data Source Object (Javascript, VBScript)


xml4jparser -> Java

Creating Web Service


1. File -> New -> Visual Basic .NET -> ASP.NET Web Service ->
http://localhost/MyAsp/Service1
2. Click the like "Switch to code view"
3. Add Methods

<WebMethod> Public Function add(ByVal a as Integer,ByVal b as Integer) as Integer


Return a + b
End Function

<WebMethod> Public Function add(ByVal a as Integer,ByVal b as Integer) as Integer


Return a * b
End Function

4. Run the Application by Pressing "F5"


5. Copy the URL and Paste it in the notepad
6. Close the Solution

Adding Web service in C#


1. File -> New -> Visual C# -> Console application
WebService1
2. Project Menu -> Add Web Reference -> Paste the URL -> Click "Add Reference"
3. Add the following Codings
static void Main(string[] args)
{
localhost.Service1 obj = new localhost.Service1();
string str = obj.HelloWorld();
Console.WriteLine(str);
int c = obj.add(10,20);
int d = obj.mul(3,4);
Console.WriteLine("c = " + c);
Console.WriteLine("d = " + d);
Console.ReadLine();
}

Creating Web Service


1. File -> New -> Visual Basic .NET -> ASP.NET Web Service ->
http://localhost/MyAsp/Service1
2. Click the like "Switch to code view"
3. Add Methods
<WebMethod()> Public Function getData(ByVal pid As Integer) As Product
Try
Dim con As SqlConnection
con = New SqlConnection("server=server;Database=master;User
id=sa;Password=killer")
Dim cmd As SqlCommand
Dim qry As String
qry = "Select * from prod where pid=" & pid
cmd = New SqlCommand(qry, con)
cmd.Connection.Open()
Dim dr As SqlDataReader
Dim pr As New Product
dr = cmd.ExecuteReader()
If (dr.Read()) Then
pr.pid = dr.GetInt32(0)
pr.pname = dr.GetString(1)
pr.qty = dr.GetInt32(2)
pr.price = dr.GetInt32(3)
Return pr
End If
cmd.Connection.Close()
Catch ex As Exception
ex.ToString()
End Try
End Function

Public Class Product


Public pid As Integer
Public pname As String
Public qty As Integer
Public price As Integer
End Class

4. Run the Application by Pressing "F5"


5. Copy the URL and Paste it in the notepad

6. Close the Solution


Adding Web service in C#
1. File -> New -> Visual C# -> Console application
WebService1
2. Project Menu -> Add Web Reference -> Paste the URL -> Click "Add Reference"
3. Add the following Codings

static void Main(string[] args)


{
localhost.Product pr1 = new localhost.Product();
localhost.Service1 obj = new localhost.Service1();
int pid;
Console.WriteLine("Enter Product ID : ");
pid = Int32.Parse(Console.ReadLine());
pr1 = obj.getData(pid);
Console.WriteLine("Product ID : " + pr1.pid);
Console.WriteLine("Product Name : " + pr1.pname);
Console.WriteLine("Qty : " + pr1.qty);
Console.WriteLine("Price : " + pr1.price);
Console.ReadLine();
}

También podría gustarte