< FTP, MSMQ Info & C# Network Program Example | Main | C & Winsock2 Programming Tutorial >


 

 

Chapter 15 Part 2:

Advancements in .NET Framework Networking

 

 

What do we have in this chapter 15 Part 2?

  1. Collecting and Displaying the Network Info VB .NET Program Example

  2. Adding References Manually

  3. Build and Run the VB .NET Project

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

  5. Adding References Manually

  6. Build and Run the C++/CLI Project

  7. Interoperability and Web Services

  8. Security

  9. Productivity

Collecting and Displaying the Network Info VB .NET Program Example

 

Create a new VB .NET console application. You may want to use the solution and project name as shown in the following screenshot.

 

Collecting and Displaying the Network Info VB .NET Program Example: creating new VB .NET console application

 

Add/edit the code as given below.

 

Imports System

Imports System.Management

'This sample demonstrates the use of System.Managment

'to detect whether or not one or more valid network

'connections is associated with the machine.

Module NetworkInformation

 

    Sub Main()

        ' Check to see if there is one or more connections

        ' 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

        ' Note for more detail on this type you can search

        ' for "Win32_NetworkAdapterConfiguration"

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

        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 if 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

 

If the types from System.Management namespace cannot be resolved, we need to add the reference manually.

 

Collecting and Displaying the Network Info VB .NET Program Example: the unresolved types from the System.Management

 

Adding References Manually

 

In this case, invoke the VB .NET project property page.

 

Collecting and Displaying the Network Info VB .NET Program Example: invoking the VB .NET project property page

 

Then, from the References page, click the Add button.

 

Collecting and Displaying the Network Info VB .NET Program Example: the VB .NET References page of the project property page

 

Browse and select the System.Management component. Click OK to add the reference.

 

Collecting and Displaying the Network Info VB .NET Program Example: selecting the System.Management component to add a reference to the current project

 

Build and Run the VB .NET Project

 

Next, build the project.

 

Collecting and Displaying the Network Info VB .NET Program Example: building the project

 

If you encounter the following error, Re-open the VB .NET project property page.

------ Build started: Project: NetworkConnectionVB, Configuration: Debug Any CPU ------

c:\WINDOWS\Microsoft.NET\Framework\v3.5\Vbc.exe /noconfig /imports:Microsoft.VisualBasic,System,System.Collections,System.Collections.Generic,

System.Data,System.Diagnostics,System.Linq,System.Xml.Linq /optioncompare:Binary /optionexplicit+ /optionstrict:custom /nowarn:42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 /optioninfer+ /rootnamespace:NetworkConnectionVB /doc:obj\Debug\NetworkConnectionVB.xml /define:"CONFIG=\"Debug\",DEBUG=-1,TRACE=-1,_MyType=\"Console\",PLATFORM=\"AnyCPU\"" /reference:"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll","C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.DataSetExtensions.dll",

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll,

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Deployment.dll,

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll,

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Management.dll,

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll,

"C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll" /main:NetworkConnectionVB.Module1 /debug+ /debug:full /filealign:512 /out:obj\Debug\NetworkConnectionVB.exe /resource:obj\Debug\NetworkConnectionVB.Resources.resources /target:exe Module1.vb "My Project\AssemblyInfo.vb" "My Project\Application.Designer.vb" "My Project\Resources.Designer.vb" "My Project\Settings.Designer.vb"

vbc : error BC30420: 'Sub Main' was not found in 'NetworkConnectionVB.Module1'.

========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ==========

Next, in the Application page, change the Startup object: to Sub Main.

 

Collecting and Displaying the Network Info VB .NET Program Example: changing the Startup object: to Sub Main

 

Then, rebuild the project. The previous error should be vanished.

 

 

 

 

Collecting and Displaying the Network Info VB .NET Program Example: re-building the project

 

Next, run the project without debugging.

 

Collecting and Displaying the Network Info VB .NET Program Example: running the project without debugging

 

The following screenshot shows a sample output.

 

Collecting and Displaying the Network Info VB .NET Program Example: a console output sample

 

Collecting and Displaying the Network Info C++ Program Example

 

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

 

Collecting and Displaying the Network Info C++ Program Example: creating a new C++ CLR console application project

 

Add/edit the source code as given below.

 

// NetworkConnectionCP.cpp : main project file.

 

#include "stdafx.h"

 

using namespace System;

using namespace System::Management;

 

// just a normal function

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 = gcnew SelectQuery("select * from Win32_NetworkAdapterConfiguration");

     ManagementObjectSearcher^ NASearcher = gcnew ManagementObjectSearcher(NAQuery);

     int availableConnections = 0;

 

     try

     {

             // Loop through each adapter returned from the query

             for each (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)

                     {

                           array<String^>^ IPAddress = (array<String^>^)enumerate["IPAddress"];;

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

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

                           {

                                 availableConnections++;

                           }

                       }

                            Console::WriteLine();

                 }

            }

            catch(Exception^ err)

            {

                  Console::WriteLine("You've got some error: " + err->ToString());

             }

         return availableConnections;

     }

/// <summary>

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

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

/// connections is associated with the machine.

/// </summary>

[STAThread]

int main(array<System::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");

        }

   return 0;

}

 

Then, if you encounter the unresolved types from the System::Management, you need to add the reference manually.

 

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

 

Adding References Manually

 

In this case, invoke the References page (project property page).

 

Collecting and Displaying the Network Info C++ Program Example: invoking the C++ References page

 

Then, in the Framework and References page, click the Add New Reference button.

 

Collecting and Displaying the Network Info C++ Program Example: Adding the .NET references to the current project

 

As done previously for C# and VB .NET, select System.Management component from the .NET page and click OK.

 

Collecting and Displaying the Network Info C++ Program Example: selecting the System.Management namespace component from the .NET Add Reference page

 

Then, the System.Management reference should be visible in the References: column of the project property page.

 

Collecting and Displaying the Network Info C++ Program Example: the System.Management namespace should be visible in the References column of the C++ property page

 

Build and Run the C++/CLI 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.

 

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 console output sample displaying the network information for the current machine

 

'Traditionally', the Windows system programming normally uses the Win32 library (C code). The legacy still can be seen in the .NET as shown by the Win32_NetworkAdapterConfiguration class (C++). The Win32_NetworkAdapterConfiguration Windows Management Instrumentation (WMI) class represents the attributes and behaviors of a network adapter. This class includes extra properties and methods that support the management of the TCP/IP and Internetwork Packet Exchange (IPX) protocols that are independent from the network adapter. There are many C++ WMI code examples which can be browsed at WMI C++ Application Examples.

 

 

 

 

Interoperability and Web Services

 

You never know when the interoperability requirements on your application are going to change dramatically. For example, when business groups, divisions, and even companies reorganize or merge, it’s not uncommon for applications to see requirements for interoperability shift overnight. Web services are the solution for interoperability in the .NET Framework. While the other distributed application technologies discussed in this book have specific benefits, the cost of interoperability must be carefully weighed when deciding to go with a solution that might not interoperate well with disparate systems. To achieve its vision for Web services, Microsoft is expected to advance the technology in the .NET Framework so that most applications will have no need to go beyond Web services for distributed application functionality.

 

Security

 

It should come as no surprise that security will continue to play a critical role in distributed application development. Security is a top priority for distributed applications being created today, and this will not change anytime soon. Therefore, you can expect to see the .NET Framework evolves with security features at all levels of network communication, ranging from raw packets to application-level messages. Security enhancements will come in up and down the stack, but some will be more compelling than others. Applications that work to maintain a clean separation between business logic and the nuts and bolts of security will be best positioned to take advantage of the most important security features as they evolve.

 

Productivity

 

Increasing developer productivity with distributed applications was a core reason for inventing the .NET Framework. Microsoft will continue to focus on developer productivity for many years to come by simplifying key scenarios in the framework and making it easier to achieve new ones. However, keep in mind that “increased productivity” doesn’t always mean that you get a higher layer of indirection. Productivity is also achieved through extensibility where appropriate across all layers of the stack. Well-factored applications will be able to take advantage of productivity enhancements as they are introduced into the Framework.

 


< FTP, MSMQ Info & C# Network Program Example | Main | C & Winsock2 Programming Tutorial >