Chapter 12. Networking and the Web

It is a rare application these days that does not have some functionality tied to the Internet. The software world is increasingly connected, and much software is expected to have some networking functionality, even if it is as simple as checking for updates to itself.

Good networking is hard, but this chapter will get you well on your way with some basics and some not-so-basics.

Resolve a Hostname to an IP Address

Solution: The System.Net namespace contains much of the functionality you’ll see in this chapter, including such basics as the IPAddress and Dns classes.

image

Here is the output from a sample run of a few common hostnames:

image

Get This Machine’s Hostname and IP Address

Solution: In addition to the solution in the previous section, all you need to do is make one additional call to get the current hostname:

image

Here is the output on my machine. Notice the IPv6 addresses in the list:

image

Ping a Machine

Solution: .NET has a ping interface that supports synchronous and asynchronous operations:

image

Note

Many networks are configured to not allow pings outside their local networks. You should handle catch PingException when using this functionality and look at the inner exception to see the specific reason a failure occurs. Look at the MSDN documentation for the Send() method for more possible exceptions.

The output is as follows:

image

Get Network Card Information

Solution: The System.Net.NetworkInformation.NetworkInterface class provides this functionality.

image

For the complete code, see the NicInfo project in the accompanying code.

Here is some sample output (for just one adaptor):

image

Create a TCP/IP Client and Server

Solution: .NET makes creating a TCP/IP client and server very easy. Let’s do the server first (see Listing 12.1). The logic is pretty easy to follow:

• Run in a loop. Inside the loop, wait for a connection.

• Once a connection is achieved, spawn a thread to handle it.

• Receive a message.

• Send a response.

• Close the connection and return from the thread.

Listing 12.1 TCP Server

image

image

image

The only way to stop this server is with Ctrl+C (which is fairly standard for console servers).

Next, the client (see Listing 12.2). Its logic is similarly easy:

• Connect to the server.

• Loop until an exit is signaled.

• Send a message.

• Read a response.

• If the response is “BYE,” signal an exit.

Listing 12.2 TCP Client

image

image

Note

Raw TCP/IP is still useful, but if you can use WCF, it is far superior and easier to develop. It’s described later in this chapter, beginning with the section “Communicate Between Processes on the Same Machine (WCF).”

Send an Email via SMTP

Solution: SMTP stands for Simple Mail Transport Protocol and is a simple, well-defined protocol for exchanging emails with an SMTP server. Thankfully, the specifics of the protocol are handled for you in the System.Net.Mail.SmtpClient class. Figure 12.1 shows an SMTP client.

Figure 12.1 It’s very easy to create a simple SMTP client with full attachment support.

image

To see a full example of a simple email program, look at the EmailClient code example for this chapter. Here is just the method for sending email:

image

Note

The MailMessage class must be disposed after you send it. I once noticed strange problems with mail not going out immediately when I neglected to do this.

Download Web Content via HTTP

Solution: The System.Net.WebClient class provides most of the functionality you will ever need, as demonstrated in the following example:

image

This is very easy to do, but DownloadFile is a synchronous method, which means it will wait until the file is done before returning. This isn’t great if you want to allow the user to do other things in the meanwhile (or to be able to cancel the transfer). For a better solution, continue to the next section.

Download Web Content Asynchronously

Solution: Here’s a rundown of how the asynchronous model works in this instance:

• Listen to events that will notify you of the download status.

• Start the download event with an -Async method.

• Do other stuff (even if it’s just listen for a button click to cancel).

• In the event handlers for the download events, respond to the download progress (or completion).

Listing 12.3 shows a portion of the code for our sample application. To run this sample, please see the WebDownloaderAsync project in this chapter’s sample code.

Listing 12.3 Asynchronous Web Downloader

image

image

image

Upload a File with FTP

Solution: FTP is an old, but ever-popular file transfer mechanism, and .NET supports it out of the box with the WebClient, which will see the “ftp://” part of the URL and internally use a FtpWebRequest to perform the communication.

image

There is also an asynchronous version of UploadFile.

Strip HTML of Tags

Solution: A common practice of analyzing web data sources when they do not provide an API for structured access is to scrape the web pages themselves. This is an imprecise process and prone to easy breakage, but sometimes still useful. One part of this process that could be useful is to remove the HTML content, leaving just the text on the page. This could also be useful in a simple web-indexing application. You can use regular expressions to accomplish this (see Chapter 8, “Regular Expressions,” for more information):

image

Embed a Web Browser in Your Application

Solution: You can use the Internet Explorer component included with .NET. In Visual Studio, it shows up under Common Controls in the Form Designer.

You can use the WebBrowser control just like you would any other control and arrange it how you want. Figure 12.3 shows an example of a simple browser.

Figure 12.3 It is quite simple to create your own web browser by using the existing functionality from Internet Explorer.

image

Listing 12.4 provides a snippet of the code that manipulates the browser control.

Listing 12.4 Custom Web Browser

image

As you can see, it’s equally easy to show your own content or anything on the Web. However, the renderer is always Internet Explorer, regardless of what you put around it (just right-click on a page to see the standard IE context menu). Keep this in mind when dealing with JavaScript, for example.

Consume an RSS Feed

Solution: An RSS feed is merely an XML file generated at regular intervals, consumed by an application that knows what to do with it. Therefore, it’s really just putting together pieces you already know: web download and XML parsing.

The accompanying source code for this chapter contains two projects: RssLib and RssReader. The following sample is from RssLib and contains some simple feed parsing code.

image

image

image

image

image

Here’s a short sample of how this library is used:

image

To see the full example, look at the RssReader application in the sample code for this chapter.

