needing to list servers for a project I was working on, Marty Cerisano's article A C# Server Drop-down Control seemed perfect. Downloading and attempting to compile left me a little frustrated. The original code appears to be developed under a BETA version of Visual Studio .NET and would not compile under the released version. (MarshalAs.LPVoid was not defined, this has been updated in his May 30, 2002 release of his code).
i decided to rewrite the code and make it a bit more modular. I separated the code to enumerate the servers to it's own class. I removed the use of pointers and removed the use of the unsafe block.
the tricky part I found was removing the pointer use. Calculating the offset in the structure and using the Marshal.PtrToStructure() method to get correct data took some digging into the class library documentation.
there are three classes and an enumeration. They are:
ServerType - Enumeration listing possible server types, such as SQL Server or Terminal Server. ServerTypes can be logically OR'ed, i.e. the ServerType has the Flags attribute.
Servers - Collection of servers of specified type. Implements IEnumerable which allows foreach to be used.
ServerEnumerator - Enumerator to loop over the list of servers.
ServerComboBox - Example ComboBox control that uses the other classes. AutoRefresh property will not automatically rescan the network. Setting AutoRefresh to true will cause any changes to the ServerType property to automatically call the Refresh() method. This is not an auto update setting. using System;
using NetworkManagement;
//
// List all the SQL Server database to the
// console (using foreach)
//
Servers servers = new Servers( ServerType.SQLServer );
foreach (String name in servers)
{
Console.WriteLine(name);
}
//
// List all the Domains to the console.
//
Servers servers = new Servers( ServerType.DomainEnum );
IEnumerator i = servers.GetEnumerator()
while ( i.MoveNext() )
{
string domainName = (string) i.Current;
Console.WriteLine(domainName);
}
using System;
using NetworkManagement;
public class ServerComboBoxForm : System.Windows.Forms.Form
{
private ServerComboBox sCombo1;
private void InitializeComponent()
{
sCombo1 = new NetworkManagement.ServerComboBox();
sCombo1.AutoRefresh = true; // turn force changes on
sCombo1.ServerType = ServerType.DomainEnum;
}
// other code omitted...
}
this is a simple example of calling Windows API functions. Included is a sample application that demonstrates using the classes.
ServerType enumeration to have CLR base type of long. Should fix problem VB.NET users were experiencing.
|
Click here to view Phil Bolduc's online profile. |