Thứ Bảy, 22 tháng 2, 2014

Tài liệu Module 11: Internet Access pptx

Module 11: Internet Access 1


Overview
!
Internet Application Scenarios
!
The WebRequest and WebResponse Model
!
Application Protocols
!
Handling Errors
!
Security
!
Best Practices

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
The Microsoft
®
.NET Framework System.Net and System.Net.Sockets
namespaces provide a layered, extensible, and managed implementation of
Internet protocols that applications can use to send or receive data over the
Internet. The System.Net classes provide functionality that is similar to the
Microsoft WinInet API. These classes provide varying levels of detail, from a
generic request/response model to control over application protocols and
sockets. In particular, the System.Net classes are designed for writing
scaleable, high-performance applications.
An application can use the System.Net classes to communicate with any other
application that supports the basic Internet protocols. However, that other
application need not be a .NET application. The .NET Framework provides
alternative mechanisms for inter-application communication.
For example, .NET Framework remoting implements a generic mechanism for
.NET Framework objects to interact with one another across application
domains. In addition, the System.Web.Services namespace contains classes for
applications to build and use XML Web services that are based on the standard
Simple Object Access Protocol (SOAP).
For more information about the remoting and XML Web services approaches to
inter-application communication, see Module 12, “Serialization,” in Course
2349B, Programming with the Microsoft .NET Framework (Microsoft
Visual C#

.NET).
After completing this module, you will be able to:
!
Use the basic request/response model to send and receive data over the
Internet.
!
Use the System.Net classes to communicate with other applications by
using the Hypertext Transfer Protocol (HTTP), Transmission Control
Protocol (TCP), User Datagram Protocol (UDP), and Socket Internet
protocols.

Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
about the basic
request/response model that
is used to send and receive
data over the Internet, the
System.Net classes that
are used to communicate
with other applications, and
various techniques to
enhance application security
and performance.
2 Module 11: Internet Access


Internet Application Scenarios
!
Server-Side ASP.NET Applications
"
Obtain data from back-end sources for a browser
request
!
Peer-to-Peer Applications
"
Send and receive data by acting as servers and clients
!
Client Applications That Periodically Access the
Network
"
A robust implementation of HTTP 1.1, including:
Pipelining, chunking, authentication, pre-authentication,
encryption, proxy support, server certificate validation,
and connection management

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Several types of applications use the System.Net classes to send or receive data
over the Internet. The following three Internet application scenarios are
examples of Internet applications that use the System.Net classes:
!
Server-side ASP.NET applications that request data from server resources in
response to a browser request.
The System.Net classes are designed for writing scalable, high-performance
ASP.NET middle-tier applications. The server-side ASP.NET scenario
requires a robust middle-tier networking stack that can tolerate a high load.
The System.Net classes specifically fulfill this important customer
requirement. Such features as connection management, pipelining,
Keep-alive, and asynchronous operations ensure strong support for the
middle tier.
In addition, because the System.Net classes are part of an overall
framework, integration with ASP.NET features, such as impersonation and
caching, is seamless.
!
Peer-to-peer Windows Forms applications that act as servers and clients to
send and receive data.
!
Client applications that periodically access the network for updates.
The System.Net classes expose a robust implementation of the HTTP
protocol. Because a large share of Internet traffic travels over the HTTP
protocol, the protocol’s importance as an application protocol is significant.
The System.Net classes support most of the HTTP 1.1 protocol features.
The advanced features of HTTP 1.1 include pipelining, chunking,
authentication, pre-authentication, encryption, proxy support, server
certificate validation, connection management, and HTTP extensions.

Topic Objective
To introduce Internet
application scenarios that
use the System.Net
classes.
Lead-in
Several types of
applications use the
System.Net classes to send
or receive data over the
Internet.
Module 11: Internet Access 3


#
##
#

The WebRequest and WebResponse Model
!
Uniform Resource Identifier
!
NetworkStream Class
!
Creating a WebRequest
!
Invoking a WebRequest
!
Sending Data
!
Receiving Data
!
Using the WebRequest and WebResponse Model

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Internet applications can be classed broadly into two types: client applications
that request information, and server applications that respond to information
requests from clients. The classic Internet client/server application is the World
Wide Web, where people use browsers to access documents and other data that
is stored on Web servers worldwide.
Applications are not limited to playing either the client or server role; the
familiar middle-tier application server responds to requests from clients by
requesting data from another server. In this case, it is acting as both a server and
a client.
The client application makes a request by identifying the desired Internet
resource and the communication protocol that will be used to exchange the
request and response. If necessary, the client application also specifies any
additional data that is required to complete the request, such as proxy location
or authentication information. Authentication information includes such
information as user name and password. When the request is formed, it can be
sent to the server.
After the server has received the request and processed the response, the
response is returned to the client application. The response includes information
that supplements the contents of the response, such as the type of content,
which may include raw text or XML data.
Topic Objective
To introduce the topics in
the section.
Lead-in
Internet applications can be
classed broadly into two
types: client applications
that request information,
and server applications that
respond to information
requests from clients.
4 Module 11: Internet Access


The .NET Framework provides classes that can be used to implement a
request/response model to access Internet resources. The two principal classes
are the WebRequest class, which contains a request for the resource; and the
WebResponse class, which provides a container for the incoming response. In
addition, the Uri class is used to contain a Uniform Resource Identifier (URI),
which identifies the Internet resource that you are seeking. The
NetworkStream class is used to write and read the data.

A Uniform Resource Identifier URI is a compact representation of a
resource that is available to your application through the Internet. You may be
more familiar with the term, URL, which stands for Uniform Resource Locator.
URLs form a subset of the more general URI naming scheme. A URL identifies
an Internet resource that has a Web page address.

For applications that need to make simple requests for Internet resources, the
WebClient class provides common methods for uploading data to or
downloading data from an Internet server. WebClient relies on the
WebRequest class to provide access to Internet resources; therefore, the
WebClient class can use any registered pluggable protocol.
Note
Module 11: Internet Access 5


Uniform Resource Identifier
!
URI Contains:
"
Scheme identifier – specifies protocol to be used
"
Server identifier – specifies DNS name or TCP address
"
Path identifier – specifies location on the server
"
Optional query string – provides additional request information
!
Example: http://www.contoso.com/whatsnew.aspx?date=today
"
Scheme identifier – http
"
Server identifier – www.contoso.com
"
Path identifier – /whatsnew.aspx
"
Query String – ?date=today

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
The .NET Framework uses the URI to identify the desired communication
protocol and Internet resource.
The URI consists of at least three, and possibly four, parts:
!
The scheme identifier, which identifies the communications protocol that is
used by the request and response
!
The server identifier, which consists of a Domain Name System (DNS) host
name or TCP address that uniquely identifies the server on the Internet
!
The path identifier, which locates the requested information on the server
!
An optional query string, which passes information from the client to the
server

For example, the URI http://www.contoso.com/whatsnew.aspx?date=today
consists of the scheme identifier http, the server identifier www.contoso.com,
the path identifier /whatsnew.aspx, and the query string ?date=today.
Topic Objective
To introduce the four parts
of the URI.
Lead-in
The .NET Framework uses
the URI to identify the
desired communication
protocol and Internet
resource.
6 Module 11: Internet Access


NetworkStream Class
!
A NetworkStream Object Provides:
"
A Way to Send and Receive All Types of Web Data
"
Methods That Are Compatible with Other .NET Streams
"
Processing of Data As It Arrives
!
System.Text.Encoding – Characters from and to Bytes
!
Sequential Blocks Use StreamReader and StreamWriter
// reading ASCII stream to string
Byte[] read = new Byte[32];
int bytes = anASCIIStream1.Read(read, 0, read.Length);
string stringData = Encoding.ASCII.GetString(read);
// writing string to ASCII stream
Byte[] asciiBytes = Encoding.ASCII.GetBytes(stringData);
anASCIIStream2.Write(asciiBytes, 0, asciiBytes.Length);
// reading ASCII stream to string
Byte[] read = new Byte[32];
int bytes = anASCIIStream1.Read(read, 0, read.Length);
string stringData = Encoding.ASCII.GetString(read);
// writing string to ASCII stream
Byte[] asciiBytes = Encoding.ASCII.GetBytes(stringData);
anASCIIStream2.Write(asciiBytes, 0, asciiBytes.Length);

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
When resources on the Internet are obtained by using the System.Net classes, a
Stream object represents the data that is being sent and received.
Streams provide:
!
A common way to send and receive Web data.
Whether the actual contents of the file are HTML, XML, or another format,
an application uses Stream.Write and Stream.Read to send and receive
byte data.
!
Compatibility with streams across the .NET Framework.
Streams are used throughout the .NET Framework, which provides a rich
infrastructure for handling them. For example, by changing only the few
lines of code that initialize the stream, you can modify an application that
reads XML data from a file stream to read data from a network stream
instead.
The major differences between the NetworkStream class and other streams
are that the NetworkStream class is not seekable, the CanSeek property
always returns false, and the Seek and Position methods throw a
NotSupportedException.
!
Processing of data as it arrives.
Streams provide access to data as it arrives from the Internet, rather than
forcing your application to wait for an entire data set to be downloaded.

Topic Objective
To explain the function of
Network streams in the
.NET Framework.
Lead-in
When resources on the
Internet are obtained by
using the System.Net
classes, the data that is
being sent and received is
represented through a
Stream object.
Module 11: Internet Access 7


Conversion Between Characters and Bytes
The System.Text namespace contains classes for converting blocks of
characters to and from blocks of bytes. In particular, the Encoding class has
methods to convert arrays and strings of Unicode characters to and from arrays
of bytes, as in the following example:
// variable named anASCIIStream1 of type Stream
// has been previously assigned to a Stream
// containing bytes representing 7 bit ASCII character
//
// reading ASCII stream and converting to string
Byte[] read = new Byte[32];
int bytes = anASCIIStream1.Read(read, 0, read.Length);
string stringData = Encoding.ASCII.GetString(read);
//
// variable named anASCIIStream2 of type Stream
// has been previously assigned to a writable Stream
//
// converting string and writing 7 bit ASCII characters
Byte[] asciiBytes =
Encoding.ASCII.GetBytes(stringData);
anASCIIStream2.Write(asciiBytes, 0, asciiBytes.Length);

Converting Data from Sequential Blocks
When the data that must be converted is only available in sequential blocks,
such as data that is read from a long stream, an application may choose to use a
decoder or an encoder to perform the conversion. However, you can use the
StreamReader and StreamWriter classes to facilitate decoding and encoding
characters, as in the following example:
// variable anASCIIStream has been previously assigned
// to a Stream of ASCII bytes
StreamReader sr = new StreamReader(
anASCIIStream,Encoding.ASCII);

int length = 1024;
char[] Buffer = new char[1024];
int bytesread = 0;

//Read from the stream and write data to console
bytesread = sr.Read( Buffer, 0, length);
while( bytesread > 0 ) {
Console.Write( Buffer,0, bytesread);
bytesread = sr.Read( Buffer, 0, length);
}

//Close the stream when finished
sr.Close();

8 Module 11: Internet Access


Creating a WebRequest
!
The WebRequest Encapsulates Details of Request
"
Created by calling WebRequest.Create method
"
Set any property values that are required
"
Cast to access protocol-specific features
WebRequest req =
WebRequest.Create("http://www.contoso.com/");
WebRequest req =
WebRequest.Create("http://www.contoso.com/");
HttpWebRequest httpReq = (HttpWebRequest)
WebRequest.Create("http://www.contoso.com/");
// Turn off connection keep-alives.
httpReq.KeepAlive = false;
HttpWebRequest httpReq = (HttpWebRequest)
WebRequest.Create("http://www.contoso.com/");
// Turn off connection keep-alives.
httpReq.KeepAlive = false;
req.Credentials = new
NetworkCredential("username","password");
req.Credentials = new
NetworkCredential("username","password");

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Client applications request data from servers by using the WebRequest class
and its descendents. The WebRequest class encapsulates the details of the
process of connecting to the server, sending the request, and receiving the
response.
Calling WebRequest.Create
Applications create WebRequest instances through the static
WebRequest.Create method. WebRequest.Create is a static method that
creates a descendent WebRequest instance that is based on the URI scheme
that is passed.
For example, the following code creates an HTTP request to
www.contoso.com:
WebRequest req =
WebRequest.Create("http://www.contoso.com/");

Setting Required Property Values
Clients set required property values in the WebRequest instance. For example,
to support authentication, you can set the Credentials property to an instance of
the NetworkCredential class, as shown in the following code:
req.Credentials = new
NetworkCredential("username","password");

Topic Objective
To describe how client
applications use the
WebRequest.
Lead-in
Client applications request
data from servers by using
the WebRequest class and
its descendents.
Module 11: Internet Access 9


Casting WebRequest Objects to HttpWebRequest
To handle HTTP protocol requests to the Internet, the .NET Framework
provides an HttpWebRequest class that is derived from the WebRequest
class. In most cases, the WebRequest class provides all of the properties that
you need to make a request. However, if you need to access the HTTP
protocol-specific properties of the request, you can typecast WebRequest
objects that are created by the WebRequest.Create to HttpWebRequest, as in
the following example:
HttpWebRequest httpReq = (HttpWebRequest)
WebRequest.Create("http://www.contoso.com/");

// Turn off connection keep-alives.
httpReq.KeepAlive = false;

Supporting Additional Protocols
The .NET Framework provides protocol-specific WebRequest and
WebResponse descendants for URIs that begin with http:, https:, and file:.
The programmable pluggable protocols of System.Net allow applications to
provide access through other protocols. To support additional protocols, you
should implement protocol-specific descendants of WebRequest and
WebResponse and register the descendant’s constructor with the
WebRequest.RegisterPrefix method.
For more information about supporting additional protocols, see the .NET
Framework Software Development Kit (SDK) documentation.
10 Module 11: Internet Access


Invoking a WebRequest
!
Request Is Made by Calling the GetResponse Method
"
Cast to access HTTP-specific features
WebResponse resp = req.GetResponse();
WebResponse resp = req.GetResponse();
HttpWebResponse httpResp =
(HttpWebResponse)httpReq.GetResponse();
//Get the HTTP content length returned by the server.
String contentLength =
httpResp.ContentLength.ToString();
HttpWebResponse httpResp =
(HttpWebResponse)httpReq.GetResponse();
//Get the HTTP content length returned by the server.
String contentLength =
httpResp.ContentLength.ToString();

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
After creating the WebRequest, you invoke the request for the Internet
resource by calling the GetResponse method on the WebRequest instance.
The GetResponse method is responsible for:
!
Constructing the protocol-specific request from the properties of the
WebRequest instance.
!
Making the TCP or UDP socket connection to the server.
!
Sending the request.

The GetResponse method returns an instance that is derived from
WebResponse that matches the instance that is derived from WebRequest, as
in the following example:
WebResponse resp = req.GetResponse();

The WebResponse class is also an abstract class that defines properties and
methods that are available to all applications that use pluggable protocols.
WebResponse descendents are responsible for implementing these properties
and methods for the underlying protocol.
For example, the HttpWebResponse class implements the WebResponse class
for the HTTP protocol. If you need to access the HTTP protocol-specific
properties of the response, you can typecast WebResponse objects to
HttpWebResponse, as in the following example:
HttpWebResponse httpResp =
(HttpWebResponse)httpReq.GetResponse();

//Get the HTTP content length returned by the server.
String contentLength = httpResp.ContentLength.ToString();

Topic Objective
To explain how to invoke the
request for an Internet
resource by calling the
GetResponse method on
the WebRequest instance.
Lead-in
After creating the
WebRequest, you invoke
the request for the Internet
resource by calling the
GetResponse method on
the WebRequest instance.

Không có nhận xét nào:

Đăng nhận xét