1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional ASP.NET 3.5 in C# and Visual Basic Part 123 pps

10 105 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 309,99 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

#region IHttpModule Members void IHttpModule.Dispose { throw new Exception"The method or operation is not implemented."; } void IHttpModule.InitHttpApplication context { context.BeginReq

Trang 1

#region IHttpModule Members void IHttpModule.Dispose() {

throw new Exception("The method or operation is not implemented.");

} void IHttpModule.Init(HttpApplication context) {

context.BeginRequest += new EventHandler(context_BeginRequest);

} void context_BeginRequest(object sender, EventArgs e) {

HttpApplication app = (HttpApplication)sender;

//Get the Accept-Encoding HTTP header from the request

//The requesting browser sends this header which we will use // to determine if it supports compression, and if so, what type // of compression algorithm it supports

string encodings = app.Request.Headers.Get("Accept-Encoding");

if (encodings == null) return;

Stream s = app.Response.Filter;

encodings = encodings.ToLower();

if (encodings.Contains("gzip")) {

app.Response.Filter = new GZipStream(s, CompressionMode.Compress);

app.Response.AppendHeader("Content-Encoding", "gzip");

app.Context.Trace.Warn("GZIP Compression on");

} else { app.Response.Filter =

new DeflateStream(s, CompressionMode.Compress);

app.Response.AppendHeader("Content-Encoding", "deflate");

app.Context.Trace.Warn("Deflate Compression on");

} }

#endregion }

}

After you create and build the module, add the assembly to your Web site’sBindirectory After that’s

done, you let your Web application know that it should use theHttpModulewhen it runs Do this by

adding the module to theweb.configfile Listing 25-23 shows the nodes to add to theweb.config

system.webconfiguration section

Trang 2

Listing 25-23: Adding an HttpCompression module to the web.config

<httpModules>

<add name="HttpCompressionModule"

type="Wrox.Demo.Compression.CompressionModule, HttpCompressionModule"/>

</httpModules>

<trace enabled="true" />

Notice that one other change you are making is to enable page tracing You use this to demonstrate that the page is actually being compressed When you run the page, you should see the trace output shown

in Figure 25-14 Notice a new entry under the trace information showing that the GZip compression has been enabled on this page

Figure 25-14

Wor king with Serial Por ts

Also introduced in the NET 2.0 Framework was theSystem.IO.Portsnamespace This namespace

contains classes that enable you to work with and communicate through serial ports

.NET provides aSerialPortcomponent that you can add to the Component Designer of your Web page Adding this component enables your application to communicate via the serial port Listing 25-24 shows how to write some text to the serial port

Trang 3

Listing 25-24: Writing text to the serial port

VB

<script runat="server">

Dim SerialPort1 As New System.IO.Ports.SerialPort()

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

Me.SerialPort1.PortName = "COM1"

If (Not Me.SerialPort1.IsOpen()) Then Me.SerialPort1.Open()

End If Me.SerialPort1.Write("Hello World") Me.SerialPort1.Close()

End Sub

</script>

C#

<script runat="server">

System.IO.Ports.SerialPort SerialPort1 = new System.IO.Ports.SerialPort();

protected void Page_Load(object sender, EventArgs e)

{

this.SerialPort1.PortName = "COM1";

if (!this.SerialPort1.IsOpen) {

this.SerialPort1.Open();

} this.SerialPort1.Write("Hello World");

this.SerialPort1.Close();

}

</script>

This code simply attempts to open the serial port COM1 and write a bit of text TheSerialPort

component gives you control over most aspects of the serial port, including baud rate, parity, and

stop bits

Networ k Communications

Finally, this chapter takes you beyond your own systems and talks about how you can use the NET

Framework to communicate with other systems The NET Framework contains a rich set of classes in

theSystem.Netnamespace that allow you to communicate over a network using a variety of protocols

and communications layers You can perform all types of actions, from DNS resolution to programmatic

HTTP Posts to sending e-mail through SMTP

Trang 4

WebRequest and WebResponse

The first series of classes to discuss are theWebRequestandWebResponseclasses You can use these two classes to develop applications that can make a request to a Uniform Resource Identifier (URI) and receive

a response from that resource The NET Framework provides three derivatives of theWebRequestand

WebResponseclasses, each designed to communicate to a specific type of end point via HTTP, FTP, and file:// protocols

HttpWebRequest and HttpWebResponse

The first pair of classes are theHttpWebRequestandHttpWebResponseclasses As you can probably guess based on their names, these two classes are designed to communicate using the HTTP protocol Perhaps the most famous use of theHttpWebRequestandHttpWebResponseclasses is to write applications that

can make requests to other Web pages via HTTP and parse the resulting text to extract data This is

known as screen scraping.

For an example of using theHttpWebRequestandHttpWebResponseclasses to screen scrape, you can

use the following code to build a Web page that will serve as a simple Web browser You also learn

how another Web page can be displayed inside of yours using anHttpWebRequest In this example, you scrape the wrox.com home page and display it in a panel on your Web page Listing 25-25 shows the

code

Listing 25-25: Using an HttpWebRequest to retrieve a Web page

VB

<%@ Page Language="VB" %>

<%@ Import Namespace=System.IO %>

<%@ Import Namespace=System.Net %>

<script runat="server">

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

Dim uri As New Uri("http://www.wrox.com/")

If (uri.Scheme = uri.UriSchemeHttp) Then Dim request As HttpWebRequest = HttpWebRequest.Create(uri) request.Method = WebRequestMethods.Http.Get

Dim response As HttpWebResponse = request.GetResponse() Dim reader As New StreamReader(response.GetResponseStream()) Dim tmp As String = reader.ReadToEnd()

response.Close() Me.Panel1.GroupingText = tmp End If

End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

Continued

Trang 5

<p>This is the wrox.com website:</p>

<asp:Panel ID="Panel1" runat="server"

Height="355px" Width="480px" ScrollBars=Auto>

</asp:Panel>

</div>

</form>

</body>

</html>

C#

<script runat="server">

protected void Page_Load(object sender, EventArgs e)

{

Uri uri = new Uri("http://www.wrox.com/");

if (uri.Scheme == Uri.UriSchemeHttp) {

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create( uri );

request.Method = WebRequestMethods.Http.Get;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

StreamReader reader = new StreamReader(response.GetResponseStream());

string tmp = reader.ReadToEnd();

response.Close();

this.Panel1.GroupingText = tmp;

} }

</script>

Figure 25-15 shows what the Web page look likes when you execute the code in Listing 25-25 The

Http-WebRequestto the Wrox.com home page returns a string containing the scraped HTML The sample

assigns the value of this string to theGroupingTextproperty of the Panel control When the final page is

rendered, the browser renders the HTML that was scraped as literal content on the page

One other use of theHttpWebRequestandHttpWebResponseclasses is to programmatically post data to

another Web page, as shown in Listing 25-26

Listing 25-26: Using an HttpWebRequest to post data to a remote Web page

VB

<%@ Page Language="VB" %>

<%@ Import Namespace=System.IO %>

<%@ Import Namespace=System.Net %>

<script runat="server">

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

Dim uri As New Uri("http://www.amazon.com/" & _

"exec/obidos/search-handle-form/102-5194535-6807312") Dim data As String = "field-keywords=Professional ASP.NET 3.5"

If (uri.Scheme = uri.UriSchemeHttp) Then Dim request As HttpWebRequest = HttpWebRequest.Create(uri)

Continued

Trang 6

request.Method = WebRequestMethods.Http.Post

request.ContentLength = data.Length

request.ContentType = "application/x-www-form-urlencoded"

Dim writer As New StreamWriter(request.GetRequestStream())

writer.Write(data)

writer.Close()

Dim response As HttpWebResponse = request.GetResponse()

Dim reader As New StreamReader(response.GetResponseStream())

Dim tmp As String = reader.ReadToEnd()

response.Close()

Me.Panel1.GroupingText = tmp

End If

End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Panel ID="Panel1" runat="server"

Height="355px" Width="480px" ScrollBars=Auto>

</asp:Panel>

</div>

</form>

</body>

</html>

C#

<script runat="server">

protected void Page_Load(object sender, EventArgs e)

{

Uri uri = new Uri("http://www.amazon.com/" +

"exec/obidos/search-handle-form/102-5194535-6807312");

string data = "field-keywords=Professional ASP.NET 3.5";

if (uri.Scheme == Uri.UriSchemeHttp)

{

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);

request.Method = WebRequestMethods.Http.Post;

request.ContentLength = data.Length;

request.ContentType = "application/x-www-form-urlencoded";

StreamWriter writer = new StreamWriter( request.GetRequestStream() );

writer.Write(data);

writer.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Continued

Trang 7

StreamReader reader = new StreamReader(response.GetResponseStream());

string tmp = reader.ReadToEnd();

response.Close();

this.Panel1.GroupingText = tmp;

} }

