root/mpich2/trunk/src/pm/smpd/wmpiconfig/wmpiconfig.cs @ 100

Revision 100, 46.2 KB (checked in by balaji, 2 years ago)

Added all components in the right places.

Line 
1#define VERIFY_USING_REGISTRY
2using System;
3using System.Drawing;
4using System.Collections;
5using System.ComponentModel;
6using System.Windows.Forms;
7using System.Data;
8using Microsoft.Win32; // registry reading/writing
9using System.Net; // Dns
10using System.IO; // File
11using System.Diagnostics; // Process
12using System.Runtime.InteropServices;
13using System.Text; // StringBuilder
14
15namespace wmpiconfig
16{
17        /// <summary>
18        /// Summary description for Form1.
19        /// </summary>
20        public class wmpiconfig : System.Windows.Forms.Form
21        {
22                private bool domain_populated;
23                private Color setting_color;
24                private Hashtable hash;
25                private string smpd;
26                private string mpiexec;
27                private System.Windows.Forms.Label host_label;
28                private System.Windows.Forms.TextBox host_textBox;
29                private System.Windows.Forms.Button get_settings_button;
30                private System.Windows.Forms.ListView list;
31                private System.Windows.Forms.Button apply_button;
32                private System.Windows.Forms.Button cancel_button;
33                private System.Windows.Forms.ListView hosts_list;
34                private System.Windows.Forms.Label domain_label;
35                private System.Windows.Forms.Button scan_button;
36                private System.Windows.Forms.ColumnHeader HostsHeader;
37                private System.Windows.Forms.ColumnHeader SettingsHeader;
38                private System.Windows.Forms.ColumnHeader DefaultHeader;
39                private System.Windows.Forms.ColumnHeader AvailableHeader;
40                private System.Windows.Forms.TextBox output_textBox;
41                private System.Windows.Forms.Button ok_button;
42                private System.Windows.Forms.ComboBox domain_comboBox;
43                private System.Windows.Forms.Button get_hosts_button;
44                private System.Windows.Forms.Button apply_all_button;
45                private System.Windows.Forms.CheckBox append_checkBox;
46                private System.Windows.Forms.CheckBox click_checkBox;
47                /// <summary>
48                /// Required designer variable.
49                /// </summary>
50                private System.ComponentModel.Container components = null;
51                private System.Windows.Forms.Button toggle_button;
52                private System.Windows.Forms.ProgressBar scan_progressBar;
53                private ToolTip tool_tip;
54                private System.Windows.Forms.Button versions_button;
55                private System.Windows.Forms.ColumnHeader VersionHeader;
56                private Color orig_background;
57
58                public wmpiconfig()
59                {
60                        //
61                        // Required for Windows Form Designer support
62                        //
63                        InitializeComponent();
64
65                        hash = new Hashtable();
66                        smpd = get_smpd();
67                        mpiexec = get_mpiexec();
68                        setting_color = Color.FromArgb(204,230,230);
69
70                        domain_comboBox.Text = Environment.UserDomainName;
71                        domain_populated = false;
72                        host_textBox.Text = Environment.MachineName.ToLower();
73                        hosts_list.Items.Add(host_textBox.Text);
74
75                        // set defaults
76                        hash["log"] = new Setting("log", "", "no", "yes,no");
77                        hash["logfile"] = new Setting("logfile", "", "none", @"filename (example: c:\temp\smpd.log)");
78                        hash["channel"] = new Setting("channel", "", "sock", "sock,mt,ssm,essm,shm,sshm,ib,auto");
79                        hash["internode_channel"] = new Setting("internode_channel", "", "ssm", "sock,mt,ssm,essm,ib");
80                        hash["phrase"] = new Setting("phrase", "", "", "");
81                        hash["hosts"] = new Setting("hosts", "", "localhost", "list of hostnames (example: foo bar bazz)");
82                        hash["max_logfile_size"] = new Setting("max_logfile_size", "", "unlimited", "max number of bytes");
83                        hash["timeout"] = new Setting("timeout", "", "infinite", "max number of seconds");
84                        //hash["map_drives"] = new Setting("map_drives", "", "no", "yes,no");
85                        hash["exitcodes"] = new Setting("exitcodes", "", "no", "yes,no");
86                        hash["port"] = new Setting("port", "", "8676", "");
87                        hash["noprompt"] = new Setting("noprompt", "", "no", "yes,no");
88                        hash["priority"] = new Setting("priority", "", "2:3", "0..4[:0..5] idle, below, normal, above, high[:idle, lowest, below, normal, above, highest]");
89                        hash["app_path"] = new Setting("app_path", "", "", "path to search for user executables");
90                        hash["plaintext"] = new Setting("plaintext", "", "no", "yes,no");
91                        hash["localonly"] = new Setting("localonly", "", "no", "yes,no");
92                        hash["nocache"] = new Setting("nocache", "", "no", "yes,no");
93                        hash["delegate"] = new Setting("delegate", "", "no", "yes,no");
94                        hash["sspi_protect"] = new Setting("sspi_protect", "", "no", "yes,no");
95
96                        UpdateHash(get_settings(host_textBox.Text));
97                        UpdateListBox();
98
99                        orig_background = list.BackColor;
100                }
101
102                /// <summary>
103                /// Clean up any resources being used.
104                /// </summary>
105                protected override void Dispose( bool disposing )
106                {
107                        if( disposing )
108                        {
109                                if (components != null) 
110                                {
111                                        components.Dispose();
112                                }
113                        }
114                        base.Dispose( disposing );
115                }
116
117                #region Windows Form Designer generated code
118                /// <summary>
119                /// Required method for Designer support - do not modify
120                /// the contents of this method with the code editor.
121                /// </summary>
122                private void InitializeComponent()
123                {
124                        System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(wmpiconfig));
125                        this.host_label = new System.Windows.Forms.Label();
126                        this.host_textBox = new System.Windows.Forms.TextBox();
127                        this.get_settings_button = new System.Windows.Forms.Button();
128                        this.list = new System.Windows.Forms.ListView();
129                        this.SettingsHeader = new System.Windows.Forms.ColumnHeader();
130                        this.DefaultHeader = new System.Windows.Forms.ColumnHeader();
131                        this.AvailableHeader = new System.Windows.Forms.ColumnHeader();
132                        this.apply_button = new System.Windows.Forms.Button();
133                        this.cancel_button = new System.Windows.Forms.Button();
134                        this.hosts_list = new System.Windows.Forms.ListView();
135                        this.HostsHeader = new System.Windows.Forms.ColumnHeader();
136                        this.domain_label = new System.Windows.Forms.Label();
137                        this.scan_button = new System.Windows.Forms.Button();
138                        this.output_textBox = new System.Windows.Forms.TextBox();
139                        this.ok_button = new System.Windows.Forms.Button();
140                        this.domain_comboBox = new System.Windows.Forms.ComboBox();
141                        this.get_hosts_button = new System.Windows.Forms.Button();
142                        this.apply_all_button = new System.Windows.Forms.Button();
143                        this.append_checkBox = new System.Windows.Forms.CheckBox();
144                        this.click_checkBox = new System.Windows.Forms.CheckBox();
145                        this.toggle_button = new System.Windows.Forms.Button();
146                        this.scan_progressBar = new System.Windows.Forms.ProgressBar();
147                        this.versions_button = new System.Windows.Forms.Button();
148                        this.VersionHeader = new System.Windows.Forms.ColumnHeader();
149                        this.SuspendLayout();
150                        //
151                        // host_label
152                        //
153                        this.host_label.Location = new System.Drawing.Point(144, 8);
154                        this.host_label.Name = "host_label";
155                        this.host_label.Size = new System.Drawing.Size(32, 16);
156                        this.host_label.TabIndex = 0;
157                        this.host_label.Text = "Host:";
158                        //
159                        // host_textBox
160                        //
161                        this.host_textBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
162                                | System.Windows.Forms.AnchorStyles.Right)));
163                        this.host_textBox.Location = new System.Drawing.Point(176, 8);
164                        this.host_textBox.Name = "host_textBox";
165                        this.host_textBox.Size = new System.Drawing.Size(312, 20);
166                        this.host_textBox.TabIndex = 1;
167                        this.host_textBox.Text = "localhost";
168                        //
169                        // get_settings_button
170                        //
171                        this.get_settings_button.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
172                        this.get_settings_button.Location = new System.Drawing.Point(408, 32);
173                        this.get_settings_button.Name = "get_settings_button";
174                        this.get_settings_button.Size = new System.Drawing.Size(80, 23);
175                        this.get_settings_button.TabIndex = 2;
176                        this.get_settings_button.Text = "&Get Settings";
177                        this.get_settings_button.Click += new System.EventHandler(this.get_settings_button_Click);
178                        //
179                        // list
180                        //
181                        this.list.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
182                                | System.Windows.Forms.AnchorStyles.Left) 
183                                | System.Windows.Forms.AnchorStyles.Right)));
184                        this.list.CheckBoxes = true;
185                        this.list.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
186                                                                                                                                                                   this.SettingsHeader,
187                                                                                                                                                                   this.DefaultHeader,
188                                                                                                                                                                   this.AvailableHeader});
189                        this.list.FullRowSelect = true;
190                        this.list.GridLines = true;
191                        this.list.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
192                        this.list.Location = new System.Drawing.Point(144, 64);
193                        this.list.Name = "list";
194                        this.list.Size = new System.Drawing.Size(344, 376);
195                        this.list.TabIndex = 3;
196                        this.list.View = System.Windows.Forms.View.Details;
197                        this.list.ItemActivate += new System.EventHandler(this.list_ItemActivate);
198                        this.list.AfterLabelEdit += new System.Windows.Forms.LabelEditEventHandler(this.list_AfterLabelEdit);
199                        this.list.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.list_ItemCheck);
200                        //
201                        // SettingsHeader
202                        //
203                        this.SettingsHeader.Text = "Settings";
204                        this.SettingsHeader.Width = 132;
205                        //
206                        // DefaultHeader
207                        //
208                        this.DefaultHeader.Text = "Default";
209                        //
210                        // AvailableHeader
211                        //
212                        this.AvailableHeader.Text = "Available options";
213                        this.AvailableHeader.Width = 122;
214                        //
215                        // apply_button
216                        //
217                        this.apply_button.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
218                        this.apply_button.Location = new System.Drawing.Point(248, 448);
219                        this.apply_button.Name = "apply_button";
220                        this.apply_button.TabIndex = 4;
221                        this.apply_button.Text = "&Apply";
222                        this.apply_button.Click += new System.EventHandler(this.apply_button_Click);
223                        //
224                        // cancel_button
225                        //
226                        this.cancel_button.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
227                        this.cancel_button.Location = new System.Drawing.Point(416, 448);
228                        this.cancel_button.Name = "cancel_button";
229                        this.cancel_button.TabIndex = 14;
230                        this.cancel_button.Text = "&Cancel";
231                        this.cancel_button.Click += new System.EventHandler(this.cancel_button_Click);
232                        //
233                        // hosts_list
234                        //
235                        this.hosts_list.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
236                                | System.Windows.Forms.AnchorStyles.Left)));
237                        this.hosts_list.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
238                                                                                                                                                                                 this.HostsHeader,
239                                                                                                                                                                                 this.VersionHeader});
240                        this.hosts_list.FullRowSelect = true;
241                        this.hosts_list.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
242                        this.hosts_list.Location = new System.Drawing.Point(8, 144);
243                        this.hosts_list.Name = "hosts_list";
244                        this.hosts_list.Size = new System.Drawing.Size(128, 328);
245                        this.hosts_list.TabIndex = 12;
246                        this.hosts_list.View = System.Windows.Forms.View.Details;
247                        this.hosts_list.KeyUp += new System.Windows.Forms.KeyEventHandler(this.hosts_list_KeyUp);
248                        this.hosts_list.SelectedIndexChanged += new System.EventHandler(this.hosts_list_SelectedIndexChanged);
249                        //
250                        // HostsHeader
251                        //
252                        this.HostsHeader.Text = "Hosts";
253                        this.HostsHeader.Width = 91;
254                        //
255                        // domain_label
256                        //
257                        this.domain_label.Location = new System.Drawing.Point(8, 8);
258                        this.domain_label.Name = "domain_label";
259                        this.domain_label.Size = new System.Drawing.Size(48, 16);
260                        this.domain_label.TabIndex = 7;
261                        this.domain_label.Text = "Domain:";
262                        //
263                        // scan_button
264                        //
265                        this.scan_button.Location = new System.Drawing.Point(8, 80);
266                        this.scan_button.Name = "scan_button";
267                        this.scan_button.Size = new System.Drawing.Size(80, 23);
268                        this.scan_button.TabIndex = 9;
269                        this.scan_button.Text = "&Scan Hosts";
270                        this.scan_button.Click += new System.EventHandler(this.scan_button_Click);
271                        //
272                        // output_textBox
273                        //
274                        this.output_textBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
275                                | System.Windows.Forms.AnchorStyles.Right)));
276                        this.output_textBox.Location = new System.Drawing.Point(144, 32);
277                        this.output_textBox.Multiline = true;
278                        this.output_textBox.Name = "output_textBox";
279                        this.output_textBox.ReadOnly = true;
280                        this.output_textBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
281                        this.output_textBox.Size = new System.Drawing.Size(256, 32);
282                        this.output_textBox.TabIndex = 15;
283                        this.output_textBox.Text = "";
284                        //
285                        // ok_button
286                        //
287                        this.ok_button.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
288                        this.ok_button.Location = new System.Drawing.Point(336, 448);
289                        this.ok_button.Name = "ok_button";
290                        this.ok_button.Size = new System.Drawing.Size(72, 23);
291                        this.ok_button.TabIndex = 13;
292                        this.ok_button.Text = "OK";
293                        this.ok_button.Click += new System.EventHandler(this.ok_button_Click);
294                        //
295                        // domain_comboBox
296                        //
297                        this.domain_comboBox.Location = new System.Drawing.Point(8, 24);
298                        this.domain_comboBox.Name = "domain_comboBox";
299                        this.domain_comboBox.Size = new System.Drawing.Size(112, 21);
300                        this.domain_comboBox.TabIndex = 6;
301                        this.domain_comboBox.DropDown += new System.EventHandler(this.domain_comboBox_DropDown);
302                        //
303                        // get_hosts_button
304                        //
305                        this.get_hosts_button.Location = new System.Drawing.Point(8, 48);
306                        this.get_hosts_button.Name = "get_hosts_button";
307                        this.get_hosts_button.TabIndex = 7;
308                        this.get_hosts_button.Text = "Get &Hosts";
309                        this.get_hosts_button.Click += new System.EventHandler(this.get_hosts_button_Click);
310                        //
311                        // apply_all_button
312                        //
313                        this.apply_all_button.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
314                        this.apply_all_button.Location = new System.Drawing.Point(168, 448);
315                        this.apply_all_button.Name = "apply_all_button";
316                        this.apply_all_button.TabIndex = 5;
317                        this.apply_all_button.Text = "Apply All";
318                        this.apply_all_button.Click += new System.EventHandler(this.apply_all_button_Click);
319                        //
320                        // append_checkBox
321                        //
322                        this.append_checkBox.Appearance = System.Windows.Forms.Appearance.Button;
323                        this.append_checkBox.Location = new System.Drawing.Point(88, 51);
324                        this.append_checkBox.Name = "append_checkBox";
325                        this.append_checkBox.Size = new System.Drawing.Size(16, 16);
326                        this.append_checkBox.TabIndex = 8;
327                        this.append_checkBox.Text = "+";
328                        //
329                        // click_checkBox
330                        //
331                        this.click_checkBox.Appearance = System.Windows.Forms.Appearance.Button;
332                        this.click_checkBox.Location = new System.Drawing.Point(96, 80);
333                        this.click_checkBox.Name = "click_checkBox";
334                        this.click_checkBox.Size = new System.Drawing.Size(40, 24);
335                        this.click_checkBox.TabIndex = 10;
336                        this.click_checkBox.Text = "click";
337                        //
338                        // toggle_button
339                        //
340                        this.toggle_button.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
341                        this.toggle_button.Location = new System.Drawing.Point(144, 448);
342                        this.toggle_button.Name = "toggle_button";
343                        this.toggle_button.Size = new System.Drawing.Size(16, 23);
344                        this.toggle_button.TabIndex = 16;
345                        this.toggle_button.Text = "^";
346                        this.toggle_button.Click += new System.EventHandler(this.toggle_button_Click);
347                        //
348                        // scan_progressBar
349                        //
350                        this.scan_progressBar.Location = new System.Drawing.Point(8, 136);
351                        this.scan_progressBar.Name = "scan_progressBar";
352                        this.scan_progressBar.Size = new System.Drawing.Size(128, 8);
353                        this.scan_progressBar.Step = 1;
354                        this.scan_progressBar.TabIndex = 17;
355                        //
356                        // versions_button
357                        //
358                        this.versions_button.Location = new System.Drawing.Point(8, 112);
359                        this.versions_button.Name = "versions_button";
360                        this.versions_button.Size = new System.Drawing.Size(128, 23);
361                        this.versions_button.TabIndex = 11;
362                        this.versions_button.Text = "Scan for &Versions";
363                        this.versions_button.Click += new System.EventHandler(this.versions_button_Click);
364                        //
365                        // VersionHeader
366                        //
367                        this.VersionHeader.Text = "Version";
368                        //
369                        // wmpiconfig
370                        //
371                        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
372                        this.ClientSize = new System.Drawing.Size(496, 483);
373                        this.Controls.Add(this.versions_button);
374                        this.Controls.Add(this.scan_progressBar);
375                        this.Controls.Add(this.toggle_button);
376                        this.Controls.Add(this.cancel_button);
377                        this.Controls.Add(this.apply_button);
378                        this.Controls.Add(this.click_checkBox);
379                        this.Controls.Add(this.append_checkBox);
380                        this.Controls.Add(this.apply_all_button);
381                        this.Controls.Add(this.get_hosts_button);
382                        this.Controls.Add(this.domain_comboBox);
383                        this.Controls.Add(this.ok_button);
384                        this.Controls.Add(this.output_textBox);
385                        this.Controls.Add(this.host_textBox);
386                        this.Controls.Add(this.scan_button);
387                        this.Controls.Add(this.domain_label);
388                        this.Controls.Add(this.hosts_list);
389                        this.Controls.Add(this.list);
390                        this.Controls.Add(this.get_settings_button);
391                        this.Controls.Add(this.host_label);
392                        this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
393                        this.MinimumSize = new System.Drawing.Size(504, 256);
394                        this.Name = "wmpiconfig";
395                        this.Text = "MPICH2 Configurable Settings";
396                        this.Load += new System.EventHandler(this.wmpiconfig_Load);
397                        this.ResumeLayout(false);
398
399                }
400                #endregion
401
402                /// <summary>
403                /// The main entry point for the application.
404                /// </summary>
405                [STAThread]
406                static void Main() 
407                {
408                        Application.Run(new wmpiconfig());
409                }
410
411                internal void PopulateDomainList()
412                {
413                        ComputerBrowser ce;
414                        string domainName = "";
415                        string currentDomain = System.Environment.UserDomainName;
416                        int index = -1;
417
418                        Cursor.Current = Cursors.WaitCursor;
419
420                        // browse for domains
421                        ce = new ComputerBrowser(ComputerBrowser.ServerType.SV_TYPE_DOMAIN_ENUM);
422                        for (int i=0; i<ce.Length; i++)
423                        {
424                                domainName = ce[i].Name;
425                                // Add the name to the dropdown list if it already doesn't exist
426                                bool found = false;
427                                foreach (string str in domain_comboBox.Items)
428                                {
429                                        if (str.ToLower() == domainName.ToLower())
430                                                found = true;
431                                }
432                                if (!found)
433                                {
434                                        domain_comboBox.Items.Add(domainName);
435                                }
436                                // Save the index of the current machine's domain so it will be selected by default
437                                if (domainName.ToLower() == currentDomain.ToLower())
438                                {
439                                        index = i;
440                                }
441                        }
442                        if (index == -1)
443                        {
444                                index = domain_comboBox.Items.Add(currentDomain);
445                        }
446                        domain_comboBox.SelectedIndex = index;
447                        Cursor.Current = Cursors.Default;
448                }
449
450                internal string [] GetHostNames()
451                {
452                        ComputerBrowser ce;
453                        string [] results = null;
454
455                        Cursor.Current = Cursors.WaitCursor;
456
457                        ce = new ComputerBrowser(domain_comboBox.Text);
458                        int numServer = ce.Length;
459
460                        if (ce.LastError.Length == 0)
461                        {
462                                IEnumerator enumerator = ce.GetEnumerator();
463
464                                // add the domain text to the dropdown list if it isn't already there
465                                bool found = false;
466                                foreach (string str in domain_comboBox.Items)
467                                {
468                                        if (str == domain_comboBox.Text)
469                                        {
470                                                found = true;
471                                        }
472                                }
473                                if (!found)
474                                {
475                                        domain_comboBox.Items.Add(domain_comboBox.Text);
476                                }
477
478                                results = new string[numServer];
479                                int i = 0;
480                                while (enumerator.MoveNext())
481                                {
482                                        results[i] = ce[i].Name;
483                                        i++;
484                                }
485                        }
486                        else
487                        {
488                                output_textBox.Text = "Error \"" + ce.LastError + "\"";
489                        }
490
491                        Cursor.Current = Cursors.Default;
492                        return results;
493                }
494
495                private void UpdateHash(Hashtable h)
496                {
497                        // update or add entries to the internal hash for each key in the input hash
498                        foreach (string str in h.Keys)
499                        {
500                                if (str != "binary") // ignore the smpd binary key because it is machine specific
501                                {
502                                        if (hash.Contains(str))
503                                        {
504                                                ((Setting)hash[str])._value = (string)h[str];
505                                        }
506                                        else
507                                        {
508                                                hash[str] = new Setting(str, (string)h[str], "", "");
509                                        }
510                                }
511                        }
512                        // remove settings from the internal hash for keys not in the input hash
513                        foreach (string str in hash.Keys)
514                        {
515                                if (!h.Contains(str))
516                                {
517                                        ((Setting)hash[str])._value = "";
518                                }
519                        }
520                }
521
522                private void UpdateListBox()
523                {
524                        int i;
525                        Hashtable h = new Hashtable();
526                        // make a hash of the settings already in the listbox
527                        for (i=0; i<list.Items.Count; i+=2)
528                        {
529                                // add the name to the hash
530                                h.Add(list.Items[i].Text, i+1);
531                                // clear the current setting
532                                list.Items[i+1].Text = "";
533                        }
534                        // update or add items to the listbox
535                        foreach (string str in hash.Keys)
536                        {
537                                if (h.Contains(str))
538                                {
539                                        i = (int)h[str];
540                                        list.Items[i].Text = ((Setting)hash[str])._value;
541                                }
542                                else
543                                {
544                                        Setting s = (Setting)hash[str];
545                                        ListViewItem item = list.Items.Add(str);
546                                        item.BackColor = setting_color;
547                                        item = list.Items.Add(s._value);
548                                        item.SubItems.Add(s._default_val);
549                                        item.SubItems.Add(s._available_values);
550                                }
551                        }
552                }
553
554                delegate void ScanHostDelegate(string host);
555                private void ScanHost(string host)
556                {
557                        bool success;
558                        string result = host + "\r\n";
559                        Hashtable h;
560                        h = get_settings(host);
561                        success = !(h.Contains("error") || h.Count == 0);
562
563                        SetHostBackgroundDelegate sd = new SetHostBackgroundDelegate(set_host_background);
564                        object [] sd_list = new object[2] { host, success };
565                        Invoke(sd, sd_list);
566                        //set_host_background(host, success);
567
568                        foreach (string key in h.Keys)
569                        {
570                                result = result + key + " = " + h[key] + "\r\n";
571                        }
572                        UpdateHostScanResultDelegate rd = new UpdateHostScanResultDelegate(UpdateHostScanResult);
573                        object [] list = new object[1] { result };
574                        Invoke(rd, list);
575                }
576
577                delegate void UpdateHostScanResultDelegate(string result);
578                private void UpdateHostScanResult(string result)
579                {
580                        output_textBox.AppendText(result);
581                        scan_progressBar.PerformStep();
582                }
583
584                delegate void ScanHostVersionDelegate(string host);
585                private void ScanHostVersion(string host)
586                {
587                        string version;
588                        version = get_version(host);
589
590                        UpdateHostScanVersionResultDelegate rd = new UpdateHostScanVersionResultDelegate(UpdateHostScanVersionResult);
591                        object [] list = new object[2] { host, version };
592                        Invoke(rd, list);
593                }
594
595                delegate void UpdateHostScanVersionResultDelegate(string host, string version);
596                private void UpdateHostScanVersionResult(string host, string version)
597                {
598                        add_host_version_to_list(host, version);
599                        scan_progressBar.PerformStep();
600                }
601
602                private void scan_button_Click(object sender, System.EventArgs e)
603                {
604                        // Get the versions
605                        versions_button_Click(sender, e);
606                        // Then get the rest of the details
607                        scan_progressBar.Value = 0;
608                        scan_progressBar.Maximum = hosts_list.Items.Count;
609                        output_textBox.Text = "";
610                        foreach (ListViewItem item in hosts_list.Items)
611                        {
612                                item.BackColor = orig_background;
613                                ScanHostDelegate shd = new ScanHostDelegate(ScanHost);
614                                shd.BeginInvoke(item.Text, null, null);
615                        }
616                }
617
618                private void VerifyEncryptedPasswordExists()
619                {
620                        try
621                        {
622                                bool popup = true;
623                                string mpiexec = get_mpiexec();
624#if VERIFY_USING_REGISTRY
625                                // Check the registry for the encrypted password
626                                // This code will have to be kept synchronized with the smpd code
627                                // The advantage of this approach is that the credentials don't have to be valid on the local host
628                                RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\MPICH");
629                                if (key != null)
630                                {
631                                        // check to see that an encrypted password for the current user exists
632                                        object obj = key.GetValue("smpdPassword");
633                                        key.Close();
634                                        if (obj != null)
635                                        {
636                                                popup = false;
637                                        }
638                                }
639#else
640                                // Or run "mpiexec -validate" and check the output for SUCCESS
641                                // This code will last longer because it doesn't rely on known information about the smpd implementation.
642                                // The disadvantage of this code is that the user credentials have to be valid on the local host.
643                                Process p1 = new Process();
644                                p1.StartInfo.RedirectStandardOutput = true;
645                                p1.StartInfo.RedirectStandardError = true;
646                                p1.StartInfo.UseShellExecute = false;
647                                p1.StartInfo.CreateNoWindow = true;
648                                p1.StartInfo.FileName = mpiexec;
649                                p1.StartInfo.Arguments = "-validate";
650                                p1.Start();
651                                string output = p1.StandardOutput.ReadToEnd() + p1.StandardError.ReadToEnd();
652                                p1.WaitForExit();
653                                p1.Close();
654                                if (output.IndexOf("SUCCESS") != -1)
655                                {
656                                        popup = false;
657                                }
658#endif
659                                if (popup)
660                                {
661                                        string wmpiregister;
662                                        wmpiregister = mpiexec.Replace("mpiexec.exe", "wmpiregister.exe");
663                                        Process p = new Process();
664                                        p.StartInfo.FileName = wmpiregister;
665                                        p.Start();
666                                        p.WaitForExit();
667                                }
668                        }
669                        catch (Exception)
670                        {
671                        }
672                }
673
674                private Hashtable get_settings(string host)
675                {
676                        string option, val;
677                        Hashtable hash = new Hashtable();
678
679                        VerifyEncryptedPasswordExists();
680
681                        Process p = new Process();
682                        p.StartInfo.FileName = mpiexec;
683                        p.StartInfo.Arguments = string.Format("-timeout 20 -noprompt -path {{SMPD_PATH}} -n 1 -host {0} smpd.exe -enumerate", host);
684                        p.StartInfo.RedirectStandardOutput = true;
685                        p.StartInfo.CreateNoWindow = true;
686                        p.StartInfo.UseShellExecute = false;
687
688                        //MessageBox.Show("About to launch: " + p.StartInfo.FileName + " " + p.StartInfo.Arguments);
689                        try
690                        {
691                                p.Start();
692                                while ((option = p.StandardOutput.ReadLine()) != null)
693                                {
694                                        val = p.StandardOutput.ReadLine();
695                                        if (val == null)
696                                                break;
697                                        hash.Add(option, val);
698                                }
699                                if (!p.WaitForExit(20000))
700                                {
701                                        p.Kill();
702                                }
703                                if (p.ExitCode != 0)
704                                {
705                                        hash.Clear();
706                                }
707                                p.Close();
708                        }
709                        catch (Exception)
710                        {
711                                hash.Clear();
712                                hash.Add("error", host + ": Unable to detect the settings");
713                        }
714                        if (hash.Count == 0)
715                        {
716                                hash.Add("error", host + ": MPICH2 not installed or unable to query the host");
717                        }
718                        return hash;
719                }
720
721                private string get_version(string host)
722                {
723                        string version = "";
724
725                        Process p = new Process();
726                        p.StartInfo.FileName = smpd;
727                        p.StartInfo.Arguments = string.Format("-version {0}", host);
728                        p.StartInfo.RedirectStandardOutput = true;
729                        p.StartInfo.CreateNoWindow = true;
730                        p.StartInfo.UseShellExecute = false;
731
732                        //MessageBox.Show("About to launch: " + p.StartInfo.FileName + " " + p.StartInfo.Arguments);
733                        try
734                        {
735                                p.Start();
736                                version = p.StandardOutput.ReadToEnd();
737                                if (!p.WaitForExit(20000))
738                                {
739                                        p.Kill();
740                                }
741                                if (p.ExitCode != 0)
742                                {
743                                        version = "";
744                                }
745                                p.Close();
746                        }
747                        catch (Exception)
748                        {
749                        }
750                        return version.Trim();
751                }
752
753                private void set_settings(string host, Hashtable h)
754                {
755                        StringBuilder str;
756                        string val;
757
758                        if (h.Keys.Count < 1)
759                        {
760                                // nothing to set
761                                return;
762                        }
763
764                        VerifyEncryptedPasswordExists();
765
766                        str = new StringBuilder("-timeout 20 -noprompt -path {SMPD_PATH} -n 1 -host ");
767                        str.AppendFormat("{0} smpd.exe", host);
768                        foreach (string key in h.Keys)
769                        {
770                                val = (string)h[key];
771                                if (val.IndexOf(' ') != -1 || val.Length == 0)
772                                {
773                                        str.AppendFormat(" -set {0} \"{1}\"", key, val);
774                                }
775                                else
776                                {
777                                        str.AppendFormat(" -set {0} {1}", key, val);
778                                }
779                        }
780                        //output_textBox.Text = str.ToString();
781
782                        Process p = new Process();
783                        p.StartInfo.FileName = mpiexec;
784                        p.StartInfo.Arguments = str.ToString();
785                        p.StartInfo.RedirectStandardOutput = true;
786                        p.StartInfo.CreateNoWindow = true;
787                        p.StartInfo.UseShellExecute = false;
788
789                        //MessageBox.Show("About to launch: " + p.StartInfo.FileName + " " + p.StartInfo.Arguments);
790                        try
791                        {
792                                output_textBox.AppendText(host + "\r\n");
793                                p.Start();
794                                while ((val = p.StandardOutput.ReadLine()) != null)
795                                {
796                                        output_textBox.AppendText(val + "\r\n");
797                                }
798                                if (!p.WaitForExit(20000))
799                                {
800                                        p.Kill();
801                                }
802                                p.Close();
803                        }
804                        catch (Exception)
805                        {
806                        }
807                }
808
809                private Hashtable get_setttings_hash()
810                {
811                        int i;
812                        Hashtable h = new Hashtable();
813                        for (i=0; i<list.Items.Count; i+=2)
814                        {
815                                if (list.Items[i].Checked)
816                                {
817                                        h[list.Items[i].Text] = list.Items[i+1].Text;
818                                }
819                        }
820                        return h;
821                }
822
823                private string get_mpiexec()
824                {
825                        string mpiexec = "";
826                        object obj;
827                        try
828                        {
829                                RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\MPICH2");
830                                if (key != null)
831                                {
832                                        obj = key.GetValue("Path");
833                                        key.Close();
834                                        if (obj != null)
835                                        {
836                                                mpiexec = obj.ToString();
837                                                if (mpiexec.EndsWith(@"\"))
838                                                {
839                                                        mpiexec = mpiexec + @"bin\mpiexec.exe";
840                                                }
841                                                else
842                                                {
843                                                        mpiexec = mpiexec + @"\bin\mpiexec.exe";
844                                                }
845                                                if (!File.Exists(mpiexec))
846                                                {
847                                                        mpiexec = "";
848                                                }
849                                        }
850                                }
851                                if (mpiexec == "")
852                                {
853                                        key = Registry.LocalMachine.OpenSubKey(@"Software\MPICH\SMPD");
854                                        if (key != null)
855                                        {
856                                                obj = key.GetValue("binary");
857                                                key.Close();
858                                                if (obj != null)
859                                                {
860                                                        mpiexec = obj.ToString().Replace("smpd.exe", "mpiexec.exe");
861                                                        if (!File.Exists(mpiexec))
862                                                        {
863                                                                mpiexec = "";
864                                                        }
865                                                }
866                                        }
867                                }
868                                if (mpiexec == "")
869                                {
870                                        mpiexec = "mpiexec.exe";
871                                }
872                                mpiexec = mpiexec.Trim();
873                                /*
874                                if (mpiexec.IndexOf(' ') != -1)
875                                {
876                                        mpiexec = "\"" + mpiexec + "\"";
877                                }
878                                */
879                        }
880                        catch (Exception)
881                        {
882                                mpiexec = "mpiexec.exe";
883                        }
884                        return mpiexec;
885                }
886
887                private string get_smpd()
888                {
889                        string smpd = "";
890                        object obj;
891                        try
892                        {
893                                RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\MPICH2");
894                                if (key != null)
895                                {
896                                        obj = key.GetValue("Path");
897                                        key.Close();
898                                        if (obj != null)
899                                        {
900                                                smpd = obj.ToString();
901                                                if (smpd.EndsWith(@"\"))
902                                                {
903                                                        smpd = smpd + @"bin\smpd.exe";
904                                                }
905                                                else
906                                                {
907                                                        smpd = smpd + @"\bin\smpd.exe";
908                                                }
909                                                if (!File.Exists(smpd))
910                                                {
911                                                        smpd = "";
912                                                }
913                                        }
914                                }
915                                if (smpd == "")
916                                {
917                                        key = Registry.LocalMachine.OpenSubKey(@"Software\MPICH\SMPD");
918                                        if (key != null)
919                                        {
920                                                obj = key.GetValue("binary");
921                                                key.Close();
922                                                if (obj != null)
923                                                {
924                                                        smpd = obj.ToString();
925                                                        if (!File.Exists(smpd))
926                                                        {
927                                                                smpd = "";
928                                                        }
929                                                }
930                                        }
931                                }
932                                if (smpd == "")
933                                {
934                                        smpd = "smpd.exe";
935                                }
936                                smpd = smpd.Trim();
937                                /*
938                                if (smpd.IndexOf(' ') != -1)
939                                {
940                                        smpd = "\"" + smpd + "\"";
941                                }
942                                */
943                        }
944                        catch (Exception)
945                        {
946                                smpd = "smpd.exe";
947                        }
948                        return smpd;
949                }
950
951                private string get_value(string key)
952                {
953                        object obj;
954                        try
955                        {
956                                RegistryKey regkey = Registry.LocalMachine.OpenSubKey(@"Software\MPICH\SMPD");
957                                if (regkey != null)
958                                {
959                                        obj = regkey.GetValue(key);
960                                        regkey.Close();
961                                        if (obj != null)
962                                        {
963                                                return obj.ToString();
964                                        }
965                                }
966                        }
967                        catch (Exception)
968                        {
969                        }
970                        return "";
971                }
972
973                private void get_settings_button_Click(object sender, System.EventArgs e)
974                {
975                        bool success;
976                        Hashtable h;
977                        Cursor.Current = Cursors.WaitCursor;
978                        output_textBox.Text = "";
979                        h = get_settings(host_textBox.Text);
980                        UpdateHash(h);
981                        UpdateListBox();
982                        add_host_to_list(host_textBox.Text);
983                        success = !(h.Contains("error") || h.Count == 0);
984                        set_host_background(host_textBox.Text, success);
985                        Cursor.Current = Cursors.Default;
986                }
987
988                private void add_host_to_list(string host)
989                {
990                        bool found = false;
991                        foreach (ListViewItem item in hosts_list.Items)
992                        {
993                                if (String.Compare(item.Text, host, true) == 0)
994                                        found = true;
995                        }
996                        if (!found)
997                        {
998                                hosts_list.Items.Add(host);
999                        }
1000                }
1001
1002                private void add_host_version_to_list(string host, string version)
1003                {
1004                        foreach (ListViewItem item in hosts_list.Items)
1005                        {
1006                                if (String.Compare(item.Text, host, true) == 0)
1007                                {
1008                                        if (item.SubItems.Count == 2)
1009                                                item.SubItems[1].Text = version;
1010                                        else
1011                                                item.SubItems.Add(version);
1012                                        return;
1013                                }
1014                        }
1015                }
1016
1017                delegate void SetHostBackgroundDelegate(string host, bool success);
1018                private void set_host_background(string host, bool success)
1019                {
1020                        foreach (ListViewItem item in hosts_list.Items)
1021                        {
1022                                if (String.Compare(item.Text, host, true) == 0)
1023                                {
1024                                        if (success)
1025                        item.BackColor = Color.GreenYellow;
1026                                        else
1027                                                item.BackColor = Color.LightGray;
1028                                }
1029                        }
1030                }
1031
1032                private void apply_button_Click(object sender, System.EventArgs e)
1033                {
1034                        Hashtable h;
1035
1036                        Cursor.Current = Cursors.WaitCursor;
1037                        output_textBox.Clear();
1038                        h = get_setttings_hash();
1039                        set_settings(host_textBox.Text, h);
1040                        Cursor.Current = Cursors.Default;
1041                }
1042
1043                private void apply_all_button_Click(object sender, System.EventArgs e)
1044                {
1045                        Hashtable h;
1046
1047                        Cursor.Current = Cursors.WaitCursor;
1048                        output_textBox.Clear();
1049                        h = get_setttings_hash();
1050                        scan_progressBar.Value = 0;
1051                        scan_progressBar.Maximum = hosts_list.Items.Count;
1052                        foreach (ListViewItem item in hosts_list.Items)
1053                        {
1054                                set_settings(item.Text, h);
1055                                scan_progressBar.PerformStep();
1056                        }
1057                        Cursor.Current = Cursors.Default;
1058                }
1059
1060                private void cancel_button_Click(object sender, System.EventArgs e)
1061                {
1062                        Close();
1063                }
1064
1065                private void list_ItemActivate(object sender, System.EventArgs e)
1066                {
1067                        int index;
1068                        if (list.SelectedIndices.Count > 0)
1069                        {
1070                                index = list.SelectedIndices[0];
1071                                if ((index & 0x1) == 0)
1072                                {
1073                                        index++;
1074                                }
1075                                // turn on and begin editing the value field
1076                                list.LabelEdit = true;
1077                                list.Items[index].BeginEdit();
1078                        }
1079                }
1080
1081                private void list_AfterLabelEdit(object sender, System.Windows.Forms.LabelEditEventArgs e)
1082                {
1083                        // turn off editing after a field has been modified to prevent the name from being modified
1084                        list.LabelEdit = false;
1085                        list.Items[e.Item].Checked = true;
1086                }
1087
1088                private void ok_button_Click(object sender, System.EventArgs e)
1089                {
1090                        Close();
1091                }
1092
1093                private void hosts_list_SelectedIndexChanged(object sender, System.EventArgs e)
1094                {
1095                        if (hosts_list.SelectedItems.Count > 0)
1096                        {
1097                                host_textBox.Text = hosts_list.SelectedItems[0].Text;
1098                                if (click_checkBox.Checked)
1099                                {
1100                                        get_settings_button_Click(null, null);
1101                                }
1102                                if (hosts_list.SelectedItems[0].BackColor == Color.LightGray)
1103                                {
1104                                        list.BackColor = Color.LightGray;
1105                                        list.Enabled = false;
1106                                }
1107                                else
1108                                {
1109                                        list.BackColor = orig_background;
1110                                        list.Enabled = true;
1111                                }
1112                        }
1113                        else
1114                        {
1115                                list.BackColor = orig_background;
1116                                list.Enabled = true;
1117                        }
1118                }
1119
1120                private void domain_comboBox_DropDown(object sender, System.EventArgs e)
1121                {
1122                        if (!domain_populated)
1123                        {
1124                                PopulateDomainList();
1125                                domain_populated = true;
1126                        }
1127                }
1128
1129                private void get_hosts_button_Click(object sender, System.EventArgs e)
1130                {
1131                        string [] hosts;
1132                        if (domain_comboBox.Text.ToLower() == Environment.MachineName.ToLower())
1133                        {
1134                                hosts = new string[1] { Environment.MachineName };
1135                        }
1136                        else
1137                        {
1138                                hosts = GetHostNames();
1139                        }
1140                        if (hosts != null)
1141                        {
1142                                if (!append_checkBox.Checked)
1143                                {
1144                                        hosts_list.Items.Clear();
1145                                }
1146                                // FIXME: This is an N^2 algorithm.
1147                                // It probably won't slow down until there are hundreds of hosts available.
1148                                // A Hashtable should be used instead.
1149                                foreach (string s in hosts)
1150                                {
1151                                        bool found = false;
1152                                        foreach (ListViewItem item in hosts_list.Items)
1153                                        {
1154                                                if (item.Text.ToLower() == s.ToLower())
1155                                                        found = true;
1156                                        }
1157                                        if (!found)
1158                                        {
1159                                                hosts_list.Items.Add(s);
1160                                        }
1161                                }
1162                        }
1163                }
1164
1165                private void wmpiconfig_Load(object sender, System.EventArgs e)
1166                {
1167                        tool_tip = new ToolTip();
1168
1169                        tool_tip.SetToolTip(append_checkBox, "Append hosts to the list");
1170                        tool_tip.SetToolTip(click_checkBox, "Get settings when a host name is selected");
1171                        tool_tip.SetToolTip(apply_button, "Apply the checked settings to the host in the host edit box");
1172                        tool_tip.SetToolTip(apply_all_button, "Apply the checked settings to all the hosts in the host list");
1173                        tool_tip.SetToolTip(scan_button, "Retrieve the settings from the hosts in the host list");
1174                        tool_tip.SetToolTip(get_hosts_button, "Get the host names from the specified domain");
1175                        tool_tip.SetToolTip(toggle_button, "Check or uncheck all the checked settings");
1176                        tool_tip.SetToolTip(versions_button, "Retrieve the version from the hosts in the host list");
1177                }
1178
1179                bool check_recursed = false;
1180                private void list_ItemCheck(object sender, System.Windows.Forms.ItemCheckEventArgs e)
1181                {
1182                        int other_index;
1183                        if (!check_recursed)
1184                        {
1185                                check_recursed = true;
1186                                // Each setting takes up two listbox entries so check and uncheck them together.
1187                                // Get the index of the sister checkbox.
1188                                other_index = ((e.Index & 0x1) == 0) ? e.Index + 1 : e.Index - 1;
1189                                list.Items[other_index].Checked = (e.NewValue == CheckState.Checked);
1190                                check_recursed = false;
1191                        }
1192                }
1193
1194                /// <summary>
1195                /// Toggle all the check boxes except the "phrase" and "port" options.
1196                /// Those options must be selected manually to make their setting more intentional.
1197                /// </summary>
1198                /// <param name="sender"></param>
1199                /// <param name="e"></param>
1200                bool checkuncheck = true;
1201                private void toggle_button_Click(object sender, System.EventArgs e)
1202                {
1203                        int index = -1;
1204                        int port_index = -1;
1205                        int error_index = -1;
1206                        bool phrase_checked = false;
1207                        bool port_checked = false;
1208                        check_recursed = true;
1209                        foreach (ListViewItem item in list.Items)
1210                        {
1211                                if (item.Text == "phrase")
1212                                {
1213                                        // save the index of the item following the phrase item to reset it afterwards
1214                                        index = item.Index + 1;
1215                                        phrase_checked = item.Checked;
1216                                }
1217                                else if (item.Text == "port")
1218                                {
1219                                        port_index = item.Index + 1;
1220                                        port_checked = item.Checked;
1221                                }
1222                                else if (item.Text == "error")
1223                                {
1224                                        error_index = item.Index + 1;
1225                                }
1226                                else
1227                                {
1228                                        item.Checked = checkuncheck; //!item.Checked;
1229                                }
1230                        }
1231                        if (index != -1)
1232                        {
1233                                // reset the phrase value
1234                                list.Items[index].Checked = phrase_checked;
1235                        }
1236                        if (port_index != -1)
1237                        {
1238                                // reset the port value
1239                                list.Items[port_index].Checked = port_checked;
1240                        }
1241                        if (error_index != -1)
1242                        {
1243                                // remove the error item check
1244                                list.Items[error_index].Checked = false;
1245                        }
1246                        checkuncheck = !checkuncheck;
1247                        toggle_button.Text = checkuncheck ? "x" : "o";
1248                        check_recursed = false;
1249                }
1250
1251                private void hosts_list_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
1252                {
1253                        if (e.KeyValue == 46) // FIXME: Is there a generic way to determine the delete key?
1254                        {
1255                                // remove the host from the list
1256                                if (hosts_list.FocusedItem != null)
1257                                {
1258                                        hosts_list.Items.Remove(hosts_list.FocusedItem);
1259                                }
1260                        }
1261                }
1262
1263                private void versions_button_Click(object sender, System.EventArgs e)
1264                {
1265                        scan_progressBar.Value = 0;
1266                        scan_progressBar.Maximum = hosts_list.Items.Count;
1267                        output_textBox.Text = "";
1268                        foreach (ListViewItem item in hosts_list.Items)
1269                        {
1270                                ScanHostVersionDelegate shd = new ScanHostVersionDelegate(ScanHostVersion);
1271                                shd.BeginInvoke(item.Text, null, null);
1272                        }
1273                }
1274        }
1275
1276        public class Setting
1277        {
1278                public string _name;
1279                public string _value;
1280                public string _default_val;
1281                public string _available_values;
1282
1283                public Setting()
1284                {
1285                }
1286
1287                public Setting(string name, string val, string default_val, string available_values)
1288                {
1289                        _name = name;
1290                        _value = val;
1291                        _default_val = default_val;
1292                        _available_values = available_values;
1293                }
1294        }
1295
1296        public class ComputerBrowser : IEnumerable, IDisposable
1297        {
1298                #region "Server type enumeration"
1299                [FlagsAttribute]
1300                public enum ServerType : uint
1301                {
1302                        SV_TYPE_WORKSTATION       = 0x00000001, // All workstations
1303                        SV_TYPE_SERVER            = 0x00000002, // All computers that have the server service running
1304                        SV_TYPE_SQLSERVER         = 0x00000004, // Any server running Microsoft SQL Server
1305                        SV_TYPE_DOMAIN_CTRL       = 0x00000008, // Primary domain controller
1306                        SV_TYPE_DOMAIN_BAKCTRL    = 0x00000010, // Backup domain controller
1307                        SV_TYPE_TIME_SOURCE       = 0x00000020, // Server running the Timesource service
1308                        SV_TYPE_AFP               = 0x00000040, // Apple File Protocol servers
1309                        SV_TYPE_NOVELL            = 0x00000080, // Novell servers
1310                        SV_TYPE_DOMAIN_MEMBER     = 0x00000100, // LAN Manager 2.x domain member
1311                        SV_TYPE_PRINTQ_SERVER     = 0x00000200, // Server sharing print queue
1312                        SV_TYPE_DIALIN_SERVER     = 0x00000400, // Server running dial-in service
1313                        SV_TYPE_XENIX_SERVER      = 0x00000800, // Xenix server
1314                        SV_TYPE_NT                = 0x00001000, // Windows NT workstation or server
1315                        SV_TYPE_WFW               = 0x00002000, // Server running Windows for Workgroups
1316                        SV_TYPE_SERVER_MFPN       = 0x00004000, // Microsoft File and Print for NetWare
1317                        SV_TYPE_SERVER_NT         = 0x00008000, // Server that is not a domain controller
1318                        SV_TYPE_POTENTIAL_BROWSER = 0x00010000, // Server that can run the browser service
1319                        SV_TYPE_BACKUP_BROWSER    = 0x00020000, // Server running a browser service as backup
1320                        SV_TYPE_MASTER_BROWSER    = 0x00040000, // Server running the master browser service
1321                        SV_TYPE_DOMAIN_MASTER     = 0x00080000, // Server running the domain master browser
1322                        SV_TYPE_WINDOWS           = 0x00400000, // Windows 95 or later
1323                        SV_TYPE_DFS               = 0x00800000, // Root of a DFS tree
1324                        SV_TYPE_TERMINALSERVER    = 0x02000000, // Terminal Server
1325                        SV_TYPE_CLUSTER_NT        = 0x01000000, // Server clusters available in the domain
1326                        SV_TYPE_CLUSTER_VS_NT     = 0x04000000, // Cluster virtual servers available in the domain
1327                        SV_TYPE_DCE               = 0x10000000, // IBM DSS (Directory and Security Services) or equivalent
1328                        SV_TYPE_ALTERNATE_XPORT   = 0x20000000, // Return list for alternate transport
1329                        SV_TYPE_LOCAL_LIST_ONLY   = 0x40000000, // Return local list only
1330                        SV_TYPE_DOMAIN_ENUM               = 0x80000000  // Lists available domains
1331                }
1332                #endregion
1333               
1334                // Server information structure
1335                [StructLayoutAttribute(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
1336                internal struct SERVER_INFO_101
1337                {
1338                        public int    sv101_platform_id;
1339                        public string sv101_name;
1340                        public int    sv101_version_major;
1341                        public int    sv101_version_minor;
1342                        public int    sv101_type;
1343                        public string sv101_comment;
1344                }
1345
1346                // enumerates network computers
1347                [DllImport("Netapi32", CharSet=CharSet.Unicode)]
1348                private static extern int NetServerEnum( 
1349                        string servername,              // must be null
1350                        int level,                              // 100 or 101
1351                        out IntPtr bufptr,              // pointer to buffer receiving data
1352                        int prefmaxlen,                 // max length of returned data
1353                        out int entriesread,    // num entries read
1354                        out int totalentries,   // total servers + workstations
1355                        uint servertype,                // server type filter
1356                        [MarshalAs(UnmanagedType.LPWStr)]
1357                        string domain,                  // domain to enumerate
1358                        IntPtr resume_handle );
1359   
1360                // Frees buffer created by NetServerEnum
1361                [DllImport("netapi32.dll")]
1362                private extern static int NetApiBufferFree(IntPtr buf);
1363
1364                // Constants
1365                private const int ERROR_ACCESS_DENIED = 5;
1366                private const int ERROR_MORE_DATA = 234;
1367                private const int ERROR_NO_SERVERS = 6118;
1368
1369                private NetworkComputers[] _computers;
1370                private string _lastError = "";
1371
1372                public ComputerBrowser(ServerType serverType, string domain) : this(UInt32.Parse(Enum.Format(typeof(ServerType), serverType, "x"), System.Globalization.NumberStyles.HexNumber), domain)
1373                {
1374                }
1375                public ComputerBrowser(ServerType serverType) : this(UInt32.Parse(Enum.Format(typeof(ServerType), serverType, "x"), System.Globalization.NumberStyles.HexNumber), null)
1376                {
1377                }
1378                public ComputerBrowser(string domainName) : this(0xFFFFFFFF, domainName)
1379                {
1380                }
1381
1382                /// <summary>
1383                /// Enumerate the hosts of type serverType in the specified domain
1384                /// </summary>
1385                /// <param name="serverType">Server type filter</param>
1386                /// <param name="domain">The domain to search for computers in</param>
1387                public ComputerBrowser(uint serverType, string domainName)
1388                {                       
1389                        int entriesread;  // number of entries actually read
1390                        int totalentries; // total visible servers and workstations
1391                        int result;               // result of the call to NetServerEnum
1392
1393                        // Pointer to buffer that receives the data
1394                        IntPtr pBuf = IntPtr.Zero;
1395                        Type svType = typeof(SERVER_INFO_101);
1396
1397                        // structure containing info about the server
1398                        SERVER_INFO_101 si;
1399
1400                        try
1401                        {
1402                                result = NetServerEnum(null, 101, out pBuf, -1, out entriesread, out totalentries, serverType, domainName, IntPtr.Zero);
1403
1404                                // Successful?
1405                                if(result != 0) 
1406                                {
1407                                        switch (result)
1408                                        {
1409                                                case ERROR_MORE_DATA:
1410                                                        _lastError = "More data is available";
1411                                                        break;
1412                                                case ERROR_ACCESS_DENIED:
1413                                                        _lastError = "Access was denied";
1414                                                        break;
1415                                                case ERROR_NO_SERVERS:
1416                                                        _lastError = "No servers available for this domain";
1417                                                        break;
1418                                                default:
1419                                                        _lastError = "Unknown error code "+result;
1420                                                        break;
1421                                        }                                       
1422                                        return;
1423                                }
1424                                else
1425                                {
1426                                        _computers = new NetworkComputers[entriesread];
1427
1428                                        int tmp = (int)pBuf;
1429                                        for(int i = 0; i < entriesread; i++ )
1430                                        {
1431                                                // fill our struct
1432                                                si = (SERVER_INFO_101)Marshal.PtrToStructure((IntPtr)tmp, svType);
1433                                                _computers[i] = new NetworkComputers(si);
1434
1435                                                // next struct
1436                                                tmp += Marshal.SizeOf(svType);
1437                                        }
1438                                }
1439                        }
1440                        finally
1441                        {
1442                                // free the buffer
1443                                NetApiBufferFree(pBuf); 
1444                                pBuf = IntPtr.Zero;
1445                        }
1446                }
1447
1448                /// <summary>
1449                /// Total computers in the collection
1450                /// </summary>
1451                public int Length
1452                {
1453                        get
1454                        {
1455                                if(_computers!=null)
1456                                {
1457                                        return _computers.Length;
1458                                }
1459                                else
1460                                {
1461                                        return 0;
1462                                }
1463                        }
1464                }
1465               
1466                /// <summary>
1467                /// Last error message
1468                /// </summary>
1469                public string LastError
1470                {
1471                        get { return _lastError; }
1472                }
1473               
1474                /// <summary>
1475                /// Obtains the enumerator for ComputerEnumerator class
1476                /// </summary>
1477                /// <returns>IEnumerator</returns>
1478                public IEnumerator GetEnumerator()
1479                {
1480                        return new ComputerEnumerator(_computers);             
1481                }
1482
1483                // cleanup
1484                public void Dispose()
1485                {
1486                        _computers = null;     
1487                }
1488   
1489                public NetworkComputers this[int item]
1490                {
1491                        get 
1492                        { 
1493                                return _computers[item];
1494                        }
1495                }
1496
1497                // holds computer info.
1498                public struct NetworkComputers
1499                {
1500                        ComputerBrowser.SERVER_INFO_101 _computerinfo;
1501                        internal NetworkComputers(ComputerBrowser.SERVER_INFO_101 info)
1502                        {
1503                                _computerinfo = info;
1504                        }
1505
1506                        /// <summary>
1507                        /// Name of computer
1508                        /// </summary>
1509                        public string Name
1510                        {
1511                                get { return _computerinfo.sv101_name; }
1512                        }
1513                        /// <summary>
1514                        /// Server comment
1515                        /// </summary>
1516                        public string Comment
1517                        {
1518                                get { return _computerinfo.sv101_comment; }
1519                        }
1520                        /// <summary>
1521                        /// Major version number of OS
1522                        /// </summary>
1523                        public int VersionMajor
1524                        {
1525                                get { return _computerinfo.sv101_version_major; }
1526                        }
1527                        /// <summary>
1528                        /// Minor version number of OS
1529                        /// </summary>
1530                        public int VersionMinor
1531                        {
1532                                get { return _computerinfo.sv101_version_minor; }
1533                        }
1534                }
1535
1536                /// <summary>
1537                /// Enumerates the collection of computers
1538                /// </summary>
1539                public class ComputerEnumerator : IEnumerator
1540                {
1541                        private NetworkComputers[] aryComputers;
1542                        private int indexer;
1543
1544                        internal ComputerEnumerator(NetworkComputers[] networkComputers)
1545                        {
1546                                aryComputers = networkComputers;
1547                                indexer = -1;
1548                        }
1549
1550                        public void Reset()
1551                        {
1552                                indexer = -1;
1553                        }
1554
1555                        public object Current
1556                        {
1557                                get
1558                                {
1559                                        return aryComputers[indexer];
1560                                }
1561                        }
1562
1563                        public bool MoveNext()
1564                        {
1565                                if (aryComputers == null)
1566                                {
1567                                        return false;
1568                                }
1569                                if (indexer < aryComputers.Length)
1570                                {
1571                                        indexer++;
1572                                }
1573                                return (!(indexer == aryComputers.Length));
1574                        }
1575                }
1576        }
1577}
Note: See TracBrowser for help on using the browser.