Abdulsalam Elsharif
Abdulsalam Elsharif

Reputation: 5101

Checked If there is Connection to SQL Server or not in WPF

My WPF application connected to SQL Server database via a connection string in App.config and it works over local network.

I have a login screen "4 PassCode digit Login", after enter the fourth digit I checked "As usual" if true or not.

My question here how can I check if client machine has connection to the server or not? If not I want to show message.

I don't know from where should I start :(

Hope this clear. Thanks

Upvotes: 1

Views: 3957

Answers (3)

Adephx
Adephx

Reputation: 317

App.config

<add name="databaseName" connectionString="Data Source=localhost; Initial Catalog=ABC_DB; Persist Security Info=True; User ID=sa;Password=1234"/>   

Window.xaml.cs

public MainWindow()
{
    InitializeComponent();
    OpenConnection();
}

public SqlConnection con = new SqlConnection
{
    ConnectionString = ConfigurationManager.ConnectionStrings["databaseName"].ConnectionString
};

public void OpenConnection()
{
    try
    {
        con.Open();
    }
    catch (SqlException ex)
    {
        MessageBox.Show(ex.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Error);
        /// If you want the program to exit completely
        /// Environment.Exit(0);
    }
}

Additional, you can add something like this:

public void Whatever()
{
    if (con.State == ConnectionState.Open)
        {
            /// Your code
        }
    else
    {
        MessageBox.Show("Could not connect to server", "Warning", MessageBoxButton.OK, MessageBoxImage.Error);
        OpenConnection();
    }
}

Upvotes: 0

Erwin Draconis
Erwin Draconis

Reputation: 784

try this

private void ConnectToServer()
    {
        string sServerName = _fileIO.GetServerInfo("ServerName");
        string sSqlInstance = _fileIO.GetServerInfo("SqlInstance");
        string sDataBase = _fileIO.GetServerInfo("DataBase");
        string sUserID = _fileIO.GetServerInfo("UserID");
        string sPassWord = _fileIO.GetServerInfo("PassWord");
         //"Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;Password=myPassword";
        string sConnectionString = string.Format("Server={0};Database={2};User Id={3};Password={4}",
                                                sServerName,sSqlInstance,sDataBase,sUserID,sPassWord);


        try
        {
            _cnn = new SqlConnection(sConnectionString); 
            _cnn.Open();
            if (_cnn.State.ToString() != "Open")
            {
                MessageBox.Show("Application could not connect to server ","Connection Failed ",MessageBoxButton.OK,MessageBoxImage.Error);
            }
            _cnn.Close();
        }
        catch (Exception _ex)
        {
            MessageBox.Show(_ex.ToString());
        }

    }

Upvotes: 0

Oren Hizkiya
Oren Hizkiya

Reputation: 4434

You can simply check perform a check whether the client can open a connection.

Code lifted from this answer.

/// <summary>
/// Test that the server is connected
/// </summary>
/// <param name="connectionString">The connection string</param>
/// <returns>true if the connection is opened</returns>
private static bool IsServerConnected(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        try
        {
            connection.Open();
            return true;
        }
        catch (SqlException)
        {
            return false;
        }
        finally
        {
            // not really necessary
            connection.Close();
        }
    }
}

Upvotes: 3

Related Questions