Tải bản đầy đủ (.pdf) (10 trang)

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

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (309.99 KB, 10 trang )

Evjen c25.tex V2 - 01/28/2008 3:42pm Page 1180
Chapter 25: File I/O and Streams
{
#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 b uild the module, add the assembly to your Web site’s
Bin
directory. After that’s
done, you let your Web application know that it should use the
HttpModule
when it runs. Do this by
adding the module to the
web.config
file. Listing 25-23 shows the nodes to add to the
web.config
system.web
configuration section.
1180
Evjen c25.tex V2 - 01/28/2008 3:42pm Page 1181
Chapter 25: File I/O and Streams
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
Working with Serial Ports
Also introduced in the .NET 2.0 Framework was the
System.IO.Ports
namespace. This namespace
contains classes that enable you to work with and communicate through serial ports.
.NET provides a
SerialPort
component 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.
1181
Evjen c25.tex V2 - 01/28/2008 3:42pm Page 1182
Chapter 25: File I/O and Streams
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. The
SerialPort
component gives you control over most aspects of the serial port, including baud rate, parity, and
stop bits.
Network 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
the
System.Net
namespace 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.
1182
Evjen c25.tex V2 - 01/28/2008 3:42pm Page 1183
Chapter 25: File I/O and Streams
WebRequest and WebResponse
The first series of classes to discuss are the
WebRequest
and
WebResponse
classes. 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 the
WebRequest
and
WebResponse
classes, 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 the
HttpWebRequest
and
HttpWebResponse
classes. 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 the
HttpWebRequest
and
HttpWebResponse
classes is t o 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 the
HttpWebRequest
and
HttpWebResponse
classes 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 an
HttpWebRequest
.Inthisexample,you
scrape the wrox.com home page a nd 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(" />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=" />>
<
head runat="server"
>
<
title

>
Untitled Page
<
/title
>
<
/head
>
<
body
>
<
form id="form1" runat="server"
>
<
div
>
Continued
1183
Evjen c25.tex V2 - 01/28/2008 3:42pm Page 1184
Chapter 25: File I/O and Streams
<
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(" />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-
WebRequest
to the Wrox.com home page returns a string containing the scraped HTML. The sample
assigns the value of this string to the
GroupingText
property of the Panel control. When the final page is
rendered, the browser renders the HTML that was scraped as literal content on the page.
Oneotheruseofthe
HttpWebRequest
and
HttpWebResponse
classes 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(" & _
"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
1184
Evjen c25.tex V2 - 01/28/2008 3:42pm Page 1185
Chapter 25: File I/O and Streams
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=" />>
<
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(" +
"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
1185
Evjen c25.tex V2 - 01/28/2008 3:42pm Page 1186
Chapter 25: File I/O and Streams
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 the
FtpWebRequest
and
FtpWebResponse
classes. 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 e xample of downloading a text file from the
public Microsoft.com FTP site. (See Figure 25-17.)

1186
Evjen c25.tex V2 - 01/28/2008 3:42pm Page 1187
Chapter 25: File I/O and Streams
Figure 25-16
Figure 25-17
1187
Evjen c25.tex V2 - 01/28/2008 3:42pm Page 1188
Chapter 25: File I/O and Streams
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(" />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=" />>
<
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(" ");
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
1188
Evjen c25.tex V2 - 01/28/2008 3:42pm Page 1189
Chapter 25: File I/O and Streams
string tmp = reader.ReadToEnd();
response.Close();
this.Panel1.GroupingText = tmp;
}
}
<
/script
>
FileWebRequest and FileWebResponse
Next, look at the
FileWebRequest
and
FileWebResponse
classes. 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 the
lorum.txt
file that exists in the
Documents
folder 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 m ail was part of the 1.0 Framework and located in the
System.Web.Mail
namespace. In the 2.0 Framework, this functionality was enhanced and moved to the
System.Net.Mail
namespace. Listing 25-29 shows an example of sending an e-mail.
1189

×