In a complete implementation, RSS can have many more fields than are presented here. See http://www.rssboard.org/rss-specification for the full specification of required and optional elements.

Produce an RSS Feed Dynamically in IIS

Solution: You already have all the pieces you need to actually create the feed: It’s merely an XML file, after all. The more important question is this: When do you generate it?

There are a few options:

• Each time content is created or updated.

• On a regular schedule (once an hour, for example).

• On each request (possibly with caching).

An example of the last option is to create a custom handler for IIS.

In a class library project, define this class:

image

image

To use this in a web project, you must modify the web project’s web.config to reference it:

image

Now, whenever you access the project’s feed.xml file via a web browser, the handler will intercept the request and run your code to generate the RSS.

Note

Rather than generate the results on each request, you may want to implement a simple caching system—only generate if the results haven’t been generated in the last 10 minutes or so; otherwise, use the previous results.

To see the web example in action, run the WebAppForRSS project in the sample source code.

Communicate Between Processes on the Same Machine (WCF)

Solution: Use Windows Communication Foundation (WCF) with named pipe bindings.

Before WCF, you had many, many communications choices, including COM, DCOM, .NET Remoting, SOAP, TCP/IP, HTTP, named pipes, and more. WCF wraps all of those into a single framework. It separates what you communicate from how you communicate. As you’ll see, you can change from using named pipes to HTTP with only configuration changes.

WCF was designed from the ground up to unify communication technologies under a single framework. This allows your apps to be resilient to change when you need to modify how they communicate. In addition, you get an enormous amount of supporting abilities like security, auditing, extensibility, and more. If you need to use more than one protocol, you can interact with both of them through the common interface of WCF rather than worrying about protocol specifics. WCF can be in command-line apps, GUIs, Windows services, or IIS components.

WCF is a large enough topic for its own book (or series of books), but we’ll present enough to get you started.

A WCF app generally has three components:

• A service interface and implementation. This can be implemented in the same assembly as the server, but it can be useful to keep it in a separate assembly so that it can be used in multiple hosts if needed.

• A server that hosts the service implementation.

• A client that calls the server via a proxy class that implements the library’s interfaces.

This section will handle each component in turn.

Define the Service Interface

The service in this example will be a simple file server that implements three methods to retrieve directory and file data for the client. The methods are defined in an interface inside a class library that the server references and implements.

image

The attributes on the interface and methods tell WCF that these should be part of the service.

The implementation is simple:

image

See the FileServiceLib project in the accompanying source code.

Create the Server

In this case, the server is going to be a console application for simplicity. You could just as easily make it part of a Windows service or run it under IIS.

image

The configuration file is where the action is. In this case, it tells WCF to use named pipes to communicate with clients, which is ideal for processes located on the same machine.

image

See the WCFHost project in the accompanying source code.

Create the Client

To allow the client to communicate with the server seamlessly, without any knowledge of the underlying protocols, you need a proxy class, which converts normal method calls into WCF commands that eventually translate into bytes that go over the connection to the server. You could create this class by hand, but it’s easier to start up the server and run a utility to generate it for you.

The file svcutil.exe ships with the Windows SDK. It generates two files: a C# code file with the proxy class implementation, and a configuration file to use in the client.

My copy of svcutil.exe is located in C:Program Files (x86)Microsoft SDKsWindowsv7.0Ain. Your location may vary. After starting the server, I ran the following command at the console:

image

Note

Visual Studio can also generate a proxy class for you in the Add Service Reference dialog box. However, if you have multiple developers working on a project, you should stick to using svcutil.exe because Visual Studio generates additional metadata files that also need to be checked in, but these can be different on different machines, which can cause headaches. It’s better to just avoid it completely.

Note

The proxy is generated for the interface and is the same regardless of which protocol is used. This allows you to make protocol changes in the configuration without having to rebuild the application.

In this example, the client will be a WinForms app that allows you to call each service method and then shows the results.

First, add both of the svcutil.exe-generated files to the project. The app.config file looks similar to this:

image

The proxy class has the name FileServiceClient, so to instantiate and use it looks something like this:

image

image

Figure 12.4 shows the client running on the same machine as the server.

Figure 12.4 The client communicates via the server over named pipes.

image

There is a lot more to WCF, but the power of the framework should be apparent.

Communicate Between Two Machines on the Same Network (WCF)

Solution: Use WCF with a TCP/IP binding.

Starting with the result from the previous section, all you need to do is change the configuration information in both the server and the client. In fact, you could just have multiple endpoints on the server and allow clients to connect however they desire.

Here’s the server’s app.config:

image

The client’s app.config is similarly modified:

image

Note

To adequately test this on a modern operating system, you may have to create a firewall exception to allow connections to the server.

That’s it. With just a configuration change, the underlying protocol completely changes and you can communicate over the network.

Communicate over the Internet (WCF)

Solution: Use an HTTP binding with WCF.

Again, this is just a configuration change in our working WCF service.

Here’s the server’s app.config:

image

Note

To be able to enable an HTTP endpoint under Vista or Windows 7, you need to run this command as an administrator:

image

Here’s an example:

netsh http add urlacl url=http://+:8080/ user=BEN-PCBen

The client’s app.config is shown next:

image

image

Discover Services During Runtime (WCF)

Solution: In .NET 4, you can use the System.ServiceModel.Discovery.DiscoveryClient class to find all the endpoints on the network that implement the interface you’re looking for. Once you bind to an address, use of the service’s proxy class is the same as before.

Implement Discoverable Host

The code for the host is exactly the same:

image

The configuration has a few new items in it, however:

image

image

Implement Dynamic Client

To keep the code concise, this client will also be implemented as console application.

image

image

The configuration is simpler:

image

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset