question

alansmith-1564 avatar image
0 Votes"
alansmith-1564 asked ·

Connect to SQL Server database with appconfig, C#

I am trying to connect to a SQL Server database with appconfig but however I am getting the following error:

"An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll".

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.Named Pipes Provider, error: 40 - could not open connection to sql server.

Here is my code:

 SqlConnection conexion = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["conectar"].ConnectionString);


the error is happening on the line: conexion.Open();


Appconfig:

 <connectionStrings>
     <add name ="conectar" connectionString="server=servername;Integrated security=yes; Database=Base01"/>
 </connectionStrings>


the error is happening on the line: conexion.Open();





sql-server-generaldotnet-csharp
· 1
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@alansmith-1564
There are many reasons that can cause this problem, please check this link:
Resolving could not open a connection to SQL Server errors

0 Votes 0 ·
SimpleSamples avatar image
0 Votes"
SimpleSamples answered ·

Are the SQL Server services running? You can use SQL Server Configuration Manager to check.

What happens when you access the database using SQL Server Manager Studio (SSMS)? Can you see the tables using it?

Can you connect to the server using SQL Server Object Explorer in Visual Studio? If so then right-click on the database and select Properties. Look at the connection string there.




·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered ·

Try the following with your server and catalog then if it works place the connection string into your app.config. Also see ConnectionStrings.

 using System;
 using System.Data.SqlClient;
    
 public class DataOperations
 {
     public static bool TestConnection()
     {
    
         var connectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=NorthWindAzure;Integrated Security=True";
    
         using (var cn = new SqlConnection { ConnectionString = connectionString })
         {
             try
             {
                 cn.Open();
                 return true;
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.Message);
                 return false;
    
             }
    
         }
    
     }
 }

If you need to check if the server is running and available. A robust version is found here.

 using System;
 using System.Data;
 using System.Data.Sql;
 using System.Linq;
 using System.ServiceProcess;
 using System.Threading.Tasks;
    
    
 public class Utilities
 {
     /// <summary> 
     /// Determine if SQL-Server is available 
     /// </summary> 
     /// <returns></returns> 
     public async Task<bool> SqlServerIsAvailable()
     {
         bool success = false;
    
         try
         {
             await Task.Run(() =>
             {
                 SqlDataSourceEnumerator sqlDataSourceEnumeratorInstance = SqlDataSourceEnumerator.Instance;
                 DataTable dt = sqlDataSourceEnumeratorInstance.GetDataSources();
                 if (dt != null)
                 {
                     success = true;
                 }
             });
         }
         catch (Exception ex)
         {
             // ignored
         }
    
         return success;
     }
     /// <summary> 
     /// Determine if a specific SQL-Server is available 
     /// </summary> 
     /// <param name="pServerName"></param> 
     /// <returns></returns> 
     public async Task<bool> SqlServerIsAvailable(string pServerName)
     {
    
         bool success = false;
    
         try
         {
             await Task.Run(() =>
             {
                 SqlDataSourceEnumerator sqlDataSourceEnumeratorInstance = SqlDataSourceEnumerator.Instance;
                 DataTable dt = sqlDataSourceEnumeratorInstance.GetDataSources();
                 if (dt != null)
                 {
                     if (dt.Rows.Count > 0)
                     {
                         var row = dt.AsEnumerable().FirstOrDefault(r => r.Field<string>("ServerName") == pServerName.ToUpper());
                         success = row != null;
                     }
                     else
                     {
                         success = false;
                     }
                 }
             });
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
         }
    
         return success;
     }
     /// <summary>
     /// Determine if a specific service is running e.g.
     /// SQL-Server: MSSQLServer
     /// MSSQLSERVER
     /// SQL Server Agent: SQLServerAgent
     /// SQL Server Analysis Services: MSSQLServerOLAPService
     /// SQL Server Browser: SQLBrowser
     /// </summary>
     /// <param name="serviceName">Service name to find</param>
     /// <returns>True if found, false if not</returns>
     public static bool ISWindowsServiceRunning(string serviceName)
     {
         var isRunning = false;
         var services = ServiceController.GetServices().
             Where(sc => sc.ServiceName.Contains("SQL")).ToList();
    
         foreach (var service in services)
         {
             if (service.ServiceName == serviceName)
             {
                 if (service.Status == ServiceControllerStatus.Running)
                 {
                     isRunning = true;
                 }
    
             }
         }
    
         return isRunning;
     }
 }


·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

DuaneArnold-0443 avatar image
0 Votes"
DuaneArnold-0443 answered ·

Is MS SQL Server on a machine on the network, you have not configured MS SQL Server to accept remote connections and you have not fingered the firewall running on the machine to open MSSQL Server port?

·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.