Presentation is loading. Please wait.

Presentation is loading. Please wait.

Module 11: Internet Access. Overview Internet Application Scenarios The WebRequest and WebResponse Model Application Protocols Handling Errors Security.

Similar presentations


Presentation on theme: "Module 11: Internet Access. Overview Internet Application Scenarios The WebRequest and WebResponse Model Application Protocols Handling Errors Security."— Presentation transcript:

1 Module 11: Internet Access

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

3 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

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

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

6 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, asciiBytes.Length, 0); // 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, asciiBytes.Length, 0);

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

8 Invoking a WebRequest Request Is Made by Calling the GetResponse Method Cast to access HTTP-specific features 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();

9 Sending Data For Requests That Send Data to the Server //... try { byte[] sendData = Encoding.ASCII.GetBytes("some data"); int sendLength = sendData.Length; HttpWebRequest httpReq = (HttpWebRequest) WebRequest.Create( "http://www.contoso.com/"); httpReq.Method = "POST"; httpReq.ContentLength = sendLength; Stream sendStream = httpReq.GetRequestStream(); sendStream.Write(sendData,0,sendLength); sendStream.Close(); } catch(Exception e) {//...} //... //... try { byte[] sendData = Encoding.ASCII.GetBytes("some data"); int sendLength = sendData.Length; HttpWebRequest httpReq = (HttpWebRequest) WebRequest.Create( "http://www.contoso.com/"); httpReq.Method = "POST"; httpReq.ContentLength = sendLength; Stream sendStream = httpReq.GetRequestStream(); sendStream.Write(sendData,0,sendLength); sendStream.Close(); } catch(Exception e) {//...} //...

10 Receiving Data Reading Response Data // Get the response stream. Stream respstrm = resp.GetResponseStream(); // Create a buffer to hold the response data. int BufferSize = 512; Byte[] Buffer = new Byte[BufferSize]; // Read the stream to access the data. int bytesRead = respstrm.Read(Buffer, 0, BufferSize); while (bytesRead > 0) { Console.Write( Encoding.ASCII.GetString(Buffer, 0, bytesRead)); bytesRead = respstrm.Read(Buffer, 0, BufferSize); } respstrm.Close(); // Get the response stream. Stream respstrm = resp.GetResponseStream(); // Create a buffer to hold the response data. int BufferSize = 512; Byte[] Buffer = new Byte[BufferSize]; // Read the stream to access the data. int bytesRead = respstrm.Read(Buffer, 0, BufferSize); while (bytesRead > 0) { Console.Write( Encoding.ASCII.GetString(Buffer, 0, bytesRead)); bytesRead = respstrm.Read(Buffer, 0, BufferSize); } respstrm.Close();

11 Using the WebRequest and WebResponse Model //... WebRequest wReq = WebRequest.Create ("http://localhost/postinfo.html"); WebResponse wResp = wReq.GetResponse(); // Get a readable stream from the server StreamReader sr = new StreamReader( wResp.GetResponseStream(),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(); //... WebRequest wReq = WebRequest.Create ("http://localhost/postinfo.html"); WebResponse wResp = wReq.GetResponse(); // Get a readable stream from the server StreamReader sr = new StreamReader( wResp.GetResponseStream(),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(); //...

12  Application Protocols HTTP Internet Domain Name System TCP and UDP Sockets

13 HTTP Classes That Provide HTTP and HTTPS Protocols HttpWebRequest and HttpWebResponse Support Most HTTP 1.1 features HTTP Redirects Automatically if AllowAutoRedirect Property Is true (the Default) Use ServicePoint, ServicePointManager, and ConnectGroupName Classes to Manage Connections

14 Internet Domain Name System Dns Class Retrieves Data About a Host from DNS GetHostByName query for www.contoso.com Resolve query for www.contoso.com IPHostEntry hostInfo = Dns.GetHostByName("www.contoso.com"); IPHostEntry hostInfo = Dns.GetHostByName("www.contoso.com"); IPHostEntry hostInfo = Dns.Resolve("www.contoso.com"); IPHostEntry hostInfo = Dns.Resolve("www.contoso.com");

15 TCP and UDP TCP Client Connecting to a Server/Listener TCP Server/Listener Monitors Port for Clients TcpClient tcpc = new TcpClient(serverURI, 13); Stream s = tcpc.GetStream(); Byte[] read = new Byte[32]; int bytes = s.Read(read, 0, read.Length); String strInData = Encoding.ASCII.GetString(read); TcpClient tcpc = new TcpClient(serverURI, 13); Stream s = tcpc.GetStream(); Byte[] read = new Byte[32]; int bytes = s.Read(read, 0, read.Length); String strInData = Encoding.ASCII.GetString(read); TcpListener tcpl = new TcpListener(13); tcpl.Start(); while (!done){ // Accept will block until someone connects Socket s = tcpl.AcceptSocket(); //Code to handle request goes here } tcpl.Stop(); TcpListener tcpl = new TcpListener(13); tcpl.Start(); while (!done){ // Accept will block until someone connects Socket s = tcpl.AcceptSocket(); //Code to handle request goes here } tcpl.Stop();

16 Sockets System.Net Classes Are Built on System.Net.Sockets System.Net.Sockets Are Based on the WinSock32 API See Example in Student Notes

17 Handling Errors A WebException Can Be Thrown by GetResponse Has Status property, value from WebExceptionStatus If WebExceptionStatus.ProtocolError, then WebResponse contains protocol error information try { //... Create a request, get response and process stream. } catch (WebException webExcp) { Console.WriteLine("A WebException has been caught"); Console.WriteLine(webExcp.ToString()); WebExceptionStatus status = webExcp.Status; if (status == WebExceptionStatus.ProtocolError) { Console.Write( "The server returned protocol error "); Console.WriteLine(webExcp.Response.ToString()); } catch (Exception e) {// Code to catch other exceptions goes here.} try { //... Create a request, get response and process stream. } catch (WebException webExcp) { Console.WriteLine("A WebException has been caught"); Console.WriteLine(webExcp.ToString()); WebExceptionStatus status = webExcp.Status; if (status == WebExceptionStatus.ProtocolError) { Console.Write( "The server returned protocol error "); Console.WriteLine(webExcp.Response.ToString()); } catch (Exception e) {// Code to catch other exceptions goes here.}

18  Security Web Proxy Secure Sockets Layer Internet Authentication Permissions

19 Web Proxy Global Proxy for All Web Requests Proxy named webproxy using port 80 Overriding the Global Proxy Setting Request uses proxy named alternateproxy and port 80 WebProxy proxyObject = new WebProxy( "http://webproxy:80/"); GlobalProxySelection.Select = proxyObject; WebProxy proxyObject = new WebProxy( "http://webproxy:80/"); GlobalProxySelection.Select = proxyObject; WebRequest req = WebRequest.Create( "http://www.contoso.com/"); req.Proxy = new WebProxy( "http://alternateproxy:80/"); WebRequest req = WebRequest.Create( "http://www.contoso.com/"); req.Proxy = new WebProxy( "http://alternateproxy:80/");

20 Secure Sockets Layer SSL Is Used Automatically If the URI Begins with https String MyURI = "https://www.contoso.com/"; WebRequest wReq = WebRequest.Create(MyURI); String MyURI = "https://www.contoso.com/"; WebRequest wReq = WebRequest.Create(MyURI);

21 Internet Authentication.NET Supports Various Kinds of Authentication Basic, digest, negotiate, NTLM, and Kerberos authentication Users can also create their own authentication Credentials Stored in Classes NetworkCredential – for a single Internet resource CredentialCache – for multiple Internet resources Authentication Managed by the AuthenticationManager Some Schemes Allow Pre-Authentication to Save Time

22 Permissions WebPermissions Controls an application's right to request data from a URI or to serve a URI to the Internet SocketPermissions Controls an application's right to accept data on a local port or to contact applications Choose Permission Class Based on Application Use WebRequest and its descendents use WebPermissions Socket-level access uses SocketPermissions Both Classes Support Two Kinds of Permissions Accept – application can answer an incoming connection Connect – application can initiate a connection

23 Best Practices When Possible, Use WebRequest and WebResponse, Instead of Protocol-Specific Subclasses For Better Performance, Use Asynchronous Methods Tune Performance by Adjusting the Number of Connections ConnectionLimit property in the ServicePoint instance When Possible, Use TcpClient or UdpClient, Instead of Writing Directly to a Socket Use the CredentialCache Class If Credentials Are Required

24 Lab 11: Creating a DateTime Client/Server Application

25 Review Internet Application Scenarios The WebRequest and WebResponse Model Application Protocols Handling Errors Security Best Practices


Download ppt "Module 11: Internet Access. Overview Internet Application Scenarios The WebRequest and WebResponse Model Application Protocols Handling Errors Security."

Similar presentations


Ads by Google