I am trying to write a very simple C# Script that establishes a connection to my Azure SQL Database.
using System;
using System.Data.SqlClient;
namespace first_project
{
class MainClass
{
public static void Main(string[] args)
{
var cb = new SqlConnectionStringBuilder();
cb.DataSource = "server.bloo.blah.foobar";
cb.UserID = "user#database";
cb.Password = "secret";
cb.InitialCatalog = "database";
using (SqlConnection connection = new SqlConnection(cb.ConnectionString))
{
try
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
}
From what I have gathered online, this code should be working? However, I am getting the following error
System.AggregateException: One or more errors occurred. ---> System.IO.IOException: Unable to read data from the transport connection: Operation on non-blocking socket would block. ---> System.Net.Sockets.SocketException: Operation on non-blocking socket would block
Could anyone enlighten me on what is going on? Thanks in advance.
First the SQL database has a firewall. You have to add your IP through the azure portal.
Secondly make sure your connection string is correct you can look at another sample online. I remember having syntax errors as well, just copy the string that azure gives you.
In your connection, instead of
cb.UserID = "user#database"
use
cb.UserID = "user"
That should work.
Related
I've got an issue where I cannot connect to an on-premises SQL database through an Azure function app once it is published to Azure. However when I run it locally in Visual Studio Code, it works perfectly.
The purpose of the Function is to resize images that are stored in Azure blob storage to a thumbnail and store it in a table field <varbinary(max)>.
Here is the error message I get:
2020-12-15T15:33:52.058 [Information] 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. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
2020-12-15T15:33:52.093 [Error] Executed 'BlobTrigger_MQS_Resize' (Failed, Id=346672c6-820c-43f6-b950-d5059e44697e, Duration=19570ms)
Access is denied.
I'm connecting to the SQL database via SQL Login, which works perfectly. Connection String is in local.settings.json:
{
"IsEncrypted": false,
"Values": {
...,
"Connection_SQL_Database_MQS": "Data Source=MyServer;Initial Catalog=MyDB;User ID=MyUser;Password=MyPassword;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
}
}
The code (in C#) which I have simplified a bit to the core of the issue:
public static class BlobTrigger_MQS_Resize
{
[FunctionName("BlobTrigger_MQS_Resize")]
public static async Task Run([BlobTrigger("mqs-media/{name}", Connection = "hqdevstorage_STORAGE")]Stream input, string name, ILogger log)
{
log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {input.Length} Bytes");
try
{
var connectionString = Environment.GetEnvironmentVariable("Connection_SQL_Database_MQS", EnvironmentVariableTarget.Process);
using (var output = new MemoryStream())
using (Image<Rgba32> image = Image.Load(input))
using (SqlConnection conn = new SqlConnection(connectionString))
{
// Code that resizes images to 'output', this works also when published
image.Resize(...);
image.Save(output, encoder);
//PROBLEM IS HERE: Write resized image to SQL Database
conn.Open();
var query = "UPDATE dbo.MyTable"
+ " SET Blob = #output"
+ " WHERE File_Name = '" + name + "'";
using(SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#output", output);
var rows = await cmd.ExecuteNonQueryAsync();
log.LogInformation($"{rows} rows were updated");
}
}
}
catch (Exception ex)
{
log.LogInformation(ex.Message);
throw;
}
}
}
Can someone help me with this? I have no clue why it is working locally but not on Azure.
The server was not found or was not accessible.
This is a network connectivity issue, not a permissions issue. The Azure function cannot resolve your SQL Server's hostname into an IP address, and would not be able to connect to that IP address if it could.
Your function would need to access to an on-prem conected VNet or use a Hybrid Connection to reach your on-prem SQL Server.
see
https://learn.microsoft.com/en-us/azure/app-service/app-service-hybrid-connections
and
https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-vnet
This question already has answers here:
ASP.NET use SqlConnection connect MySQL
(3 answers)
Closed 2 years ago.
I am trying to connect to MySQL server
Screenshot from MySQL Workbench:
using System;
using System.Data.SqlClient;
namespace C_sharp_test
{
class Program
{
static void Main(string[] args)
{
try
{
string connectionString = "server=localhost;uid=root;pwd=***********;database=terra_incognita_online";
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = connectionString;
sqlConnection.Open();
Console.WriteLine("open");
sqlConnection.Close();
Console.WriteLine("close");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}
I get this error
System.Data.SqlClient.SqlException (0x80131904): 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. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I have no idea what to do, please help
Replace "SqlConnection" with "MySqlConnection" and that will work.
namespace C_sharp_test
{
class Program
{
static void Main(string[] args)
{
try
{
string connectionString = "server=localhost;uid=root;pwd=***********;database=terra_incognita_online";
MySqlConnection sqlConnection = new MySqlConnection();
sqlConnection.ConnectionString = connectionString;
sqlConnection.Open();
Console.WriteLine("open");
sqlConnection.Close();
Console.WriteLine("close");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}
Also, Install nuget package MySql.Data;
And Add Reference
using MySql.Data.MySqlClient;
You are trying to connect to a MySQL database server with classes intended for SQL Server. They use different protocols, so that doesn't work (and almost certainly never will).
Have a look at the MySQL connector for .NET, if you want to use MySQL rather than SQL Server.
when i tried to run this program in visual studio 2010 its shows an error. Like this "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.(provider:Named pipes Provider,error:40-could not open a connection to SQL Server)"
public partial class tcregistration : Form
{
SqlConnection conn = new SqlConnection("Data Source=./SQLEXPRESS;AttachDbFilename=C:/Users/dce 3/documents/visual studio 2010/Projects/TC_Maker/TC_Maker/TC_REG.mdf;Integrated Security=True;User Instance=True");
public tcregistration()
{
InitializeComponent();
}
private void insert_Click(object sender, EventArgs e)
{
string gender = string.Empty;
if (rbmale.Checked)
{
gender = "M";
}
else if (rbfemale.Checked)
{
gender = "F";
}
string tcrecieved = string.Empty;
if (rbyes.Checked)
{
tcrecieved = "Y";
}
else if (rbno.Checked)
{
tcrecieved = "N";
}
try
{
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlCommand cmd = new SqlCommand ("TCAddorUpdate",conn);
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#mode","Add");
cmd.Parameters.AddWithValue("#tcnumber",txttcno.Text.Trim());
cmd.Parameters.AddWithValue("#name",txtname.Text.Trim());
cmd.Parameters.AddWithValue("#dob",dtpdob);
cmd.Parameters.AddWithValue("#religion",txtrelig.Text.Trim());
cmd.Parameters.AddWithValue("#caste",txtcaste.Text.Trim());
cmd.Parameters.AddWithValue("#sex",gender);
cmd.Parameters.AddWithValue("#doa",dtpdoa);
cmd.Parameters.AddWithValue("#regno",txtregno.Text.Trim());
cmd.Parameters.AddWithValue("#dor",dtpdor);
cmd.Parameters.AddWithValue("#dept",txtdept.Text.Trim());
cmd.Parameters.AddWithValue("#sem", combosem);
cmd.Parameters.AddWithValue("#ifqulify",txtqualified.Text.Trim());
cmd.Parameters.AddWithValue("#conduct",txtconduct.Text.Trim());
cmd.Parameters.AddWithValue("#applieddate",dtpdoapp);
cmd.Parameters.AddWithValue("#ifrecieved",tcrecieved);
cmd.Parameters.AddWithValue("#receiveddate",dtpdor);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted Successfully");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Error Message");
}
finally
{
conn.Close();
}
}
}
}
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.(provider:Named pipes Provider,error:40-could not open a connection to SQL Server)
This is not a programming Problem, but a networking/connection string one.
Connection Strings are their own area of experetise, way outside the normal programmers knowledge. Luckily there is a page for it: https://www.connectionstrings.com/sql-server/
It turns out even when attaching, you have to supply a database name: "Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection."
And as others mentioned, you got the wrong kind of slashes too.
Pretty off topic, but exception handling is a pet peeve of mine. And yours has some of the serioues mistakes. Like catching exception and only exposing the message. Those are 2 Cardinal sins. Thee are two article on the thematic I link often:
https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/
https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET
I tried to test the sample provided here to use an Azure hybrid connection to connect to an on-premises SQL Server. My server has the "Hybrid Connection Manager" installed on it and I can connect to the database via Azure App Service Plan and an Azure Function.
However, I'd like to use the same hybrid connection from another machine resides on a different network using C# code. While I put the correct connection string in the "PortBridgeClientAgent" program in that example, the application is not able to connect to the on-premises SQL server. What is the correct way to establish this sort of connections outside of Azure?
This is my code:
using Microsoft.Azure.Relay;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace TestConsoleApp
{
public static class Program
{
private const string RelayNamespace = "{NameSpace}.servicebus.windows.net";
private const string ConnectionName = "{ConnectionName}";
private const string KeyName = "RootManageSharedAccessKey";
private const string Key = "{Key}";
public static void Main() => RunAsync().GetAwaiter().GetResult();
private static async Task RunAsync()
{
var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
var client = new HybridConnectionClient(new Uri($"sb://{RelayNamespace}/{ConnectionName}"), tokenProvider);
var hybridConnectionStream = await client.CreateConnectionAsync();
var connectionStringBuilder = new SqlConnectionStringBuilder
{
DataSource = "{SqlServerHostName},1433",
InitialCatalog = "{DatabaseName}",
IntegratedSecurity = false,
UserID = "{SqlLogin}",
Password = "{Password}",
};
try
{
using (var connection = new SqlConnection(connectionStringBuilder.ToString()))
{
connection.Open();
var command1 = new SqlCommand("Query", connection);
using (var dataReader = await command1.ExecuteReaderAsync())
{
var result = dataReader;
}
}
}
catch (Exception exception)
{
Console.WriteLine(exception.ToString());
}
Console.ReadLine();
await hybridConnectionStream.CloseAsync(CancellationToken.None);
}
}
}
You can read up on why this does not work in this question: Connecting to an Hybrid connection served by the Hybrid connection manager
There is more going on within app services beyond just connecting to Service Bus and asking for a SQL connection. That means that at this time it is not possible to use this to create a connection from outside App Services to your on premise servers.
I've searching for this and I thought I found the answer on here. this is the code I found to run a sql script through c#:
using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace SeleniumTest2
{
class CreateSchema
{
public void Schema_Create()
{
string sqlConnectionString = "connection string here";
FileInfo file = new FileInfo(#"filepath to script.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
//DOESNTLIKE
server.ConnectionContext.ExecuteNonQuery(script);
file.OpenText().Close();
conn.Close();
}
}
}
But I keep getting the following error:
An unhandled exception of type 'Microsoft.SqlServer.Management.Common.ExecutionFailureException' occurred in Microsoft.SqlServer.ConnectionInfo.dll
Additional information: An exception occurred while executing a Transact-SQL statement or batch.
Can anyone tell me how to overcome this error?
THANKS!!
This happened to me a couple times. After debugging, there were some errors in my script file itself. The following worked for me:
Try running your script file directly using SQL Management Studio. This can pinpoint errors in your script itself.
Break down the SQL script into smaller files. For some reason this worked for me. Split the file into smaller scripts accordingly. For my particular database creation script, I separated it into a create tables script, a populate tables script, and an add primary and foreign keys script.
My code:
/// <summary>
/// Process SQL script with "GO" statements
/// </summary>
/// <param name="script"></param>
public static void ProcessSQLScriptFile(string script)
{
try
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.SQLConDefault); // your connection string
con.Open();
Server server = new Server(new ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(script);
con.Close();
}
catch (SqlException e)
{
Console.WriteLine("SQL Exception: " + e.Message);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
Hope this helps.
You may try this method to execute sql (from msdn):
private static void ExecuteCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
If you will get an error, check exception details, check if your connection string is valid.
I had this exact same issue. What fixed it for me was to find out the actual error:
public void Schema_Create()
{
string sqlConnectionString = "connection string here";
FileInfo file = new FileInfo(#"filepath to script.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
try
{
server.ConnectionContext.ExecuteNonQuery(script);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.InnerException.Message);
}
file.OpenText().Close();
conn.Close();
}
My issue presented itself in the ex.InnerException.Message, which in my case happened to be that my script was attempting to write a column that already existed on the table (column names must be unique for a given table).
Change the database path to another drive
Because in c drive or in windows drive you don't have permission to create data base
If change the path , your solution is work successful.