< Chap 15 TOC: Some advancement in the .NET framework Networking | Main | VB .NET & C++/CLI Network Data Collection Examples >


 

 

Chapter 15 Part 1:

Advancements in .NET Framework Networking

 

 

What do we have in this chapter 15 Part 1?

  1. The FTP Protocol and Message Queuing (MSMQ)

  2. Protocol Independence

  3. Network Awareness

  4. Collecting and Displaying the Network Info C# Program Example

  5. Adding References

  6. Build and Run the C# Project

 

This chapter will talk about the current and possible emerging trends in the world of distributed application development and related enhancements in the Microsoft .NET Framework. Reviewing these trends will illuminate steps that you can take today as you architect solutions to ensure they will be poised to take advantage of the new technology. In most cases, the .NET Framework already provides significant support for each of these trends. However, it is useful to recognize where the key focal points will be in the future.

 

The FTP Protocol and Message Queuing (MSMQ)

 

Customers of the .NET Framework versions 1 and 1.1 said they wanted the framework to support the File Transfer Protocol (FTP). In response to this feedback, FTP support was already available from the framework’s newer release which can be found in the following links:

 

  1. The WebRequestMethods.Ftp Class
  2. FtpWebRequest Class

 

Third party options are already available before this as an example can be found at the following sites:

 

  1. First, sample FTP implementations are available free of charge on public user groups, such as in MSDN Code Sample.
  2. Second, a number of third parties provide FTP solutions for the .NET Framework. Specific examples include nSoftware (www.nsoftware.com), Dart Communications (www.dart.com) and Chilkat.

 

Another way to add asynchronous processing to your Microsoft .NET application is using (Microsoft) Message Queuing (MSMQ) which is a typical implementation for Microsoft email and messaging systems. You can use the System.Messaging classes provided by the .NET Framework to work with MSMQ and at the same time can add asynchronous workflow to your application. Have a peek at the MSMQ simple example using VB on how to access Message Queues.

 

Protocol Independence

 

As discussed in Chapter 11, a specific protocol such as HTTP is not the optimal tool for every situation faced by today’s distributed applications. Maintaining protocol independence while still achieving interoperability is an increasingly important and achievable aspect to distributed application development.

Each protocol in use on the network today comes with its own set of strengths and weaknesses. Applications with the agility to switch from one transport to another will be in demand as user needs evolve. To take advantage of this trend, the core functionality of your applications should be independent of the underlying transport protocol. The .NET Framework helps developers design applications with greater protocol independence by providing common I/O models, such as the System.IO.Stream type. Going forward, you can expect to see further enhancements in the System.Net namespace and in other areas of the .NET Framework, such as Web services that support this trend.

 

Network Awareness

 

Although applications have had to interact with the network for many years, few have done a good job of staying aware of the network and dynamically changing their behavior to best suit current conditions. For example, today’s smart client applications are considered advanced if they simply support an online/offline mode. While being aware of online/offline status is an important part of unity with the network, applications can do much more. For example, an application that is aware of network characteristics, such as connection speed and throughput between local and remote endpoints, can provide a much richer experience than an application that simply goes “offline” when the network is slow. Imagine an application that is written in such a way that it works with minimal reliance on the network in low bandwidth conditions, but automatically senses increases in speed and throughput and reacts accordingly to improve the user experience. What’s more, this application could use network “fingerprinting” techniques to recognize different network configurations and remember which services were available the last time it ran on them or even associate a geographical location with that network.

Developers building .NET applications should be aware of the potential for network awareness and plan for it in an application. For example, you should consider factoring protocol logic and business logic into the application in such a way that the network intensive protocols can be used in high bandwidth cases, but the application can have a fallback in lower bandwidth scenarios. If your application is rich in information that comes across a network, consider factoring the way your application uses the network into different profiles or buckets and providing scaled-down experiences for your users. A scaled-down experience is preferable to having a user wrestle with an application that was designed for a LAN from a dial-up connection. Today, the .NET Framework enables applications to address network elements such as connection speed and network connectivity through the System.Management classes. The following code sample demonstrates how to determine whether a machine has one or more valid IP addresses assigned, which can indicate the machine’s network connectivity:

 

 

 

 