</script>

Figure 25-15

You can see that the preceding code posts a search query to Amazon.com and receives the HTML as the

response As in the example shown earlier in Listing 25-25, you can simply use a Panel to display the

resulting text as HTML The results of the query are shown in Figure 25-16

FtpWebRequest and FtpWebResponse

The next pair of classes are theFtpWebRequestandFtpWebResponseclasses These two classes were

new additions to the NET 2.0 Framework, and they make it easy to execute File Transfer Protocol (FTP)

commands from your Web page Using these classes, it is now possible to implement an entire FTP client

right from your Web application Listing 25-27 shows an example of downloading a text file from the

public Microsoft.com FTP site (See Figure 25-17.)

Trang 8

Figure 25-16

Figure 25-17

Trang 9

Listing 25-27: Using an FtpWebRequest to download a file from an FTP site

VB

<%@ Page Language="VB" %>

<%@ Import Namespace=System.IO %>

<%@ Import Namespace=System.Net %>

<script runat="server">

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

Dim uri As New Uri("ftp://ftp.microsoft.com/SoftLib/ReadMe.txt")

If (uri.Scheme = uri.UriSchemeFtp) Then Dim request As FtpWebRequest = FtpWebRequest.Create(uri) request.Method = WebRequestMethods.Ftp.DownloadFile Dim response As FtpWebResponse = request.GetResponse() Dim reader As New StreamReader(response.GetResponseStream()) Dim tmp As String = reader.ReadToEnd()

response.Close() Me.Panel1.GroupingText = tmp End If

End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Using FTP from an ASP.NET webpage</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<div runat="server" id="ftpContent"

style="overflow:scroll; height: 260px; width: 450px;">

</div>

</div>

</form>

</body>

</html>

C#

<script runat="server">

protected void Page_Load(object sender, EventArgs e)

{

Uri uri = new Uri("ftp://ftp.microsoft.com/SoftLib/ReadMe.txt ");

if (uri.Scheme == Uri.UriSchemeFtp) {

FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(uri);

request.Method = WebRequestMethods.Ftp.DownloadFile;

FtpWebResponse response = (FtpWebResponse)request.GetResponse();

StreamReader reader = new StreamReader(response.GetResponseStream());

Continued

Trang 10

string tmp = reader.ReadToEnd();

response.Close();

this.Panel1.GroupingText = tmp;

} }

</script>

FileWebRequest and FileWebResponse

Next, look at theFileWebRequestandFileWebResponseclasses These classes provide a file system

implementation of the WebRequest and WebResponse classes and are designed to make it easy to transfer files using the file:// protocol, as shown in Listing 25-28

Listing 25-28: Using the FileWebRequest to write to a remote file

VB

Dim uri As New Uri("file://DEMOXP/Documents/lorum.txt")

If (uri.Scheme = uri.UriSchemeFile) Then

Dim request As System.Net.FileWebRequest = _

System.Net.FileWebRequest.Create(uri) Dim response As System.Net.FileWebResponse = request.GetResponse()

Dim reader As New System.IO.StreamReader(response.GetResponseStream())

Dim tmp As String = reader.ReadToEnd()

response.Close()

End If

C#

Uri uri = new Uri("file://DEMOXP/Documents/lorum.txt ");

if (uri.Scheme == Uri.UriSchemeFile)

{

System.Net.FileWebRequest request =

(System.Net.FileWebRequest)System.Net.FileWebRequest.Create(uri);

System.Net.FileWebResponse response =

(System.Net.FileWebResponse)request.GetResponse();

System.IO.StreamReader reader =

new System.IO.StreamReader(response.GetResponseStream());

string tmp = reader.ReadToEnd();

response.Close();

}

In this listing, we are requesting thelorum.txtfile that exists in theDocumentsfolder on the DEMOXP machine on our local network

Sending Mail

Finally, consider a feature common to many Web applications — the capability to send e-mail from a

Web page The capability to send mail was part of the 1.0 Framework and located in theSystem.Web.Mail

namespace In the 2.0 Framework, this functionality was enhanced and moved to theSystem.Net.Mail

namespace Listing 25-29 shows an example of sending an e-mail

Ngày đăng: 05/07/2014, 19:20

TỪ KHÓA LIÊN QUAN