Click here to Skip to main content
Licence CPOL
First Posted 6 Jun 2004
Views 98,885
Bookmarked 61 times

Network computer picker control

By | 15 Jul 2004 | Article
A Windows class library for selecting networked computers.

Introduction

A Windows class library for selecting networked computers.

Background

While having authored several Windows Forms apps, I've frequently needed to browse the network specifically for selecting a computer, however there is no managed method to accomplish this. I was inspired by Michael Potter's Finding SQL Servers on the Network article, so I decided to take it a little further and allow more granular control of the types of computers one can select.

Enumerating Computers

The first thing we have to do is define the function which will perform this task for us. NetServerEnum is located in the NetApi32.dll library.

// enumerates network computers
[DllImport("Netapi32", CharSet=CharSet.Unicode)]
private static extern int NetServerEnum( 
    string servername,        // must be null
    int level,        // 100 or 101
    out IntPtr bufptr,        // pointer to buffer receiving data
    int prefmaxlen,        // max length of returned data
    out int entriesread,    // num entries read
    out int totalentries,    // total servers + workstations
    uint servertype,        // server type filter
    [MarshalAs(UnmanagedType.LPWStr)]
    string domain,        // domain to enumerate
    IntPtr resume_handle );

The third parameter of NetServerEnum will populate a structure containing information about the computers it finds. With the exception of sv101_platform_id & sv101_type, these values are exposed as public properties in the NetworkComputers struct.

