Solved

C# Get Networked Computers (SQL Servers)

Posted on 2016-09-06
2
38 Views
Last Modified: 2016-09-09
I need to update the connection string.  

1.  Is there a way to get the server's connected to?
2.  Get the SQL Servers on the servers?
0
Comment
Question by:CipherIS
2 Comments
 
LVL 20

Accepted Solution

by:
Russ Suter earned 250 total points
ID: 41786321
Yes there is and you can do it in a single line of code.
DataTable dt = Microsoft.SqlServer.Management.Smo.SmoApplication.EnumAvailableSqlServers(false);

Open in new window

You will have to add a reference reference Microsoft.Management.Smo.dll in your project. I'd also recommend running this in a separate thread as it can take several seconds to complete the operation and you don't want to lock up your UI thread while waiting.
1
 
LVL 32

Assisted Solution

by:it_saige
it_saige earned 250 total points
ID: 41786475
Here is a method that I have used before:

LocateDatabase.cs -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EE_Q28967975
{
	public partial class LocateDatabase : Form
	{
		private string fConnectionString;
		private EntityConnectionStringBuilder fEntityBuilder = new EntityConnectionStringBuilder();
		private SqlConnectionStringBuilder fSqlBuilder = new SqlConnectionStringBuilder();
		private List<SqlServerInfo> fSqlServers = SqlServerInfo.GetSqlServers();
		private readonly List<ListItem<AuthenticationMethods>> fAuthenticationMethods = new List<ListItem<AuthenticationMethods>>();
		private readonly List<ListItem<ConnectionStringType>> fConnectionStringTypes = new List<ListItem<ConnectionStringType>>();

		public LocateDatabase(string connectionString = "")
		{
			InitializeComponent();

			// Set the key length categories.
			fAuthenticationMethods = ListItem<AuthenticationMethods>.GetListItemsFromEnum(typeof(AuthenticationMethods));
			fConnectionStringTypes = ListItem<ConnectionStringType>.GetListItemsFromEnum(typeof(ConnectionStringType));

			if (!string.IsNullOrEmpty(connectionString))
			{
				try
				{
					fEntityBuilder.ConnectionString = connectionString;
				}
				catch (Exception)
				{
					// Could not set connection string, perhaps this is a standard sql connection string;
					fEntityBuilder.ProviderConnectionString = connectionString;
				}
			}
			fConnectionString = fEntityBuilder.ConnectionString;
		}

		public string ConnectionString { get { return fConnectionString; } }

		public void PromptUser()
		{
			ShowDialog();
		}

		private bool ValidateFormData()
		{
			if (string.IsNullOrEmpty(cmbServer.Text))
			{
				MessageBox.Show("The server or host name is required.", "Missing server or host name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				cmbServer.Focus();
				return false;
			}

			if (string.IsNullOrEmpty(cmbDatabase.Text))
			{
				MessageBox.Show("The database name is required.", "Missing database name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				cmbDatabase.Focus();
				return false;
			}

			if ((AuthenticationMethods)cmbAuthentication.SelectedValue == AuthenticationMethods.Sql)
			{
				if (string.IsNullOrEmpty(tbUser.Text))
				{
					MessageBox.Show("The user name is required for SQL server authentication.", "Missing user name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					tbUser.Focus();
					return false;
				}
			}
			return true;
		}

		private void OnLoad(object sender, EventArgs e)
		{
			// Set the key length categories drop down.
			cmbAuthentication.DisplayMember = "Description";
			cmbAuthentication.ValueMember = "Value";
			cmbAuthentication.DataSource = fAuthenticationMethods;
			cmbAuthentication.SelectedValue = AuthenticationMethods.Windows;

			cmbType.DisplayMember = "Description";
			cmbType.ValueMember = "Value";
			cmbType.DataSource = fConnectionStringTypes;
			cmbType.SelectedValue = ConnectionStringType.Standard;

			fSqlBuilder.ConnectionString = fEntityBuilder.ProviderConnectionString;
			fSqlBuilder.ConnectTimeout = 0;
			fSqlBuilder.Encrypt = false;
			fSqlBuilder.Pooling = true;

			cmbServer.DataSource = fSqlServers;
			var selected = (from srv in fSqlServers where srv.ToString().Equals(fSqlBuilder.DataSource) select srv).FirstOrDefault();
			cmbServer.SelectedItem = selected ?? fSqlServers.First();
			//cmbDatabase.Text = _sqlBuilder.InitialCatalog;

			if (!string.IsNullOrEmpty(fSqlBuilder.UserID))
			{
				cmbAuthentication.SelectedValue = AuthenticationMethods.Sql;
				tbUser.Text = fSqlBuilder.UserID;
			}

			if (!string.IsNullOrEmpty(fSqlBuilder.Password))
			{
				cmbAuthentication.SelectedValue = AuthenticationMethods.Sql;
				tbPassword.Text = fSqlBuilder.Password;
			}
		}

		private void OnEnter(object sender, EventArgs e)
		{
			if (sender is TextBox)
				(sender as TextBox).SelectAll();
		}

		private void OnSelectedIndexChanged(object sender, EventArgs e)
		{
			if (sender is ComboBox)
			{
				ComboBox cmb = sender as ComboBox;
				if (cmb.Equals(cmbAuthentication))
				{
					if (cmb.SelectedItem != null)
					{
						lblUser.Enabled = (AuthenticationMethods)cmb.SelectedValue == AuthenticationMethods.Sql;
						tbUser.Enabled = (AuthenticationMethods)cmb.SelectedValue == AuthenticationMethods.Sql;
						lblPassword.Enabled = (AuthenticationMethods)cmb.SelectedValue == AuthenticationMethods.Sql;
						tbPassword.Enabled = (AuthenticationMethods)cmb.SelectedValue == AuthenticationMethods.Sql;
					}
				}

				if (cmb.Equals(cmbServer))
				{
					cmbDatabase.DataSource = (cmb.SelectedItem as SqlServerInfo).Catalogs;
					if ((cmb.SelectedItem as SqlServerInfo).Catalogs.Contains(fSqlBuilder.InitialCatalog))
					{
						var selected = (from cat in (cmb.SelectedItem as SqlServerInfo).Catalogs where cat.Equals(fSqlBuilder.InitialCatalog) select cat).FirstOrDefault();
						cmbDatabase.SelectedItem = selected;
					}
				}
			}
		}

		private void OnClick(object sender, EventArgs e)
		{
			if (sender is Button)
			{
				Button btn = sender as Button;
				if (btn.Equals(btnOK))
				{
					if (!ValidateFormData())
						return;

					fEntityBuilder.Provider = "System.Data.SqlClient";
					fEntityBuilder.Metadata = @"res://*/REPLACE_WITH_YOURS.csdl|res://*/REPLACE_WITH_YOURS.ssdl|res://*/REPLACE_WITH_YOURS.msl";
					fSqlBuilder.ApplicationName = (ConnectionStringType)cmbType.SelectedValue == ConnectionStringType.Entity ? "EntityFramework" : ".NET SqlClient Data Provider";
					fSqlBuilder.ConnectTimeout = 0;
					fSqlBuilder.DataSource = (cmbServer.SelectedItem as SqlServerInfo).ToString();
					fSqlBuilder.Encrypt = false;
					fSqlBuilder.InitialCatalog = (string)cmbDatabase.SelectedItem;
					fSqlBuilder.MultipleActiveResultSets = ((ConnectionStringType)cmbType.SelectedValue == ConnectionStringType.Entity);
					fSqlBuilder.Pooling = true;

					if ((AuthenticationMethods)cmbAuthentication.SelectedValue == AuthenticationMethods.Windows)
						fSqlBuilder.IntegratedSecurity = true;
					else
					{
						fSqlBuilder.UserID = tbUser.Text.Trim();
						fSqlBuilder.Password = tbPassword.Text.Trim();
					}

					fEntityBuilder.ProviderConnectionString = fSqlBuilder.ConnectionString;
					fConnectionString = (ConnectionStringType)cmbType.SelectedValue == ConnectionStringType.Entity ? fEntityBuilder.ConnectionString : fSqlBuilder.ConnectionString;
					DialogResult = System.Windows.Forms.DialogResult.OK;
				}
			}
		}
	}
}

Open in new window

LocateDatabase.Designer.cs -
namespace EE_Q28967975
{
	partial class LocateDatabase
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.lblInfo = new System.Windows.Forms.Label();
			this.lblServer = new System.Windows.Forms.Label();
			this.cmbServer = new System.Windows.Forms.ComboBox();
			this.lblDatabase = new System.Windows.Forms.Label();
			this.cmbDatabase = new System.Windows.Forms.ComboBox();
			this.lblAuthentication = new System.Windows.Forms.Label();
			this.cmbAuthentication = new System.Windows.Forms.ComboBox();
			this.lblUser = new System.Windows.Forms.Label();
			this.tbUser = new System.Windows.Forms.TextBox();
			this.lblPassword = new System.Windows.Forms.Label();
			this.tbPassword = new System.Windows.Forms.TextBox();
			this.btnOK = new System.Windows.Forms.Button();
			this.btnCancel = new System.Windows.Forms.Button();
			this.cmbType = new System.Windows.Forms.ComboBox();
			this.lblType = new System.Windows.Forms.Label();
			this.SuspendLayout();
			// 
			// lblInfo
			// 
			this.lblInfo.BackColor = System.Drawing.SystemColors.Control;
			this.lblInfo.ForeColor = System.Drawing.Color.Black;
			this.lblInfo.Location = new System.Drawing.Point(0, 0);
			this.lblInfo.Name = "lblInfo";
			this.lblInfo.Size = new System.Drawing.Size(344, 38);
			this.lblInfo.TabIndex = 0;
			this.lblInfo.Text = "This form will build a connection string to the chosen SQL Server.  The returned " +
    "connection string can be an Entity Type.";
			// 
			// lblServer
			// 
			this.lblServer.AutoSize = true;
			this.lblServer.BackColor = System.Drawing.SystemColors.Control;
			this.lblServer.ForeColor = System.Drawing.Color.Black;
			this.lblServer.Location = new System.Drawing.Point(64, 79);
			this.lblServer.Name = "lblServer";
			this.lblServer.Size = new System.Drawing.Size(74, 13);
			this.lblServer.TabIndex = 3;
			this.lblServer.Text = "&Server / Host:";
			// 
			// cmbServer
			// 
			this.cmbServer.ForeColor = System.Drawing.Color.Black;
			this.cmbServer.Location = new System.Drawing.Point(144, 76);
			this.cmbServer.Name = "cmbServer";
			this.cmbServer.Size = new System.Drawing.Size(208, 21);
			this.cmbServer.TabIndex = 4;
			this.cmbServer.SelectedIndexChanged += new System.EventHandler(this.OnSelectedIndexChanged);
			// 
			// lblDatabase
			// 
			this.lblDatabase.AutoSize = true;
			this.lblDatabase.BackColor = System.Drawing.SystemColors.Control;
			this.lblDatabase.ForeColor = System.Drawing.Color.Black;
			this.lblDatabase.Location = new System.Drawing.Point(51, 103);
			this.lblDatabase.Name = "lblDatabase";
			this.lblDatabase.Size = new System.Drawing.Size(87, 13);
			this.lblDatabase.TabIndex = 5;
			this.lblDatabase.Text = "&Database Name:";
			// 
			// cmbDatabase
			// 
			this.cmbDatabase.ForeColor = System.Drawing.Color.Black;
			this.cmbDatabase.Location = new System.Drawing.Point(144, 100);
			this.cmbDatabase.MaxLength = 255;
			this.cmbDatabase.Name = "cmbDatabase";
			this.cmbDatabase.Size = new System.Drawing.Size(208, 21);
			this.cmbDatabase.TabIndex = 6;
			this.cmbDatabase.Enter += new System.EventHandler(this.OnEnter);
			// 
			// lblAuthentication
			// 
			this.lblAuthentication.AutoSize = true;
			this.lblAuthentication.BackColor = System.Drawing.SystemColors.Control;
			this.lblAuthentication.ForeColor = System.Drawing.Color.Black;
			this.lblAuthentication.Location = new System.Drawing.Point(60, 127);
			this.lblAuthentication.Name = "lblAuthentication";
			this.lblAuthentication.Size = new System.Drawing.Size(78, 13);
			this.lblAuthentication.TabIndex = 7;
			this.lblAuthentication.Text = "&Authentication:";
			// 
			// cmbAuthentication
			// 
			this.cmbAuthentication.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
			this.cmbAuthentication.ForeColor = System.Drawing.Color.Black;
			this.cmbAuthentication.Location = new System.Drawing.Point(144, 124);
			this.cmbAuthentication.Name = "cmbAuthentication";
			this.cmbAuthentication.Size = new System.Drawing.Size(208, 21);
			this.cmbAuthentication.TabIndex = 8;
			this.cmbAuthentication.SelectedIndexChanged += new System.EventHandler(this.OnSelectedIndexChanged);
			// 
			// lblUser
			// 
			this.lblUser.AutoSize = true;
			this.lblUser.BackColor = System.Drawing.SystemColors.Control;
			this.lblUser.Enabled = false;
			this.lblUser.ForeColor = System.Drawing.Color.Black;
			this.lblUser.Location = new System.Drawing.Point(92, 151);
			this.lblUser.Name = "lblUser";
			this.lblUser.Size = new System.Drawing.Size(46, 13);
			this.lblUser.TabIndex = 9;
			this.lblUser.Text = "&User ID:";
			// 
			// tbUser
			// 
			this.tbUser.BackColor = System.Drawing.Color.White;
			this.tbUser.Enabled = false;
			this.tbUser.ForeColor = System.Drawing.Color.Black;
			this.tbUser.Location = new System.Drawing.Point(144, 148);
			this.tbUser.MaxLength = 255;
			this.tbUser.Name = "tbUser";
			this.tbUser.Size = new System.Drawing.Size(208, 20);
			this.tbUser.TabIndex = 10;
			this.tbUser.Enter += new System.EventHandler(this.OnEnter);
			// 
			// lblPassword
			// 
			this.lblPassword.AutoSize = true;
			this.lblPassword.BackColor = System.Drawing.SystemColors.Control;
			this.lblPassword.Enabled = false;
			this.lblPassword.ForeColor = System.Drawing.Color.Black;
			this.lblPassword.Location = new System.Drawing.Point(82, 175);
			this.lblPassword.Name = "lblPassword";
			this.lblPassword.Size = new System.Drawing.Size(56, 13);
			this.lblPassword.TabIndex = 11;
			this.lblPassword.Text = "&Password:";
			// 
			// tbPassword
			// 
			this.tbPassword.BackColor = System.Drawing.Color.White;
			this.tbPassword.Enabled = false;
			this.tbPassword.ForeColor = System.Drawing.Color.Black;
			this.tbPassword.Location = new System.Drawing.Point(144, 172);
			this.tbPassword.MaxLength = 255;
			this.tbPassword.Name = "tbPassword";
			this.tbPassword.Size = new System.Drawing.Size(208, 20);
			this.tbPassword.TabIndex = 12;
			this.tbPassword.Enter += new System.EventHandler(this.OnEnter);
			// 
			// btnOK
			// 
			this.btnOK.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton;
			this.btnOK.Location = new System.Drawing.Point(184, 204);
			this.btnOK.Name = "btnOK";
			this.btnOK.Size = new System.Drawing.Size(80, 24);
			this.btnOK.TabIndex = 13;
			this.btnOK.Text = "OK";
			this.btnOK.Click += new System.EventHandler(this.OnClick);
			// 
			// btnCancel
			// 
			this.btnCancel.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton;
			this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.btnCancel.Location = new System.Drawing.Point(272, 204);
			this.btnCancel.Name = "btnCancel";
			this.btnCancel.Size = new System.Drawing.Size(80, 24);
			this.btnCancel.TabIndex = 14;
			this.btnCancel.Text = "Cancel";
			// 
			// cmbType
			// 
			this.cmbType.ForeColor = System.Drawing.Color.Black;
			this.cmbType.Location = new System.Drawing.Point(144, 49);
			this.cmbType.Name = "cmbType";
			this.cmbType.Size = new System.Drawing.Size(208, 21);
			this.cmbType.TabIndex = 2;
			// 
			// lblType
			// 
			this.lblType.AutoSize = true;
			this.lblType.BackColor = System.Drawing.SystemColors.Control;
			this.lblType.ForeColor = System.Drawing.Color.Black;
			this.lblType.Location = new System.Drawing.Point(8, 52);
			this.lblType.Name = "lblType";
			this.lblType.Size = new System.Drawing.Size(130, 13);
			this.lblType.TabIndex = 1;
			this.lblType.Text = "&Type of connection string:";
			// 
			// LocateDatabase
			// 
			this.AcceptButton = this.btnOK;
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.CancelButton = this.btnCancel;
			this.ClientSize = new System.Drawing.Size(363, 240);
			this.ControlBox = false;
			this.Controls.Add(this.lblInfo);
			this.Controls.Add(this.lblType);
			this.Controls.Add(this.cmbType);
			this.Controls.Add(this.lblServer);
			this.Controls.Add(this.cmbServer);
			this.Controls.Add(this.lblDatabase);
			this.Controls.Add(this.cmbDatabase);
			this.Controls.Add(this.lblAuthentication);
			this.Controls.Add(this.cmbAuthentication);
			this.Controls.Add(this.lblUser);
			this.Controls.Add(this.tbUser);
			this.Controls.Add(this.lblPassword);
			this.Controls.Add(this.tbPassword);
			this.Controls.Add(this.btnOK);
			this.Controls.Add(this.btnCancel);
			this.DoubleBuffered = true;
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
			this.KeyPreview = true;
			this.Name = "LocateDatabase";
			this.ShowInTaskbar = false;
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Locate Database";
			this.Load += new System.EventHandler(this.OnLoad);
			this.ResumeLayout(false);
			this.PerformLayout();

		}

		#endregion

		internal System.Windows.Forms.Label lblInfo;
		internal System.Windows.Forms.Label lblServer;
		internal System.Windows.Forms.ComboBox cmbServer;
		internal System.Windows.Forms.Label lblDatabase;
		internal System.Windows.Forms.ComboBox cmbDatabase;
		internal System.Windows.Forms.Label lblAuthentication;
		internal System.Windows.Forms.ComboBox cmbAuthentication;
		internal System.Windows.Forms.Label lblUser;
		internal System.Windows.Forms.TextBox tbUser;
		internal System.Windows.Forms.Label lblPassword;
		internal System.Windows.Forms.TextBox tbPassword;
		internal System.Windows.Forms.Button btnOK;
		internal System.Windows.Forms.Button btnCancel;
		internal System.Windows.Forms.ComboBox cmbType;
		internal System.Windows.Forms.Label lblType;
	}
}

Open in new window

SupporingObjects.cs -
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace EE_Q28967975
{
	enum AuthenticationMethods : int
	{
		[Description("[-- Select an authentication method --]")] None = 0,
		[Description("Micorosoft Windows")] Windows = 1,
		[Description("SQL Server")] Sql = 2,
	}

	enum ConnectionStringType : int
	{
		[Description("[-- Select an connection string type --]")] None = 0,
		[Description("Standard Connection String")] Standard = 1,
		[Description("Entity Connection String")] Entity = 2,
	}

	static class Extensions
	{
		/// <summary>Performs the specified action on each element of the sequence.</summary>
		/// <typeparam name="T">The type of the elements of source.</typeparam>
		/// <param name="source">The source sequence.</param>
		/// <param name="action">The action.</param>
		/// <exception cref="System.ArgumentNullException">
		/// source
		/// or
		/// action
		/// </exception>
		public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
		{
			if (source == null)
				throw new ArgumentNullException("source");

			if (action == null)
				throw new ArgumentNullException("action");

			//foreach (T item in source)
			//	action(item);
			source.ToList().ForEach(action);
		}

		/// <summary>Gets the description attribute of an enumerations value.</summary>
		/// <param name="value">The value to get the description for</param>
		/// <returns>Returns the DescriptionAttribute if the specified value has one.  If not, returns the ToString() representation of the value.</returns>
		public static string GetDescription(this Enum value)
		{
			FieldInfo _fieldInfo = value.GetType().GetField(value.ToString());
			DescriptionAttribute[] attributes = (DescriptionAttribute[])_fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
			return attributes.Length > 0 ? attributes[0].Description : value.ToString();
		}
	}

	/// <summary>Generic class that defines a simple list item for populating lists and drop downs and lists</summary>
	[Serializable]
	class ListItem<T>
	{
		#region Public Static Methods
		/// <summary>Method that uses a list of workspace list items to build and object profile</summary>
		/// <param name="listItems">The list items.</param>
		/// <returns>Dictionary{System.StringSystem.Object}.</returns>
		public static Dictionary<string, T> GetProfileFromListItems(List<ListItem<T>> listItems)
		{
			Dictionary<string, T> profile = new Dictionary<string, T>();
			foreach (ListItem<T> item in listItems)
				profile.Add(item.Label, item.Value);
			return profile;
		}

		/// <summary>Method that builds a profile</summary>
		/// <param name="labelsAndValues">The labels and values.</param>
		/// <returns>Dictionary{System.StringSystem.Object}.</returns>
		public static Dictionary<string, T> BuildProfile(params T[] labelsAndValues)
		{
			Dictionary<string, T> profile = new Dictionary<string, T>();
			if (labelsAndValues != null)
			{
				for (int i = 0; i < labelsAndValues.Length - 1; i += 2)
					profile.Add(labelsAndValues[i].ToString(), labelsAndValues[i + 1]);
			}
			return profile;
		}

		/// <summary>Method that builds a list of workspace list items from a specified profile</summary>
		/// <param name="profile">The profile.</param>
		/// <returns>List{WorkspaceListItem}.</returns>
		public static List<ListItem<T>> GetListItemsFromProfile(Dictionary<string, T> profile)
		{
			List<ListItem<T>> items = new List<ListItem<T>>();
			foreach (KeyValuePair<string, T> pair in profile)
				items.Add(new ListItem<T>(pair.Key, pair.Value));
			return items;
		}

		/// <summary>Method that builds a list of workspace list items from a specified profile</summary>
		/// <typeparam name="TValue">The type of the sorted dictionary tvalue object.</typeparam>
		/// <param name="profile">The profile.</param>
		/// <returns>List{WorkspaceListItem}.</returns>
		public static List<ListItem<T>> GetListItemsFromProfile<T>(SortedDictionary<string, T> profile)
		{
			List<ListItem<T>> items = new List<ListItem<T>>();
			foreach (KeyValuePair<string, T> pair in profile)
				items.Add(new ListItem<T>(pair.Key, pair.Value));
			return items;
		}

		/// <summary>Static method that returns a list of workspace items from a table of items</summary>
		/// <param name="table">DataTable: table to create the list from</param>
		/// <param name="labelIdentifier">object: string, int, or column indicating which column is the label.  If the column is null
		/// or another data type is passed in, then label will be an empty string</param>
		/// <param name="valueIdentifier">object: string, int, or column indicating which column is the value.  If the column is null
		/// or another data type is passed in, then the value will be null.</param>
		/// <param name="includeDefault">bool: indicates if a default item will be placed at the beginning of the list</param>
		/// <param name="defaultLabel">string: label of the default item</param>
		/// <param name="defaultValue">object: value of the default item</param>
		/// <returns>List(WorkspaceListItem): list of resulting workspace list items</returns>
		public static List<ListItem<T>> GetListItemsFromTable(DataTable table, object labelIdentifier, object valueIdentifier, bool includeDefault = true, string defaultLabel = "", T defaultValue = default(T))
		{
			List<ListItem<T>> returnList = new List<ListItem<T>>();

			//Adding a default value for top of the list
			if (includeDefault)
				returnList.Add(new ListItem<T>(defaultLabel, defaultValue));

			//Adding an item for each row in the table
			foreach (DataRow tempRow in table.Rows)
				returnList.Add(GetListItemFromRow(tempRow, labelIdentifier, valueIdentifier));

			return returnList;
		}


		/// <summary>Static method that returns a list of workspace items from a table of items</summary>
		/// <param name="table">DataTable: table to create the list from</param>
		/// <param name="labelFormat">string: format string for building the label</param>
		/// <param name="labelColIdentifiers">object[]: used to build the arguments which, coupled with the label format, build the label</param>
		/// <param name="valueIdentifier">object: string, int, or DataColumn indicating which column holds the value</param>
		/// <param name="includeDefault">bool: indicates if a default item will be placed at the beginning of the list</param>
		/// <param name="defaultLabel">string: label of the default item</param>
		/// <param name="defaultValue">object: value of the default item</param>
		/// <returns>List(WorkspaceListItem): list of resulting workspace list items</returns>
		public static List<ListItem<T>> GetListItemsFromTable(DataTable table, string labelFormat, object[] labelColIdentifiers, object valueIdentifier, bool includeDefault = true, string defaultLabel = "", T defaultValue = default(T))
		{
			List<ListItem<T>> returnList = new List<ListItem<T>>();

			//Adding a default value for top of the list
			if (includeDefault)
				returnList.Add(new ListItem<T>(defaultLabel, defaultValue));

			//Adding an item for each row in the table
			foreach (DataRow tempRow in table.Rows)
				returnList.Add(GetListItemFromRow(tempRow, labelFormat, labelColIdentifiers, valueIdentifier));

			return returnList;
		}


		/// <summary>Static method that returns a list of workspace items from a table of items</summary>
		/// <param name="rows">The rows.</param>
		/// <param name="labelIdentifier">object: string, int, or column indicating which column is the label.  If the column is null
		/// or another data type is passed in, then label will be an empty string</param>
		/// <param name="valueIdentifier">object: string, int, or column indicating which column is the value.  If the column is null
		/// or another data type is passed in, then the value will be null.</param>
		/// <param name="includeDefault">bool: indicates if a default item will be placed at the beginning of the list</param>
		/// <param name="defaultLabel">string: label of the default item</param>
		/// <param name="defaultValue">object: value of the default item</param>
		/// <returns>List(WorkspaceListItem): list of resulting workspace list items</returns>
		public static List<ListItem<T>> GetListItemsFromRows(DataRow[] rows, object labelIdentifier, object valueIdentifier, bool includeDefault = true, string defaultLabel = "", T defaultValue = default(T))
		{
			List<ListItem<T>> returnList = new List<ListItem<T>>();

			//Adding a default value for top of the list
			if (includeDefault)
				returnList.Add(new ListItem<T>(defaultLabel, defaultValue));

			//Adding an item for each row in the table
			foreach (DataRow tempRow in rows)
				returnList.Add(GetListItemFromRow(tempRow, labelIdentifier, valueIdentifier));

			return returnList;
		}


		/// <summary>Static method that returns a list of workspace items from a table of items</summary>
		/// <param name="rows">DataRow[]: rows to create the list from</param>
		/// <param name="labelFormat">string: format string for building the label</param>
		/// <param name="labelColIdentifiers">object[]: used to build the arguments which, coupled with the label format, build the label</param>
		/// <param name="valueIdentifier">object: string, int, or DataColumn indicating which column holds the value</param>
		/// <param name="includeDefault">bool: indicates if a default item will be placed at the beginning of the list</param>
		/// <param name="defaultLabel">string: label of the default item</param>
		/// <param name="defaultValue">object: value of the default item</param>
		/// <returns>List(WorkspaceListItem): list of resulting workspace list items</returns>
		public static List<ListItem<T>> GetListItemsFromRows(DataRow[] rows, string labelFormat, object[] labelColIdentifiers, object valueIdentifier, bool includeDefault = true, string defaultLabel = "", T defaultValue = default(T))
		{
			List<ListItem<T>> returnList = new List<ListItem<T>>();

			//Adding a default value for top of the list
			if (includeDefault)
				returnList.Add(new ListItem<T>(defaultLabel, defaultValue));

			//Adding an item for each row in the table
			foreach (DataRow tempRow in rows)
				returnList.Add(GetListItemFromRow(tempRow, labelFormat, labelColIdentifiers, valueIdentifier));

			return returnList;
		}


		/// <summary>Static method that returns a list item from a data row</summary>
		/// <param name="row">DataRow: the row to get the item for</param>
		/// <param name="labelIdentifier">object: string, int, or column indicating which column is the label.  If the column is null
		/// or another data type is passed in, then label will be an empty string</param>
		/// <param name="valueIdentifier">object: string, int, or column indicating which column is the value.  If the column is null
		/// or another data type is passed in, then the value will be null.</param>
		/// <returns>WorkspaceListItem: item created from the data row</returns>
		public static ListItem<T> GetListItemFromRow(DataRow row, object labelIdentifier, object valueIdentifier)
		{
			string label = GetColumnValue(row, labelIdentifier).ToString();
			T value = valueIdentifier == null ? default(T) : GetColumnValue(row, valueIdentifier);

			return new ListItem<T>(label ?? "", value);
		}


		/// <summary>Method that gets a list item for a data row</summary>
		/// <param name="row">DataRow: row used to build the list item</param>
		/// <param name="labelFormat">string: format string for building the label</param>
		/// <param name="labelColIdentifiers">object[]: int, string, or DataColumn array used to build the label.
		/// Other data types will result in null column values</param>
		/// <param name="valueIdentifier">object: int, string, or DataColumn that indicates which column contains the item value</param>
		/// <returns>WorkspaceListItem: item created from the row</returns>
		public static ListItem<T> GetListItemFromRow(DataRow row, string labelFormat, object[] labelColIdentifiers, object valueIdentifier)
		{
			object[] args = new object[labelColIdentifiers.Length];
			string label = "";
			T value = valueIdentifier == null ? default(T) : GetColumnValue(row, valueIdentifier);

			//Getting the objects for the custom label format
			for (int i = 0; i < labelColIdentifiers.Length; i++)
				args[i] = GetColumnValue(row, labelColIdentifiers[i]);
			label = String.Format(labelFormat, args);

			return new ListItem<T>(label, value);
		}


		/// <summary>Method that takes an enumeration type and returns a corresponding list of workspace list items</summary>
		/// <param name="enumType">Type: the type of enum to use</param>
		/// <param name="includeDefault">bool: indicates if a default item should be added to the list</param>
		/// <param name="defaultLabel">string: label to used for the default item</param>
		/// <param name="defaultValue">object: value to be used for the default item</param>
		/// <returns>List&lt;CategoryItem&gt;.</returns>
		public static List<ListItem<T>> GetListItemsFromEnum(Type enumType, bool includeDefault = true, string defaultLabel = "", T defaultValue = default(T))
		{
			List<ListItem<T>> returnList = new List<ListItem<T>>();

			//Make sure the type really is an enumeration
			if (enumType.IsEnum)
			{
				//Adding a default value for top of the list
				if (includeDefault)
					returnList.Add(new ListItem<T>(defaultLabel, defaultValue) { Description = (defaultValue as Enum).GetDescription() });

				(from T value in Enum.GetValues(typeof(T)) select value).ForEach(item =>
				{
					if (!item.Equals(defaultValue))
						returnList.Add(new ListItem<T>(item.ToString(), item) { Description = (item as Enum).GetDescription() });
				});
			}

			return returnList;
		}

		/// <summary>Static method that returns a value based on a row and column identifier</summary>
		/// <param name="row">DataRow: row that contains the value</param>
		/// <param name="columnIdentifier">object: int, string, or DataColumn that identifies the requested column</param>
		/// <returns>object: value of requested column, null if invalid</returns>
		public static T GetColumnValue(DataRow row, object columnIdentifier)
		{
			T value = default(T);

			if (columnIdentifier != null && row != null)
			{
				if (columnIdentifier.GetType() == typeof(int))
					value = row.IsNull((int)columnIdentifier) ? default(T) : (T)row[(int)columnIdentifier];
				else if (columnIdentifier.GetType() == typeof(string))
					value = row.IsNull((string)columnIdentifier) ? default(T) : (T)row[(string)columnIdentifier];
				else if (columnIdentifier.GetType() == typeof(DataColumn))
					value = row.IsNull((DataColumn)columnIdentifier) ? default(T) : (T)row[(DataColumn)columnIdentifier];
			}

			return value;
		}
		#endregion

		#region Private Fields
		/// <summary>The value field</summary>
		private T fValue = default(T);
		#endregion

		#region Public Properties
		/// <summary>Gets or sets the description.</summary>
		/// <value>The description.</value>
		public string Description { get; set; }
		/// <summary>Gets/Sets the label of the list item</summary>
		/// <value>The label.</value>
		public string Label { get; set; }

		/// <summary>Gets/Sets the selectio item ID</summary>
		/// <value>The selection identifier.</value>
		public int SelectionID { get; set; }

		/// <summary>Gets/Sets the value associated with the list item</summary>
		/// <value>The value.</value>
		public T Value
		{
			get { return fValue == null ? default(T) : fValue; }
			set { fValue = value; }
		}
		#endregion

		#region Constructor(s)
		/// <summary>Default constructor - no params</summary>
		public ListItem() : this("", default(T)) { ;}

		/// <summary>Overload constructor - takes params for each public property</summary>
		/// <param name="label">string: the label to display</param>
		/// <param name="value">object: data value to associate with the label</param>
		public ListItem(string label = "", T value = default(T))
		{
			Label = label;
			Value = value;
		}
		#endregion

		#region Public Methods
		/// <summary>Method that gets a string representation of the list item</summary>
		/// <returns>string: the list item label</returns>
		public override string ToString()
		{
			return Label;
		}
		#endregion
	}

	static class NativeMethods
	{
		public const short DEFAULT_RESULT_SIZE = 1024;
		public const short SQL_HANDLE_DBC = 2;
		public const short SQL_HANDLE_ENV = 1;
		public const short SQL_NEED_DATA = 99;
		public const short SQL_SUCCESS = 0;

		public const int SQL_ATTR_ODBC_VERSION = 200;
		public const int SQL_OV_ODBC3 = 3;

		public const string SQL_DRIVER_STR = "DRIVER=SQL SERVER";

		/// <summary>Allocates an environment, connection, statement, or descriptor handle.</summary>
		/// <param name="handleType">Type of the handle.</param>
		/// <param name="inputHandle">The input handle in whose context the new handle is to be allocated.</param>
		/// <param name="outputHandlePtr">Pointer to a buffer in which to return the handle to the newly allocated data structure.</param>
		/// <returns>When allocating a handle other than an environment handle, if SQLAllocHandle returns SQL_ERROR, it sets OutputHandlePtr to SQL_NULL_HDBC, SQL_NULL_HSTMT, or SQL_NULL_HDESC, depending on the value of HandleType, unless the output argument is a null pointer.  The application can then obtain additional information from the diagnostic data structure associated with the handle in the InputHandle argument.</returns>
		[DllImport("odbc32.dll")]
		public static extern short SQLAllocHandle(short handleType, IntPtr inputHandle, out IntPtr outputHandlePtr);

		/// <summary>Supports an iterative method of discovering and enumerating the attributes and attribute values required to connect to a data source.</summary>
		/// <param name="handleConnection">The handle connection.</param>
		/// <param name="inConnection">Browse request connection string.</param>
		/// <param name="stringLength">Length of the string.</param>
		/// <param name="outConnection">Pointer to a character buffer in which to return the browse result connection string.  If outConnection is NULL, stringLength2Ptr will still return the total number of characters (excluding the null-termination character for character data) available to return in the buffer pointed to by outConnection.</param>
		/// <param name="bufferLength">Length, in characters, of the outConnection buffer.</param>
		/// <param name="stringLength2Ptr">The total number of characters (excluding null-termination) available to return in outConnection. If the number of characters available to return is greater than or equal to bufferLength, the connection string in outConnection is truncated to bufferLength minus the length of a null-termination character.</param>
		/// <returns>SQL_SUCCESS, SQL_SUCCESS_WITH_INFO, SQL_NEED_DATA, SQL_ERROR, SQL_INVALID_HANDLE, or SQL_STILL_EXECUTING.</returns>
		[DllImport("odbc32.dll", CharSet = CharSet.Ansi)]
		public static extern short SQLBrowseConnect(IntPtr handleConnection, StringBuilder inConnection, short stringLength, StringBuilder outConnection, short bufferLength, out short stringLength2Ptr);

		/// <summary>Frees resources associated with a specific environment, connection, statement, or descriptor handle.</summary>
		/// <param name="hType">The type of handle to be freed.</param>
		/// <param name="Handle">The handle to be freed.</param>
		/// <returns>SQL_SUCCESS, SQL_ERROR, or SQL_INVALID_HANDLE.  If SQLFreeHandle returns SQL_ERROR, the handle is still valid.</returns>
		[DllImport("odbc32.dll")]
		public static extern short SQLFreeHandle(short hType, IntPtr Handle);

		/// <summary>Sets attributes that govern aspects of environments.</summary>
		/// <param name="environmentHandle">The environment handle.</param>
		/// <param name="attribute">The attribute to set.</param>
		/// <param name="valuePtr">Pointer to the value to be associated with Attribute. Depending on the value of Attribute, ValuePtr will be a 32-bit integer value or point to a null-terminated character string.</param>
		/// <param name="stringLength">If ValuePtr points to a character string or a binary buffer, this argument should be the length of *ValuePtr. For character string data, this argument should contain the number of bytes in the string.  If ValuePtr is an integer, StringLength is ignored.</param>
		/// <returns>SQL_SUCCESS, SQL_SUCCESS_WITH_INFO, SQL_ERROR, or SQL_INVALID_HANDLE.</returns>
		[DllImport("odbc32.dll")]
		public static extern short SQLSetEnvAttr(IntPtr environmentHandle, int attribute, IntPtr valuePtr, int stringLength);
	}

	/// <summary>Class SqlServerInfo <p/>Provides information about a MS SQL server instance.</summary>
	/// <example><pre>SqlServerInfo[] servs = SqlServerInfo.Seek();
	/// foreach(SqlServerInfo inst in servs)
	/// {
	///      Console.WriteLine("Server: {0}, InstanceName: {1}, Version: {2}", serv.ServerName, serv.InstanceName, serv.Version);
	///      foreach(string db in serv.Catalogs)
	///      {
	///           Console.WriteLine("      Database: {0}", db);
	///      }
	/// }</pre></example>
	class SqlServerInfo
	{
		#region Fields
		private readonly string fServerName;
		private readonly string fInstanceName;
		private readonly bool fIsClustered;
		private readonly string fVersion;
		private readonly int fTcpPort;
		private readonly string fNamedPipe;
		private readonly string fRpc;
		private readonly IPAddress fIP;
		private List<string> fCatalogs;
		private string fUserId;
		private string fPassword;
		private bool fIntegratedSecurity = true;
		private int fTimeOut = 2;
		#endregion

		#region Constructors
		/// <summary>Initializes a new instance of the <see cref="SqlServerInfo"/> class.</summary>
		private SqlServerInfo() { ;}

		private SqlServerInfo(string serverName, string instanceName = default(string))
		{
			fServerName = serverName;
			fInstanceName = instanceName;
		}

		/// <summary>Initializes a new instance of the <see cref="SqlServerInfo"/> class.</summary>
		/// <param name="ip">The ip.</param>
		/// <param name="info">The info.</param>
		public SqlServerInfo(IPAddress ip, byte[] info) : this(ip, ASCIIEncoding.ASCII.GetString(info, 3, BitConverter.ToInt16(info, 1))) { ;}

		/// <summary>Initializes a new instance of the <see cref="SqlServerInfo"/> class.</summary>
		/// <param name="ip">The ip address.</param>
		/// <param name="info">The info.</param>
		public SqlServerInfo(IPAddress ip, string info)
		{
			fIP = ip;
			string[] nvs = info.Split(';');
			for (int i = 0; i < nvs.Length; i += 2)
			{
				switch (nvs[i].ToLower())
				{
					case "servername":
						fServerName = nvs[i + 1];
						break;
					case "instancename":
						fInstanceName = nvs[i + 1];
						break;
					case "isclustered":
						fIsClustered = (nvs[i + 1].ToLower() == "yes");   //bool.Parse(nvs[i+1]);
						break;
					case "version":
						fVersion = nvs[i + 1];
						break;
					case "tcp":
						fTcpPort = int.Parse(nvs[i + 1]);
						break;
					case "np":
						fNamedPipe = nvs[i + 1];
						break;
					case "rpc":
						fRpc = nvs[i + 1];
						break;
				}
			}
		}
		#endregion

		#region Public Properties
		/// <summary>Gets the IP address.</summary>
		/// <value>The address.</value>
		/// <remarks>Presently, this is not implemented and will always return null,</remarks>
		public IPAddress Address { get { return fIP; } }
		/// <summary>Gets the name of the server.</summary>
		/// <value>The name of the server.</value>
		public string ServerName { get { return fServerName; } }
		/// <summary>Gets the name of the instance.</summary>
		/// <value>The name of the instance.</value>
		public string InstanceName { get { return fInstanceName; } }
		/// <summary>Gets a value indicating whether this instance is clustered.</summary>
		/// <value><see langword="true"/> if this instance is clustered; otherwise, <see langword="false"/>.</value>
		public bool IsClustered { get { return fIsClustered; } }
		/// <summary>Gets the version.</summary>
		/// <value>The version.</value>
		public string Version { get { return fVersion; } }
		/// <summary>Gets the TCP port.</summary>
		/// <value>The TCP port.</value>
		public int TcpPort { get { return fTcpPort; } }
		/// <summary>Gets the named pipe.</summary>
		/// <value>The named pipe.</value>
		public string NamedPipe { get { return fNamedPipe; } }
		/// <summary>Gets the catalogs.</summary>
		/// <value>The catalogs.</value>
		public List<string> Catalogs
		{
			get
			{
				if (fCatalogs == null)
					fCatalogs = GetCatalogs();
				return fCatalogs;
			}
		}
		/// <summary>Gets or sets the user id.</summary>
		/// <value>The user id.</value>
		public string UserId
		{
			get { return fUserId; }
			set
			{
				fUserId = value;
				fIntegratedSecurity = false;
			}
		}
		/// <summary>Gets or sets the password.</summary>
		/// <value>The password.</value>
		public string Password
		{
			get { return fPassword; }
			set
			{
				fPassword = value;
				fIntegratedSecurity = false;
			}
		}
		/// <summary>Gets or sets a value indicating whether [integrated security].</summary>
		/// <value><see langword="true"/> if [integrated security]; otherwise, <see langword="false"/>.</value>
		public bool IntegratedSecurity
		{
			get { return fIntegratedSecurity; }
			set { fIntegratedSecurity = value; }
		}
		/// <summary>Gets or sets the time out.</summary>
		/// <value>The time out.</value>
		public int TimeOut
		{
			get { return fTimeOut; }
			set { fTimeOut = value; }
		}
		#endregion

		#region Public Methods
		/// <summary>Tests the connection.</summary>
		public bool TestConnection()
		{
			OleDbConnection conn = GetConnection();
			bool success = false;
			try
			{
				conn.Open();
				conn.Close();
				success = true;
			}
			catch (Exception ex)
			{
				MessageBox.Show(string.Format("Exception reported in {0} - {1} [{2}]", ex.Source, ex, ex.Message), "Exception Reported!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			return success;
		}
		/// <summary>Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.</summary>
		/// <returns>A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.</returns>
		public override string ToString()
		{
			return InstanceName == null || InstanceName == "MSSQLSERVER" ? ServerName : string.Format("{0}\\{1}", ServerName, InstanceName);
		}
		#endregion

		#region Private Methods
		private List<string> GetCatalogs()
		{
			List<string> catalogs = new List<string>();

			try
			{
				OleDbConnection myConnection = GetConnection();
				myConnection.Open();
				DataTable schemaTable = myConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Catalogs, null);
				myConnection.Close();
				foreach (DataRow dr in schemaTable.Rows)
					catalogs.Add(dr[0] as string);
			}
			catch (Exception)
			{
				/* An exception here means that the catalogs could not be retrieved */
			}
			return catalogs;
		}

		private OleDbConnection GetConnection()
		{
			string myConnString = IntegratedSecurity ?
				string.Format("Provider=SQLOLEDB;Data Source={0};Integrated Security=SSPI;Connect Timeout={1}", this, TimeOut)
				: string.Format("Provider=SQLOLEDB;Data Source={0};User Id={1};Password={2};Connect Timeout={3}", this, UserId, Password, TimeOut);
			return new OleDbConnection(myConnString);
		}
		#endregion

		#region Public Static Method - Seek
		public static List<SqlServerInfo> GetSqlServers()
		{
			List<SqlServerInfo> results = new List<SqlServerInfo>();
			string instances = string.Empty;
			IntPtr henv = IntPtr.Zero;
			IntPtr hconn = IntPtr.Zero;
			StringBuilder inString = new StringBuilder(NativeMethods.SQL_DRIVER_STR);
			StringBuilder outString = new StringBuilder(NativeMethods.DEFAULT_RESULT_SIZE);
			short inStringLength = (short)inString.Length;
			short lenNeeded = 0;

			try
			{
				if (NativeMethods.SQL_SUCCESS == NativeMethods.SQLAllocHandle(NativeMethods.SQL_HANDLE_ENV, henv, out henv))
				{
					if (NativeMethods.SQL_SUCCESS == NativeMethods.SQLSetEnvAttr(henv, NativeMethods.SQL_ATTR_ODBC_VERSION, (IntPtr)NativeMethods.SQL_OV_ODBC3, 0))
					{
						if (NativeMethods.SQL_SUCCESS == NativeMethods.SQLAllocHandle(NativeMethods.SQL_HANDLE_DBC, henv, out hconn))
						{
							if (NativeMethods.SQL_NEED_DATA == NativeMethods.SQLBrowseConnect(hconn, inString, inStringLength, outString, NativeMethods.DEFAULT_RESULT_SIZE, out lenNeeded))
							{
								if (NativeMethods.DEFAULT_RESULT_SIZE < lenNeeded)
								{
									outString.Capacity = lenNeeded;
									if (NativeMethods.SQL_NEED_DATA != NativeMethods.SQLBrowseConnect(hconn, inString, inStringLength, outString, lenNeeded, out lenNeeded))
									{
										throw new ApplicationException("Unabled to aquire SQL Servers from ODBC driver.");
									}
								}
								instances = outString.ToString();
								int start = instances.IndexOf("{") + 1;
								int len = instances.IndexOf("}") - start;
								instances = (start > 0) && (len > 0) ? instances.Substring(start, len) : string.Empty;
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(string.Format("Exception reported in {0} - {1} [{2}]", ex.Source, ex, ex.Message), "Exception Reported!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
				instances = string.Empty;
			}
			finally
			{
				if (hconn != IntPtr.Zero)
					NativeMethods.SQLFreeHandle(NativeMethods.SQL_HANDLE_DBC, hconn);

				if (henv != IntPtr.Zero)
					NativeMethods.SQLFreeHandle(NativeMethods.SQL_HANDLE_ENV, henv);
			}

			if (instances.Length > 0)
			{
				foreach (string instance in instances.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
				{
					string[] pair = instance.Split('\\');
					if (pair.Count() < 2)
						results.Add(new SqlServerInfo(pair[0]));
					else
						results.Add(new SqlServerInfo(pair[0], pair[1] ?? default(string)));
				}
			}
			return results;
		}

		/// <summary>Seeks SQL servers on this network.</summary>
		/// <returns>An array of SqlServerInfo objects describing Sql Servers on this network</returns>
		static public SqlServerInfo[] Seek()
		{
			Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

			socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
			socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000);

			//  For .Net v 2.0 it's a bit simpler
			//  socket.EnableBroadcast = true;  // for .Net v2.0
			//  socket.ReceiveTimeout = 3000;   // for .Net v2.0

			ArrayList servers = new ArrayList();
			try
			{
				byte[] msg = new byte[] { 0x02 };
				IPEndPoint ep = new IPEndPoint(IPAddress.Broadcast, 1434);
				socket.SendTo(msg, ep);

				int cnt = 0;
				byte[] bytBuffer = new byte[1024];
				do
				{
					cnt = socket.Receive(bytBuffer);
					servers.Add(new SqlServerInfo(null, bytBuffer));
					socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 300);
				} while (cnt != 0);
			}
			catch (SocketException socex)
			{
				const int WSAETIMEDOUT = 10060;     // Connection timed out.
				const int WSAEHOSTUNREACH = 10065;  // No route to host.

				// Re-throw if it's not a timeout.
				if (socex.ErrorCode == WSAETIMEDOUT || socex.ErrorCode == WSAEHOSTUNREACH)
				{
					// DO nothing......
				}
				else
				{
					//                  Console.WriteLine("{0} {1}", socex.ErrorCode, socex.Message);
					throw;
				}
			}
			finally
			{
				socket.Close();
			}

			// Copy from the untyped but expandable ArrayList, to a
			// type-safe but fixed array of SqlServerInfos.

			SqlServerInfo[] aServers = new SqlServerInfo[servers.Count];
			servers.CopyTo(aServers);
			return aServers;
		}
		#endregion
	}
}

Open in new window

This is a dialog form the produces the following results:Capture.JPGThe Server/Host drop down will contain a list of retrieved SQL Server instances.  When you select a SQL Server instance, the Database Name drop down list will be filled with a list of databases available for the instance (an exception can be thrown if you cannot catalog the databases, just update the GetCatalogs() method in the SqlServerInfo class).

-saige-
1

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

A common practice in small networks is making file sharing easy which works extremely well when intra-network security is not an issue. In essence, everyone, that is "Everyone", is given access to all of the shared files - often the entire C: drive …
Trying to figure out group policy inheritance and which settings apply where can be a chore.  Here's a very simple summary I've written which might help.  Keep in mind, this is just a high-level conceptual overview where I try to avoid getting bogge…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now