C#

using System;

using System.Management;

 

/// <summary>

/// This sample demonstrates the use of System.Management

/// to detect whether one or more valid network

/// connections are associated with the machine.

/// </summary>

class NetworkInformation

{

    [STAThread]

    static void Main(string[ ] args)

    {

        // Check to see whether one or more connections

        // are assigned to this machine (based on IP address)

        int numConnections = GetNumAvailableConnections();

        if(numConnections > 0)

        {

            if(numConnections == 1)

            {

                Console.WriteLine("1 connection on this machine with ");

                Console.WriteLine("at least 1 valid IP address assigned");

            }

            else

            {

                Console.WriteLine(numConnections + " connections on this ");

                Console.WriteLine("machine with at least 1 valid IP address");

            }

        }

        else

        {

            Console.WriteLine("No cards found with a valid IP address");

        }

    }

 

    public static int GetNumAvailableConnections()

    {

        // Query for the list of network adapters on the machine

        // For more detail on this type you can search

        // http://msdn.microsoft.com for "Win32_NetworkAdapterConfiguration"

        SelectQuery NAQuery = new SelectQuery("select * from " +

            "Win32_NetworkAdapterConfiguration");

 

        ManagementObjectSearcher NASearcher = new ManagementObjectSearcher(NAQuery);

 

        int availableConnections = 0;

 

        try

        {

            // Loop through each adapter returned from the query

            foreach (ManagementObject enumerate in NASearcher.Get())

            {

                // Find out whether IP is enabled on this adapter

                bool  IPEnabled = (bool)enumerate["IPEnabled"];

                // Get the adapter description

                Console.WriteLine((string)enumerate["Caption"]);

                // If the IP is enabled check for non-zero IP

                if(IPEnabled)

                {

                    string[ ] IPAddress = (string[ ])enumerate["IPAddress"];

 

                    Console.WriteLine("IP Address: " + IPAddress[0]);

                    if(IPAddress[0] != "0.0.0.0")

                    {

                        availableConnections++;

                    }

                }

                Console.WriteLine();

            }

        }

        catch(Exception e)

        {

            Console.WriteLine(e.ToString());

        }

        return availableConnections;

    }

}

Visual Basic .NET

Imports System

Imports System.Management

'This sample demonstrates the use of System.Management

'to detect whether one or more valid network

'connections are associated with the machine.

Module NetworkInformation

    Sub Main()

        ' Check to see whether one or more connections

        ' are assigned to this machine (based on IP address)

        Dim numConnections As Integer

        numConnections = GetNumAvailableConnections()

 

        If numConnections > 0 Then

            If (numConnections = 1) Then

                Console.WriteLine("1 connection on this machine with")

                Console.WriteLine("at least 1 valid IP address assigned")

            Else

                Console.WriteLine(numConnections & " connections on this ")

                Console.WriteLine("machine with at least 1 valid IP address")

            End If

        Else

            Console.WriteLine("No cards found with a valid IP address")

        End If

    End Sub

    Function GetNumAvailableConnections() As Integer

        ' Query for the list of network adapters on the machine

        ' For more detail on this type you can search

        ' http://msdn.microsoft.com for "Win32_NetworkAdapterConfiguration"

        Dim NAQuery As SelectQuery

        NAQuery = New SelectQuery("select * from " & _

            "Win32_NetworkAdapterConfiguration")

 

        Dim NASearcher As ManagementObjectSearcher

        NASearcher = New ManagementObjectSearcher(NAQuery)

        Dim availableConnections As Integer

 

        Try

            ' Loop through each adapter returned from the query

            Dim enumerate As ManagementObject

 

            For Each enumerate In NASearcher.Get()

                ' Find out whether IP is enabled on this adapter

                Dim IPEnabled As Boolean

                IPEnabled = enumerate("IPEnabled")

                ' Get the adapter description

                Console.WriteLine(enumerate("Caption"))

                ' If IP is enabled then check for a non-zero IP

                If IPEnabled Then

                    Dim IPAddress As String()

                    IPAddress = enumerate("IPAddress")

                    Console.WriteLine("IP Address: " & IPAddress(0))

                    If IPAddress(0) <> "0.0.0.0" Then

                        availableConnections = availableConnections + 1

                    End If

                End If

                Console.WriteLine()

            Next

        Catch e As Exception

            Console.WriteLine(e.ToString())

        End Try

        Return availableConnections

    End Function

End Module

This code uses the System.Management classes to query the system for installed network adapters and then inspect each adapter for associated IP addresses. This behavior is expected to be improved with richer and easier to find information in future releases of the .NET Framework. The following section presents the complete C#, VB .NET and C++/CLI program examples.

 

 

 

 

Collecting and Displaying the Network Info C# Program Example

 

Create a new C# console application. You can use the solution and project names as shown in the following screenshot.

 

Collecting and Displaying the Network Info C# Program Example: creating new C# console application project

 

Add/edit code as given below.

 

using System;

using System.Management;

 

namespace NetworkConnectionCS

{

    /// <summary>

    /// This sample demonstrates the use of System.Management

    /// to detect whether or not one or more valid network

    /// connections is associated with the machine.

    /// </summary>

    class NetworkInformation

    {

        [STAThread]

        static void Main(string[ ] args)

        {

            // Check to see if there is one or more connections

            // assigned to this machine (based on IP address)

            int numConnections = GetNumAvailableConnections();

            if (numConnections > 0)

            {

                if (numConnections == 1)

                {

                    Console.WriteLine("1 connection on this machine with ");

                    Console.WriteLine("at least 1 valid IP address assigned");

                }

                else

                {

                    Console.WriteLine(numConnections + " connections on this ");

                    Console.WriteLine("machine with at least 1 valid IP address");

                }

            }

            else

            {

                Console.WriteLine("No cards found with a valid IP address");

            }

        }

 

        public static int GetNumAvailableConnections()

        {

            // Query for the list of network adapters on the machine

            // Note for more detail on this type you can search

            // for "Win32_NetworkAdapterConfiguration":

            // http://msdn.microsoft.com/en-us/library/aa394217(VS.85).aspx

            SelectQuery NAQuery = new SelectQuery("select * from Win32_NetworkAdapterConfiguration");

            ManagementObjectSearcher NASearcher = new ManagementObjectSearcher(NAQuery);

            int availableConnections = 0;

 

            try

            {

                // Loop through each adapter returned from the query

                foreach (ManagementObject enumerate in NASearcher.Get())

                {

                    // Find out if IP is enabled on this adapter

                    bool IPEnabled = (bool)enumerate["IPEnabled"];

                    // Get the adapter description

                    Console.WriteLine((string)enumerate["Caption"]);

                    // If the IP is enabled check for non-zero IP

                    if (IPEnabled)

                    {

                        string[ ] IPAddress = (string[ ])enumerate["IPAddress"];

                        Console.WriteLine("IP Address: " + IPAddress[0]);

                        if (IPAddress[0] != "0.0.0.0")

                        {

                            availableConnections++;

                        }

                    }

                    Console.WriteLine();

                }

            }

            catch (Exception e)

            {

                Console.WriteLine(e.ToString());

            }

            return availableConnections;

        }

    }

}

 

If the System.Management namespaces cannot resolve the following types, we need to add the reference manually.

 

Collecting and Displaying the Network Info C# Program Example: the unresolved types from the System.Management namespaces

 

Adding References

 

Invoke the Add Reference page.

 

Collecting and Displaying the Network Info C# Program Example: invoking the Add Reference page

 

Then, from the .NET page, find and select the System.Management component and click OK.

 

Collecting and Displaying the Network Info C# Program Example: delecting the System.Management .NET component

 

Build and Run the C# Project

 

Next, build the project and make sure there is no error.

 

Collecting and Displaying the Network Info C# Program Example: building the project

 

Then, run the project without debugging.

 

Collecting and Displaying the Network Info C# Program Example: running the project without debugging

 

The following screenshot shows a sample output.

 

Collecting and Displaying the Network Info C# Program Example: a sample console output

 


< Chap 15 TOC: Some advancement in the .NET framework Networking | Main | VB .NET & C++/CLI Network Data Collection Examples >