// Holds computer information
[StructLayoutAttribute(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct SERVER_INFO_101
{
    public int sv101_platform_id;
    public string sv101_name;
    public int sv101_version_major;
    public int sv101_version_minor;
    public int sv101_type;
    public string sv101_comment;
}

To get our list, we simply call one of the CompEnum constructors and pass it one of the ServerType values

ce = new CompEnum(CompEnum.ServerType.SV_TYPE_DOMAIN_CTRL | 
  CompEnum.ServerType.SV_TYPE_MASTER_BROWSER)
or it's equivalent bit-mapped value (GetServerTypeValues performs this step for us)
private void GetServerTypeValues(object sender, System.EventArgs e)
{
    int filterVal = 0x00;
    bool itemsChecked = false;
    foreach (CheckBox cb in groupBoxServerTypes.Controls)
    {
        if (cb.Checked)
        {
            filterVal += Int32.Parse((string)cb.Tag,
                System.Globalization.NumberStyles.HexNumber);
            itemsChecked = true;
        }
    }

    checkBoxAll.Enabled = !itemsChecked;
    DisplayComputerTypes((uint)filterVal);
}

Now we can enumerate through our collection of computers.

internal void DisplayComputerTypes(uint serverType)
{             
    Cursor.Current = Cursors.WaitCursor;
    lbComputers.Items.Clear();
    ce = new CompEnum(serverType, cbDomainList.SelectedItem.ToString());
    int numServer = ce.Length;
    
    if (ce.LastError.Length == 0)
    {
        IEnumerator enumerator = ce.GetEnumerator();

        int i = 0;
        while (enumerator.MoveNext())
        {
            lbComputers.Items.Add(ce[i].Name);
            i++;
        }
    }
...

Enumerating SQL Servers Using SQL-DMO

Short for SQL Server Distributed Management Objects, SQL-DMO is a far more reliable way to retrieve the names of SQL Servers on your network. My code first performs a check to see if SQL-DMO is possible, otherwise it uses the regular NetServerEnum API.

private void GetSqlServersUsingSQLDMO(object sender, System.EventArgs e)
{
    SQLDMO.Application app = new SQLDMO.ApplicationClass();
    SQLDMO.NameList nameList = app.ListAvailableSQLServers();
    string srvName = "";
    _sqlServerList = new string[nameList.Count];

    for (int i=0; i<nameList.Count; i++)
    {                
        srvName = nameList.Item(i + 1);
        _sqlServerList[i] = srvName;
    }
}

ListAvailableSQLServers() returns a NameList object that enumerates SQL Server names. From here we use the Item method of NameList to retrieve the actual server name. That's all there is to it.

Sample Usage

CompPicker cp = new CompPicker();

// show selected computer
if (cp.ShowDialog(this) == DialogResult.OK)
    MessageBox.Show(this, cp.SelectedComputerName);

Extending

To extend the library to fit your needs, simply add or remove checkboxes in the groupBoxServerTypes group box and place their tag values equal to one of the ServerType bitmap values. These values are originally defined in LMServer.h and can also be found in the CompEnum class.

Performance Issues

Performance is hampered in a non-domain environment, presumably because there is no browse master defined? The same holds true when browsing in a different domain than the one you are currently in.

Compatibility

Since the NetServerEnum WinAPI is only available for Windows NT or greater, it will not work on Win9x machines.

History

  • Version 1.0 - 06.01.2004 - First release version.
  • Version 1.1 - 07.15.2004 - Utilize SQL-DMO for enumerating SQL Servers, if available.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Marc Merritt

Technical Lead
Motorcycle Road Racing Forums
United States United States

Member

Follow on Twitter Follow on Twitter
I live in southeastern Pennsylvania, USA with my lovely wife and two beautiful daughters. Life is good. My hobbies are motorcycles, motorcycles, and motorcycles.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralWorks the first couple of times then no computers are returned. Pinmemberpipipip13:38 8 Dec '09  
QuestionGet computer IP address PinmemberRadu_205:03 20 Apr '08  
GeneralRe: Get computer IP address PinmemberMarc Merritt7:35 22 Apr '08  
QuestionGetSqlServersUsingSQLDMO return only one Computer PinmemberUmer Khan21:48 30 Sep '07  
AnswerRe: GetSqlServersUsingSQLDMO return only one Computer PinmemberMarc Merritt15:08 1 Oct '07  
QuestionRe: GetSqlServersUsingSQLDMO return only one Computer PinmemberUmer Khan5:43 2 Oct '07  
GeneralError 6118 Pinmembertkotia10:11 13 Mar '07  
GeneralRe: Error 6118 PinmemberMarc Merritt16:26 28 Jun '07  
GeneralThank you very much for this article PinmemberH. S. Masud3:22 7 May '06  
GeneralRe: Thank you very much for this article PinmemberMarc Merritt14:58 7 May '06  
GeneralThank you Pinmembershawn_b17:33 4 Mar '06  
GeneralOh, it's perfect PinmemberTastoEsc23:20 24 Jan '06  
GeneralThanks PinmemberBret Williams5:17 4 May '05  
GeneralAn SQLDMO exception PinmemberRandyY16:32 11 Jan '05  
QuestionCan I implement This program in WinCE PinmemberThe illiterate20:15 29 Oct '04  
AnswerRe: Can I implement This program in WinCE PinmemberMarc Merritt2:29 5 Nov '04  
Generalcan't see xp computers Pinmemberchoiceplus10:10 27 Oct '04  
GeneralRe: can't see xp computers PinmemberMarc Merritt2:21 5 Nov '04  
GeneralRe: can't see xp computers Pinmemberchoiceplus3:00 5 Nov '04  
GeneralIt has unhandled exceptions Pinmemberjrpally9:35 30 Jun '04  
GeneralRe: It has unhandled exceptions PinmemberMarc Merritt10:25 1 Jul '04  
Generalnice PinmemberVladimir Ralev10:59 9 Jun '04  
GeneralLarge Domains Pinmembernetclectic23:52 7 Jun '04  
GeneralRe: Large Domains PinmemberMarc Merritt2:17 8 Jun '04  
GeneralEnumerating MSDE Sql Servers Pinmembervbnetuk1:50 7 Jun '04  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 16 Jul 2004
Article Copyright 2004 by Marc Merritt
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid