Link to home
Start Free TrialLog in
Avatar of lankapala
lankapala

asked on

C# App config

Hi,
I need to install client computer C# Exe (Click once deployment) ,but how to ask him to give
Database server,DB  name and username and password

My configurations in the App.config
<connectionStrings>
    <add name="Test" connectionString="Data Source=UK-DB-eRP-001;Initial Catalog=ERPMain;Integrated Security=true" providerName="System.Data.SqlClient"  />

  </connectionStrings>

Open in new window


I thought giving text file to Edit, But how to connect with App.config?
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

But how to connect with App.config?

try using System.Configuration and then try like:
String DBConn = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;

Open in new window

i'm not asking this.
I'm asking How to find Client Database?
after i created EXE file they can't enter the Database name
after i created EXE file they can't enter the Database name
are you intend to create an interface to allow users to enter the connection info?
yes, what is the best way to do that.
using XML doc or text file.
if yes, how to add to App.config File?
yes, what is the best way to do that.
if yes, how to add to App.config File?
you can always write to App.config as well.

Write values in app.config file
https://stackoverflow.com/questions/4758598/write-values-in-app-config-file

using XML doc or text file.
you can also create a custom config file if necessary, and that's in XML format.
One method that I have used in the past is to embed a form in the project whose sole purpose is to check the app.config for a valid connection string and see if it can connect to the database.  If the connection can be made then the form is not shown, otherwise, the form is shown which allows for the user to correct the problem (by entering the relevant information) and trying again, once a successful connection is made, then the form saves the connection string to the app.config, using the method discussed above; e.g. -

From a previous EE PAQ:

VB.NET Version - https:/Q_29028690.html#a42172918
C# Version - https:/Q_28967975.html#a41786475

LocateDatabase.vb -
Imports System.Data.EntityClient
Imports System.Data.SqlClient

Public Class LocateDatabase
    Private _connectionString As String
    Private _eBuilder As EntityConnectionStringBuilder = New EntityConnectionStringBuilder()
    Private _sBuilder As SqlConnectionStringBuilder = New SqlConnectionStringBuilder()
    Private _sqlServers As List(Of SqlServerInfo) = SqlServerInfo.GetSqlServers()
    ReadOnly _authMethods As List(Of ListItem(Of AuthenticationMethod)) = New List(Of ListItem(Of AuthenticationMethod))()
    ReadOnly _connTypes As List(Of ListItem(Of ConnectionStringType)) = New List(Of ListItem(Of ConnectionStringType))()

    Public ReadOnly Property ConnectionString() As String
        Get
            Return _connectionString
        End Get
    End Property

    Public Sub New(Optional connectionString As String = "")
        InitializeComponent()

        _authMethods = ListItem(Of AuthenticationMethod).GetListItemsFromEnum(GetType(AuthenticationMethod))
        _connTypes = ListItem(Of ConnectionStringType).GetListItemsFromEnum(GetType(ConnectionStringType))

        If Not String.IsNullOrEmpty(connectionString) Then
            Try
                _eBuilder.ConnectionString = connectionString
            Catch ex As Exception
                ' Could not set connection string, perhaps this is a standard sql connection string
                _eBuilder.ProviderConnectionString = connectionString
            End Try
        End If
        _connectionString = _eBuilder.ConnectionString
    End Sub

    Private Sub OnClick(sender As Object, e As EventArgs) Handles btnOK.Click
        If TypeOf sender Is Button Then
            Dim btn = DirectCast(sender, Button)
            If btn.Equals(btnOK) Then
                If Not ValidateFormData() Then Return

                _eBuilder.Provider = "System.Data.SqlClient"
                _eBuilder.Metadata = "res://*/REPLACE_WITH_YOURS.csdl|res://*/REPLACE_WITH_YOURS.ssdl|res://*/REPLACE_WITH_YOURS.msl"
                _sBuilder.ApplicationName = If(CType(cmbType.SelectedValue, ConnectionStringType) = ConnectionStringType.Entity, "EntityFramework", ".NET SqlClient Data Provider")
                _sBuilder.ConnectTimeout = 0
                _sBuilder.DataSource = CType(cmbServer.SelectedItem, SqlServerInfo).ToString()
                _sBuilder.Encrypt = False
                _sBuilder.InitialCatalog = CType(cmbDataBase.SelectedItem, String)
                _sBuilder.MultipleActiveResultSets = (CType(cmbType.SelectedValue, ConnectionStringType) = ConnectionStringType.Entity)
                _sBuilder.Pooling = True

                If CType(cmbAuthentication.SelectedValue, AuthenticationMethod) = AuthenticationMethod.Windows Then
                    _sBuilder.IntegratedSecurity = True
                Else
                    _sBuilder.UserID = tbUser.Text.Trim()
                    _sBuilder.Password = tbPassword.Text.Trim()
                End If

                _eBuilder.ProviderConnectionString = _sBuilder.ConnectionString
                _connectionString = If(CType(cmbType.SelectedValue, ConnectionStringType) = ConnectionStringType.Entity, _eBuilder.ConnectionString, _sBuilder.ConnectionString)
                DialogResult = DialogResult.OK
            End If
        End If
    End Sub

    Private Sub OnEnter(sender As Object, e As EventArgs) Handles tbPassword.Enter, tbUser.Enter
        If TypeOf sender Is TextBox Then
            CType(sender, TextBox).SelectAll()
        End If
    End Sub

    Private Sub OnLoad(sender As Object, e As EventArgs) Handles MyBase.Load
        cmbAuthentication.DisplayMember = "Description"
        cmbAuthentication.ValueMember = "Value"
        cmbAuthentication.DataSource = _authMethods
        cmbAuthentication.SelectedValue = AuthenticationMethod.Windows

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

        _sBuilder.ConnectionString = _eBuilder.ProviderConnectionString
        _sBuilder.ConnectTimeout = 0
        _sBuilder.Encrypt = False
        _sBuilder.Pooling = True

        cmbServer.DataSource = _sqlServers
        Dim selected = (From server In _sqlServers Where server.ToString().Equals(_sBuilder.DataSource) Select server).FirstOrDefault()
        cmbServer.SelectedItem = If(selected IsNot Nothing, selected, _sqlServers.First())

        If Not String.IsNullOrEmpty(_sBuilder.UserID) Then
            cmbAuthentication.SelectedValue = AuthenticationMethod.Sql
            tbUser.Text = _sBuilder.UserID
        End If

        If Not String.IsNullOrEmpty(_sBuilder.Password) Then
            cmbAuthentication.SelectedValue = AuthenticationMethod.Sql
            tbPassword.Text = _sBuilder.Password
        End If
    End Sub

    Private Sub OnSelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbAuthentication.SelectedIndexChanged, cmbServer.SelectedIndexChanged
        If TypeOf sender Is ComboBox Then
            Dim cmb = DirectCast(sender, ComboBox)
            If cmb.Equals(cmbAuthentication) Then
                If cmb.SelectedItem IsNot Nothing Then
                    lblUser.Enabled = (CType(cmb.SelectedValue, AuthenticationMethod) = AuthenticationMethod.Sql)
                    tbUser.Enabled = (CType(cmb.SelectedValue, AuthenticationMethod) = AuthenticationMethod.Sql)
                    lblPassword.Enabled = (CType(cmb.SelectedValue, AuthenticationMethod) = AuthenticationMethod.Sql)
                    tbPassword.Enabled = (CType(cmb.SelectedValue, AuthenticationMethod) = AuthenticationMethod.Sql)
                End If
            ElseIf cmb.Equals(cmbServer) Then
                cmbDataBase.DataSource = CType(cmb.SelectedItem, SqlServerInfo).Catalogs
                If CType(cmb.SelectedItem, SqlServerInfo).Catalogs.Contains(_sBuilder.InitialCatalog) Then
                    Dim selected = (From catalog In CType(cmb.SelectedItem, SqlServerInfo).Catalogs Where catalog.Equals(_sBuilder.InitialCatalog)).FirstOrDefault()
                    cmbDataBase.SelectedItem = selected
                End If
            End If
        End If
    End Sub

    Private Function ValidateFormData() As Boolean
        If String.IsNullOrEmpty(cmbServer.Text) Then
            MessageBox.Show("The server or host name is required.", "Missing server or host name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            cmbServer.Focus()
            Return False
        End If

        If String.IsNullOrEmpty(cmbDataBase.Text) Then
            MessageBox.Show("The database name is required.", "Missing database name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            cmbDataBase.Focus()
            Return False
        End If

        If CType(cmbAuthentication.SelectedValue, AuthenticationMethod) = AuthenticationMethod.Sql AndAlso String.IsNullOrEmpty(tbUser.Text) Then
            MessageBox.Show("The user name is required for SQL server authentication.", "Missing user name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            tbUser.Focus()
            Return False
        End If
        Return True
    End Function
End Class

Open in new window


LocateDatabase.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class LocateDatabase
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()>
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()>
    Private Sub InitializeComponent()
        Me.lblInfo = New System.Windows.Forms.Label()
        Me.lblServer = New System.Windows.Forms.Label()
        Me.cmbServer = New System.Windows.Forms.ComboBox()
        Me.lblDataBase = New System.Windows.Forms.Label()
        Me.cmbDataBase = New System.Windows.Forms.ComboBox()
        Me.lblAuthentication = New System.Windows.Forms.Label()
        Me.cmbAuthentication = New System.Windows.Forms.ComboBox()
        Me.lblUser = New System.Windows.Forms.Label()
        Me.tbUser = New System.Windows.Forms.TextBox()
        Me.tbPassword = New System.Windows.Forms.TextBox()
        Me.lblPassword = New System.Windows.Forms.Label()
        Me.btnOK = New System.Windows.Forms.Button()
        Me.btnCancel = New System.Windows.Forms.Button()
        Me.cmbType = New System.Windows.Forms.ComboBox()
        Me.lblType = New System.Windows.Forms.Label()
        Me.SuspendLayout()
        '
        'lblInfo
        '
        Me.lblInfo.BackColor = System.Drawing.SystemColors.Control
        Me.lblInfo.ForeColor = System.Drawing.Color.Black
        Me.lblInfo.Location = New System.Drawing.Point(0, 0)
        Me.lblInfo.Name = "lblInfo"
        Me.lblInfo.Size = New System.Drawing.Size(344, 38)
        Me.lblInfo.TabIndex = 0
        Me.lblInfo.Text = "This form will build a connection string to the chosen SQL Server.  The returned " &
    "connection string can be an Entity Type."
        '
        'lblServer
        '
        Me.lblServer.AutoSize = True
        Me.lblServer.BackColor = System.Drawing.SystemColors.Control
        Me.lblServer.ForeColor = System.Drawing.Color.Black
        Me.lblServer.Location = New System.Drawing.Point(64, 79)
        Me.lblServer.Name = "lblServer"
        Me.lblServer.Size = New System.Drawing.Size(74, 13)
        Me.lblServer.TabIndex = 3
        Me.lblServer.Text = "&Server / Host:"
        '
        'cmbServer
        '
        Me.cmbServer.ForeColor = System.Drawing.Color.Black
        Me.cmbServer.Location = New System.Drawing.Point(144, 76)
        Me.cmbServer.Name = "cmbServer"
        Me.cmbServer.Size = New System.Drawing.Size(208, 21)
        Me.cmbServer.TabIndex = 4
        '
        'lblDataBase
        '
        Me.lblDataBase.AutoSize = True
        Me.lblDataBase.BackColor = System.Drawing.SystemColors.Control
        Me.lblDataBase.ForeColor = System.Drawing.Color.Black
        Me.lblDataBase.Location = New System.Drawing.Point(51, 103)
        Me.lblDataBase.Name = "lblDataBase"
        Me.lblDataBase.Size = New System.Drawing.Size(87, 13)
        Me.lblDataBase.TabIndex = 5
        Me.lblDataBase.Text = "&Database Name:"
        '
        'cmbDataBase
        '
        Me.cmbDataBase.ForeColor = System.Drawing.Color.Black
        Me.cmbDataBase.Location = New System.Drawing.Point(144, 100)
        Me.cmbDataBase.MaxLength = 255
        Me.cmbDataBase.Name = "cmbDataBase"
        Me.cmbDataBase.Size = New System.Drawing.Size(208, 21)
        Me.cmbDataBase.TabIndex = 6
        '
        'lblAuthentication
        '
        Me.lblAuthentication.AutoSize = True
        Me.lblAuthentication.BackColor = System.Drawing.SystemColors.Control
        Me.lblAuthentication.ForeColor = System.Drawing.Color.Black
        Me.lblAuthentication.Location = New System.Drawing.Point(60, 127)
        Me.lblAuthentication.Name = "lblAuthentication"
        Me.lblAuthentication.Size = New System.Drawing.Size(75, 13)
        Me.lblAuthentication.TabIndex = 7
        Me.lblAuthentication.Text = "&Authentication"
        '
        'cmbAuthentication
        '
        Me.cmbAuthentication.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
        Me.cmbAuthentication.ForeColor = System.Drawing.Color.Black
        Me.cmbAuthentication.Location = New System.Drawing.Point(144, 124)
        Me.cmbAuthentication.Name = "cmbAuthentication"
        Me.cmbAuthentication.Size = New System.Drawing.Size(208, 21)
        Me.cmbAuthentication.TabIndex = 8
        '
        'lblUser
        '
        Me.lblUser.AutoSize = True
        Me.lblUser.BackColor = System.Drawing.SystemColors.Control
        Me.lblUser.Enabled = False
        Me.lblUser.ForeColor = System.Drawing.Color.Black
        Me.lblUser.Location = New System.Drawing.Point(92, 151)
        Me.lblUser.Name = "lblUser"
        Me.lblUser.Size = New System.Drawing.Size(46, 13)
        Me.lblUser.TabIndex = 9
        Me.lblUser.Text = "&User ID:"
        '
        'tbUser
        '
        Me.tbUser.BackColor = System.Drawing.Color.White
        Me.tbUser.Enabled = False
        Me.tbUser.ForeColor = System.Drawing.Color.Black
        Me.tbUser.Location = New System.Drawing.Point(144, 148)
        Me.tbUser.MaxLength = 255
        Me.tbUser.Name = "tbUser"
        Me.tbUser.Size = New System.Drawing.Size(208, 20)
        Me.tbUser.TabIndex = 10
        '
        'tbPassword
        '
        Me.tbPassword.BackColor = System.Drawing.Color.White
        Me.tbPassword.Enabled = False
        Me.tbPassword.ForeColor = System.Drawing.Color.Black
        Me.tbPassword.Location = New System.Drawing.Point(144, 172)
        Me.tbPassword.MaxLength = 255
        Me.tbPassword.Name = "tbPassword"
        Me.tbPassword.Size = New System.Drawing.Size(208, 20)
        Me.tbPassword.TabIndex = 12
        '
        'lblPassword
        '
        Me.lblPassword.AutoSize = True
        Me.lblPassword.BackColor = System.Drawing.SystemColors.Control
        Me.lblPassword.Enabled = False
        Me.lblPassword.ForeColor = System.Drawing.Color.Black
        Me.lblPassword.Location = New System.Drawing.Point(82, 175)
        Me.lblPassword.Name = "lblPassword"
        Me.lblPassword.Size = New System.Drawing.Size(53, 13)
        Me.lblPassword.TabIndex = 11
        Me.lblPassword.Text = "&Password"
        '
        'btnOK
        '
        Me.btnOK.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton
        Me.btnOK.Location = New System.Drawing.Point(184, 204)
        Me.btnOK.Name = "btnOK"
        Me.btnOK.Size = New System.Drawing.Size(80, 24)
        Me.btnOK.TabIndex = 13
        Me.btnOK.Text = "OK"
        '
        'btnCancel
        '
        Me.btnCancel.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton
        Me.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.btnCancel.Location = New System.Drawing.Point(272, 204)
        Me.btnCancel.Name = "btnCancel"
        Me.btnCancel.Size = New System.Drawing.Size(80, 24)
        Me.btnCancel.TabIndex = 14
        Me.btnCancel.Text = "Cancel"
        '
        'cmbType
        '
        Me.cmbType.ForeColor = System.Drawing.Color.Black
        Me.cmbType.Location = New System.Drawing.Point(144, 49)
        Me.cmbType.Name = "cmbType"
        Me.cmbType.Size = New System.Drawing.Size(208, 21)
        Me.cmbType.TabIndex = 2
        '
        'lblType
        '
        Me.lblType.AutoSize = True
        Me.lblType.BackColor = System.Drawing.SystemColors.Control
        Me.lblType.ForeColor = System.Drawing.Color.Black
        Me.lblType.Location = New System.Drawing.Point(8, 52)
        Me.lblType.Name = "lblType"
        Me.lblType.Size = New System.Drawing.Size(130, 13)
        Me.lblType.TabIndex = 1
        Me.lblType.Text = "&Type of connection string:"
        '
        'LocateDatabase
        '
        Me.AcceptButton = Me.btnOK
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(363, 240)
        Me.ControlBox = False
        Me.Controls.Add(Me.btnCancel)
        Me.Controls.Add(Me.btnOK)
        Me.Controls.Add(Me.tbPassword)
        Me.Controls.Add(Me.lblPassword)
        Me.Controls.Add(Me.tbUser)
        Me.Controls.Add(Me.lblUser)
        Me.Controls.Add(Me.cmbAuthentication)
        Me.Controls.Add(Me.lblAuthentication)
        Me.Controls.Add(Me.cmbDataBase)
        Me.Controls.Add(Me.lblDataBase)
        Me.Controls.Add(Me.cmbServer)
        Me.Controls.Add(Me.lblServer)
        Me.Controls.Add(Me.cmbType)
        Me.Controls.Add(Me.lblType)
        Me.Controls.Add(Me.lblInfo)
        Me.DoubleBuffered = True
        Me.KeyPreview = True
        Me.Name = "LocateDatabase"
        Me.ShowInTaskbar = False
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "Locate Database"
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub

    Friend WithEvents lblInfo As Label
    Friend WithEvents lblType As Label
    Friend WithEvents cmbType As ComboBox
    Friend WithEvents lblServer As Label
    Friend WithEvents cmbServer As ComboBox
    Friend WithEvents lblDataBase As Label
    Friend WithEvents cmbDataBase As ComboBox
    Friend WithEvents lblAuthentication As Label
    Friend WithEvents cmbAuthentication As ComboBox
    Friend WithEvents lblUser As Label
    Friend WithEvents tbUser As TextBox
    Friend WithEvents lblPassword As Label
    Friend WithEvents tbPassword As TextBox
    Friend WithEvents btnOK As Button
    Friend WithEvents btnCancel As Button
End Class

Open in new window


Supporting Classes -
Enum AuthenticationMethod
    <Description("[-- Select an authentication method --]")> None = 0
    <Description("Micorosoft Windows")> Windows
    <Description("SQL Server")> Sql
End Enum

Enum ConnectionStringType
    <Description("[-- Select an connection string type --]")> None = 0
    <Description("Standard Connection String")> Standard
    <Description("Entity Connection String")> Entity
End Enum

Module Extensions
    <Extension()>
    Public Sub ForEach(Of T)(source As IEnumerable(Of T), action As Action(Of T))
        If source Is Nothing Then Throw New ArgumentException("source")
        If action Is Nothing Then Throw New ArgumentException("action")
        source.ToList().ForEach(action)
    End Sub

    <Extension()>
    Public Function GetDescription(value As [Enum]) As String
        Dim field As FieldInfo = value.GetType().GetField(value.ToString())
        Dim attributes As DescriptionAttribute() = CType(field.GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute())
        Return If(attributes.Length > 0, attributes(0).Description, value.ToString())
    End Function
End Module

Class ListItem(Of T)
    Public Shared Function BuildProfile(ParamArray items() As T) As Dictionary(Of String, T)
        Dim profiles As Dictionary(Of String, T) = New Dictionary(Of String, T)()
        If items IsNot Nothing Then
            For i = 0 To items.Length - 1 Step 2
                profiles.Add(items(i).ToString(), items(i + 1))
            Next
        End If
        Return profiles
    End Function

    Public Shared Function GetColumnValue(row As DataRow, column As Object)
        Dim value As T = Nothing
        If (column IsNot Nothing AndAlso row IsNot Nothing) Then
            If (column.GetType() = GetType(Integer)) Then
                value = If(row.IsNull(CType(column, Integer)), New Integer(), CType(row(CType(column, Integer)), T))
            ElseIf (column.GetType() = GetType(String)) Then
                value = If(row.IsNull(CType(column, String)), String.Empty, CType(row(CType(column, String)), T))
            ElseIf (column.GetType() = GetType(DataColumn)) Then
                value = If(row.IsNull(CType(column, DataColumn)), Nothing, CType(row(CType(column, DataColumn)), T))
            End If
        End If
        Return value
    End Function

    Public Shared Function GetListItemsFromEnum(source As Type, Optional includeDefault As Boolean = False, Optional defaultLabel As String = "",
                                                Optional defaultValue As Object = Nothing) As List(Of ListItem(Of T))
        Dim items As List(Of ListItem(Of T)) = New List(Of ListItem(Of T))()
        If (source.IsEnum) Then
            If (includeDefault) Then items.Add(New ListItem(Of T)(defaultLabel, defaultValue) With {.Description = CType(defaultValue, [Enum]).GetDescription()})
            Dim values = From value In [Enum].GetValues(GetType(T)) Select value
            values.ForEach(Sub(x)
                               items.Add(New ListItem(Of T)(x.ToString(), x) With {.Description = DirectCast(x, [Enum]).GetDescription()})
                           End Sub)
        End If
        Return items
    End Function

    Public Shared Function GetListItemsFromProfile(profiles As IDictionary(Of String, T)) As List(Of ListItem(Of T))
        Dim items As List(Of ListItem(Of T)) = New List(Of ListItem(Of T))()
        For Each pair As KeyValuePair(Of String, T) In profiles
            items.Add(New ListItem(Of T)(pair.Key, pair.Value))
        Next
        Return items
    End Function

    Public Shared Function GetListItemFromRow(row As DataRow, label As Object, value As Object)
        Dim _label As String = GetColumnValue(row, label).ToString()
        Dim _value As T = GetColumnValue(row, value)
        Return New ListItem(Of T)(If(_label IsNot Nothing, _label, ""), _value)
    End Function

    Public Shared Function GetListItemFromRow(rows As DataRow, format As String, columns As Object(), value As Object)
        Dim args As Object() = New Object(columns.Length)() {}
        Dim _label As String = ""
        Dim _value As T = GetColumnValue(rows, value)
        For i = 0 To columns.Length
            args(i) = GetColumnValue(rows, columns(i))
        Next
        _label = String.Format(format, args)
        Return New ListItem(Of T)(_label, _value)
    End Function

    Public Shared Function GetListItemsFromRows(rows As IEnumerable(Of DataRow), label As Object, value As Object, Optional includeDefault As Boolean = False,
                                                 Optional defaultLabel As String = "", Optional defaultValue As T = Nothing) As List(Of ListItem(Of T))
        Dim items As List(Of ListItem(Of T)) = New List(Of ListItem(Of T))()
        If (includeDefault) Then items.Add(New ListItem(Of T)(defaultLabel, defaultValue))
        For Each row As DataRow In rows
            items.Add(GetListItemFromRow(row, label, value))
        Next
        Return items
    End Function

    Public Shared Function GetListItemsFromRows(rows As IEnumerable(Of DataRow), format As String, columns As Object(), value As Object, Optional includeDefault As Boolean = False,
                                                 Optional defaultLabel As String = "", Optional defaultValue As T = Nothing) As List(Of ListItem(Of T))
        Dim items As List(Of ListItem(Of T)) = New List(Of ListItem(Of T))()
        If (includeDefault) Then items.Add(New ListItem(Of T)(defaultLabel, defaultValue))
        For Each row As DataRow In rows
            items.Add(GetListItemFromRow(row, format, columns, value))
        Next
        Return items
    End Function

    Public Shared Function GetListItemsFromTable(table As DataTable, label As Object, value As Object, Optional includeDefault As Boolean = False,
                                                 Optional defaultLabel As String = "", Optional defaultValue As T = Nothing) As List(Of ListItem(Of T))
        Dim items As List(Of ListItem(Of T)) = New List(Of ListItem(Of T))()
        If (includeDefault) Then items.Add(New ListItem(Of T)(defaultLabel, defaultValue))
        For Each row As DataRow In table.Rows
            items.Add(GetListItemFromRow(row, label, value))
        Next
        Return items
    End Function

    Public Shared Function GetListItemsFromTable(table As DataTable, format As String, columns As Object(), value As Object, Optional includeDefault As Boolean = False,
                                                 Optional defaultLabel As String = "", Optional defaultValue As T = Nothing) As List(Of ListItem(Of T))
        Dim items As List(Of ListItem(Of T)) = New List(Of ListItem(Of T))()
        If (includeDefault) Then items.Add(New ListItem(Of T)(defaultLabel, defaultValue))
        For Each row As DataRow In table.Rows
            items.Add(GetListItemFromRow(row, format, columns, value))
        Next
        Return items
    End Function

    Public Shared Function GetProfileFromListItems(items As List(Of ListItem(Of T))) As Dictionary(Of String, T)
        Dim profiles As Dictionary(Of String, T) = New Dictionary(Of String, T)()
        For Each item As ListItem(Of T) In items
            profiles.Add(item.Label, item.Value)
        Next
        Return profiles
    End Function

    Public Property Description() As String
    Public Property Label() As String
    Public Property SelectionId() As Integer
    Public Property Value() As T

    Public Sub New()
        Me.New("", Nothing)
    End Sub

    Public Sub New(Optional label As String = "", Optional value As T = Nothing)
        Me.Label = label
        Me.Value = value
    End Sub

    Public Overrides Function ToString() As String
        Return Label
    End Function
End Class

Module NativeMethods
    Public Const DEFAULT_RESULT_SIZE As Short = 1024
    Public Const SQL_HANDLE_DBC As Short = 2
    Public Const SQL_HANDLE_ENV As Short = 1
    Public Const SQL_NEED_DATA As Short = 99
    Public Const SQL_SUCCESS As Short = 0
    Public Const SQL_ATTR_ODBC_VERSION As Integer = 200
    Public Const SQL_OV_ODBC3 As Integer = 3
    Public Const SQL_DRIVER_STR As String = "DRIVER=SQL SERVER"

    <DllImport("odbc32.dll")>
    Public Function SQLAllocHandle(handleType As Short, inputHandle As IntPtr, ByRef outputHandlePtr As IntPtr) As Short
    End Function
    <DllImport("odbc32.dll", CharSet:=CharSet.Ansi)>
    Public Function SQLBrowseConnect(handleConnection As IntPtr, inConnection As StringBuilder, stringLength As Short, outConnection As StringBuilder, bufferLength As Short, ByRef stringLength2Ptr As Short) As Short
    End Function
    <DllImport("odbc32.dll")>
    Public Function SQLFreeHandle(hType As Short, Handle As IntPtr) As Short
    End Function
    <DllImport("odbc32.dll")>
    Public Function SQLSetEnvAttr(environmentHandle As IntPtr, attribute As Integer, valuePtr As IntPtr, stringLength As Integer) As Short
    End Function
End Module

Class SqlServerInfo
#Region "Fields"
    Private ReadOnly _serverName As String
    Private ReadOnly _instanceName As String
    Private ReadOnly _isClustered As Boolean
    Private ReadOnly _version As String
    Private ReadOnly _tcpPort As Integer
    Private ReadOnly _namedPipe As String
    Private ReadOnly _rpc As String
    Private ReadOnly _ip As IPAddress
    Private _catalogs As List(Of String)
    Private _userId As String
    Private _password As String
    Private _integratedSecurity As Boolean = True
    Private _timeOut As Integer = 2
#End Region

#Region "Constructors"
    ''' <summary>Initializes a new instance of the <see cref="SqlServerInfo"/> class.</summary>
    Private Sub New()
    End Sub

    Private Sub New(serverName As String, Optional instanceName As String = Nothing)
        _serverName = serverName
        _instanceName = instanceName
    End Sub

    ''' <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 Sub New(ip As IPAddress, info As Byte())
        Me.New(ip, ASCIIEncoding.ASCII.GetString(info, 3, BitConverter.ToInt16(info, 1)))
    End Sub

    ''' <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 Sub New(ip As IPAddress, info As String)
        _ip = ip
        Dim nvs As String() = info.Split(";"c)
        For i As Integer = 0 To nvs.Length - 1 Step 2
            Select Case nvs(i).ToLower()
                Case "servername"
                    _serverName = nvs(i + 1)
                    Exit Select
                Case "instancename"
                    _instanceName = nvs(i + 1)
                    Exit Select
                Case "isclustered"
                    _isClustered = (nvs(i + 1).ToLower() = "yes")
                    Exit Select
                Case "version"
                    _version = nvs(i + 1)
                    Exit Select
                Case "tcp"
                    _tcpPort = Integer.Parse(nvs(i + 1))
                    Exit Select
                Case "np"
                    _namedPipe = nvs(i + 1)
                    Exit Select
                Case "rpc"
                    _rpc = nvs(i + 1)
                    Exit Select
            End Select
        Next
    End Sub
#End Region

#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 ReadOnly Property Address() As IPAddress
        Get
            Return _ip
        End Get
    End Property
    ''' <summary>Gets the name of the server.</summary>
    ''' <value>The name of the server.</value>
    Public ReadOnly Property ServerName() As String
        Get
            Return _serverName
        End Get
    End Property
    ''' <summary>Gets the name of the instance.</summary>
    ''' <value>The name of the instance.</value>
    Public ReadOnly Property InstanceName() As String
        Get
            Return _instanceName
        End Get
    End Property
    ''' <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 ReadOnly Property IsClustered() As Boolean
        Get
            Return _isClustered
        End Get
    End Property
    ''' <summary>Gets the version.</summary>
    ''' <value>The version.</value>
    Public ReadOnly Property Version() As String
        Get
            Return _version
        End Get
    End Property
    ''' <summary>Gets the TCP port.</summary>
    ''' <value>The TCP port.</value>
    Public ReadOnly Property TcpPort() As Integer
        Get
            Return _tcpPort
        End Get
    End Property
    ''' <summary>Gets the named pipe.</summary>
    ''' <value>The named pipe.</value>
    Public ReadOnly Property NamedPipe() As String
        Get
            Return _namedPipe
        End Get
    End Property
    ''' <summary>Gets the catalogs.</summary>
    ''' <value>The catalogs.</value>
    Public ReadOnly Property Catalogs() As List(Of String)
        Get
            If _catalogs Is Nothing Then
                _catalogs = GetCatalogs()
            End If
            Return _catalogs
        End Get
    End Property
    ''' <summary>Gets or sets the user id.</summary>
    ''' <value>The user id.</value>
    Public Property UserId() As String
        Get
            Return _userId
        End Get
        Set
            _userId = Value
            _integratedSecurity = False
        End Set
    End Property
    ''' <summary>Gets or sets the password.</summary>
    ''' <value>The password.</value>
    Public Property Password() As String
        Get
            Return _password
        End Get
        Set
            _password = Value
            _integratedSecurity = False
        End Set
    End Property
    ''' <summary>Gets or sets a value indicating whether [integrated security].</summary>
    ''' <value><see langword="true"/> if [integrated security]; otherwise, <see langword="false"/>.</value>
    Public Property IntegratedSecurity() As Boolean
        Get
            Return _integratedSecurity
        End Get
        Set
            _integratedSecurity = Value
        End Set
    End Property
    ''' <summary>Gets or sets the time out.</summary>
    ''' <value>The time out.</value>
    Public Property TimeOut() As Integer
        Get
            Return _timeOut
        End Get
        Set
            _timeOut = Value
        End Set
    End Property
#End Region

#Region "Public Methods"
    ''' <summary>Tests the connection.</summary>
    Public Function TestConnection() As Boolean
        Dim conn As OleDbConnection = GetConnection()
        Dim success As Boolean = False
        Try
            conn.Open()
            conn.Close()
            success = True
        Catch ex As Exception
            MessageBox.Show(String.Format("Exception reported in {0} - {1} [{2}]", ex.Source, ex, ex.Message), "Exception Reported!!!", MessageBoxButtons.OK, MessageBoxIcon.[Error])
        End Try
        Return success
    End Function
    ''' <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 Overrides Function ToString() As String
        Return If(InstanceName Is Nothing OrElse InstanceName = "MSSQLSERVER", ServerName, String.Format("{0}\{1}", ServerName, InstanceName))
    End Function
#End Region

#Region "Private Methods"
    Private Function GetCatalogs() As List(Of String)
        Dim catalogs As New List(Of String)()

        Try
            Dim myConnection As OleDbConnection = GetConnection()
            myConnection.Open()
            Dim schemaTable As DataTable = myConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Catalogs, Nothing)
            myConnection.Close()
            For Each dr As DataRow In schemaTable.Rows
                catalogs.Add(TryCast(dr(0), String))
            Next
            ' An exception here means that the catalogs could not be retrieved 

        Catch generatedExceptionName As Exception
        End Try
        Return catalogs
    End Function

    Private Function GetConnection() As OleDbConnection
        Dim myConnString As String = If(IntegratedSecurity, String.Format("Provider=SQLOLEDB;Data Source={0};Integrated Security=SSPI;Connect Timeout={1}", Me, TimeOut), String.Format("Provider=SQLOLEDB;Data Source={0};User Id={1};Password={2};Connect Timeout={3}", Me, UserId, Password, TimeOut))
        Return New OleDbConnection(myConnString)
    End Function
#End Region

#Region "Public Static Method - Seek"
    Public Shared Function GetSqlServers() As List(Of SqlServerInfo)
        Dim results As New List(Of SqlServerInfo)()
        Dim instances As String = String.Empty
        Dim henv As IntPtr = IntPtr.Zero
        Dim hconn As IntPtr = IntPtr.Zero
        Dim inString As New StringBuilder(NativeMethods.SQL_DRIVER_STR)
        Dim outString As New StringBuilder(NativeMethods.DEFAULT_RESULT_SIZE)
        Dim inStringLength As Short = CShort(inString.Length)
        Dim lenNeeded As Short = 0

        Try
            If NativeMethods.SQL_SUCCESS = NativeMethods.SQLAllocHandle(NativeMethods.SQL_HANDLE_ENV, henv, henv) Then
                If NativeMethods.SQL_SUCCESS = NativeMethods.SQLSetEnvAttr(henv, NativeMethods.SQL_ATTR_ODBC_VERSION, New IntPtr(NativeMethods.SQL_OV_ODBC3), 0) Then
                    If NativeMethods.SQL_SUCCESS = NativeMethods.SQLAllocHandle(NativeMethods.SQL_HANDLE_DBC, henv, hconn) Then
                        If NativeMethods.SQL_NEED_DATA = NativeMethods.SQLBrowseConnect(hconn, inString, inStringLength, outString, NativeMethods.DEFAULT_RESULT_SIZE, lenNeeded) Then
                            If NativeMethods.DEFAULT_RESULT_SIZE < lenNeeded Then
                                outString.Capacity = lenNeeded
                                If NativeMethods.SQL_NEED_DATA <> NativeMethods.SQLBrowseConnect(hconn, inString, inStringLength, outString, lenNeeded, lenNeeded) Then
                                    Throw New ApplicationException("Unabled to aquire SQL Servers from ODBC driver.")
                                End If
                            End If
                            instances = outString.ToString()
                            Dim start As Integer = instances.IndexOf("{") + 1
                            Dim len As Integer = instances.IndexOf("}") - start
                            instances = If((start > 0) AndAlso (len > 0), instances.Substring(start, len), String.Empty)
                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            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 Then
                NativeMethods.SQLFreeHandle(NativeMethods.SQL_HANDLE_DBC, hconn)
            End If

            If henv <> IntPtr.Zero Then
                NativeMethods.SQLFreeHandle(NativeMethods.SQL_HANDLE_ENV, henv)
            End If
        End Try

        If instances.Length > 0 Then
            For Each instance As String In instances.Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries)
                Dim pair As String() = instance.Split("\"c)
                If pair.Count() < 2 Then
                    results.Add(New SqlServerInfo(pair(0)))
                Else
                    results.Add(New SqlServerInfo(pair(0), If(pair(1), Nothing)))
                End If
            Next
        End If
        Return results
    End Function

    ''' <summary>Seeks SQL servers on this network.</summary>
    ''' <returns>An array of SqlServerInfo objects describing Sql Servers on this network</returns>
    Public Shared Function Seek() As SqlServerInfo()
        Dim socket As 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

        Dim servers As New ArrayList()
        Try
            Dim msg As Byte() = New Byte() {&H2}
            Dim ep As New IPEndPoint(IPAddress.Broadcast, 1434)
            socket.SendTo(msg, ep)

            Dim cnt As Integer = 0
            Dim bytBuffer As Byte() = New Byte(1023) {}
            Do
                cnt = socket.Receive(bytBuffer)
                servers.Add(New SqlServerInfo(Nothing, bytBuffer))
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 300)
            Loop While cnt <> 0
        Catch socex As SocketException
            Const WSAETIMEDOUT As Integer = 10060
            ' Connection timed out.
            Const WSAEHOSTUNREACH As Integer = 10065
            ' No route to host.
            ' Re-throw if it's not a timeout.
            ' DO nothing......
            If socex.ErrorCode = WSAETIMEDOUT OrElse socex.ErrorCode = WSAEHOSTUNREACH Then
            Else
                Throw
            End If
        Finally
            socket.Close()
        End Try

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

        Dim aServers As SqlServerInfo() = New SqlServerInfo(servers.Count - 1) {}
        servers.CopyTo(aServers)
        Return aServers
    End Function
#End Region
End Class

Open in new window


Which produces the following dialog form -User generated imageThe 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).

The ConnectionString Property contains the string that would be placed inside of your app.config.

-saige-
some good info were provided. do you need any further assistance here?
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.