Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#

.pdf
Скачиваний:
175
Добавлен:
12.02.2016
Размер:
16.87 Mб
Скачать

Module 11: Internet Access

iii

 

 

 

Instructor Notes

Presentation:

60 Minutes

Lab:

45 Minutes

After completing this module, students 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 HTTP, Transmission Control Protocol (TCP), User Datagram Protocol (UDP), and Socket Internet protocols.

Materials and Preparation

This section provides the materials and preparation tasks that you need to teach this module.

Required Materials

To teach this module, you need the Microsoft® PowerPoint® file 2349B_11.ppt.

Preparation Tasks

To prepare for this module, you should:

!Read all of the materials for this module.

!Complete the lab.

iv

Module 11: Internet Access

Module Strategy

Use the following strategy to present this module:

!Internet Application Scenarios

Briefly introduce examples of Internet applications that use the System.Net classes, including server-side ASP.NET applications, peer-to-peer Microsoft Windows® Forms applications that act as servers and clients to send and receive data, and client applications that periodically access the network for updates.

!The WebRequest and WebResponse Model

!

!

!

!

Introduce the WebRequest and WebResponse model. Explain how the Microsoft .NET Framework uses the Uniform Resource Identifier (URI) to identify the desired communication protocol and Internet resource. Discuss network streams as the means of obtaining and receiving Web data.

Explain how to use the WebRequest class to request data from a server, invoke the request for the Internet resource, and send data through a network stream. Discuss how the WebResponse.GetResponseStream method serves as the means of obtaining a stream that contains response data from a network resource.

Application Protocols

Discuss the HTTP, TCP, and UDP protocol support that is provided in the

.NET Framework, as well as information about using the Windows Sockets interface to implement custom protocols.

Handling Errors

Discuss how the WebRequest and WebResponse classes can throw system exceptions, such as InvalidArgumentException, and Web-specific exceptions, which are instances of WebException and thrown by the

GetResponse method. Security

Explain how an application can provide security for sending and receiving data over the Internet by using a Web proxy, Secure Sockets Layer (SSL) encryption, Internet authentication, and the NET Framework code access permissions.

Best Practices

Briefly outline the list of recommendations that will help students use the classes that are contained in System.Net more effectively.

Module 11: Internet Access

1

 

 

 

Overview

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.

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

2Module 11: Internet Access

Internet Application Scenarios

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.

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

Module 11: Internet Access

3

 

 

 

# The WebRequest and WebResponse Model

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.

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

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

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

Module 11: Internet Access

5

 

 

 

Uniform Resource Identifier

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.

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

6Module 11: Internet Access

NetworkStream Class

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.

! 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

// reading ASCII stream to string // reading ASCII stream to string Byte[] read = new Byte[32]; Byte[] read = new Byte[32];

int bytes = anASCIIStream1.Read(read, 0, read.Length); int bytes = anASCIIStream1.Read(read, 0, read.Length); string stringData = Encoding.ASCII.GetString(read); string stringData = Encoding.ASCII.GetString(read);

// writing string to ASCII stream // writing string to ASCII stream

Byte[] asciiBytes = Encoding.ASCII.GetBytes(stringData); Byte[] asciiBytes = Encoding.ASCII.GetBytes(stringData); anASCIIStream2.Write(asciiBytes, 0, asciiBytes.Length); anASCIIStream2.Write(asciiBytes, 0, asciiBytes.Length);

! Sequential Blocks Use StreamReader and StreamWriter

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

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

8Module 11: Internet Access

Creating a WebRequest

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.

! The WebRequest Encapsulates Details of Request

" Created by calling WebRequest.Create method

WebRequest req =

WebRequest req =

WebRequest.Create("http://www.contoso.com/");

WebRequest.Create("http://www.contoso.com/");

" Set any property values that are required

req.Credentials = new req.Credentials = new

NetworkCredential("username","password");

NetworkCredential("username","password");

" Cast to access protocol-specific features

HttpWebRequest httpReq = (HttpWebRequest) HttpWebRequest httpReq = (HttpWebRequest)

WebRequest.Create("http://www.contoso.com/");

WebRequest.Create("http://www.contoso.com/"); // Turn off connection keep-alives.

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

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

Соседние файлы в папке c#