Connect Azure SQL Database to .NET Project - c#

I have built a web api using dotnet and this is my first time using Azure (or any other cloud platform) to host web applications. I've used EntityFramework and MySQL database with to build my project.
I used DbConnectionString = "Server=localhost;Database=hms;Uid='{root-user}';Pwd={pw};" as the connection string of my SQL Database and now I'm wondering how can I connect it with the Azure SQL Database I have created. I added my IP address in firewall access in the Azure server and tried changing the connection string as DbConnectionString = "Server=server.database.windows.net:1433;Database=hms;Uid='{root-user}';Pwd={pw};" but it gives an error An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseMySql' call. when I'm trying to update the database after adding migrations.
I'd like to know what I have done wrong or what else I need to do in order to get this running. tyia.

I have created an Azure SQL database with one table.
Table is having data as below
3.Created Console application using C#.
Added Package Microsoft.Data.SqlClient to the Project.
Added following code in Program.cs file,
[Taking reference from here](https://learn.microsoft.com/en-us/azure/azure-sql/database/connect-query-dotnet-visual-studio?view=azuresql), I created a replica of the program.cs file as shown:
using System;
using Microsoft.Data.SqlClient;
using System.Text;
namespace sqltest
{
class Program
{
static void Main(string[] args)
{
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "yourservername.database.windows.net";
builder.UserID = "your_username";
builder.Password = "your_password";
builder.InitialCatalog = "your_database";
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
Console.WriteLine("\nQuery data example:");
Console.WriteLine("=========================================\n");
//String sql = "SELECT * FROM dbo.Persons";
String sql = "SELECT LastName, FirstName FROM dbo.Persons";
using (SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1}", reader.GetString(0), reader.GetString(1));
}
}
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
Console.ReadLine();
}
}
}
6.Using above code, I am connecting to Azure SQL and retrieving data from database.
Run the application and getting data from Azure Sql data base as shown below,
Reference links:
https://learn.microsoft.com/en-us/visualstudio/azure/azure-sql-database-add-connected-service?view=vs-2022

Related

Keyword not supported: 'authentication' error while connecting to DB through Azure AD

I am trying to connect to a SQL Server database through Azure AD from an Azure .NET Core application. I have also added Nuget packages Microsoft.Data.SqlClient. But, I am getting this error:
System.ArgumentException: Keyword not supported: 'authentication'.
at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary2 parsetable, String connectionString, Boolean buildChain, Dictionary2 synonyms, Boolean firstKey)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
This is the code that I have written:
public static void testAADConnectionDbConnect(IConfiguration config)
{
string ConnectionString = #"Server=serverName; Authentication=Active Directory Service Principal; Encrypt=True; Database=databaseName; User Id=userId; Password=Password";
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
}
}
Can I please get some help on it?
Thanks!
I was able to connect to the sql Database using the following process.
First, I created a service principle using azure active directory. Just go to active directory and click on app registration and register an app.
Also create a client secret by going in the Certificates & secrets tag and click on new client secret.
Now while creating the SQL server in azure itself, we have to add Authentication method as Use only Azure Active Directory (AzureAD) authentication and then select the admin to the app registration done previously.
Now make sure you are using the latest version of Microsoft.Data.SqlClient in the code.
Complete code :
using Microsoft.Data.SqlClient;
using System;
namespace ConsoleApp4
{
internal class Program
{
static void Main(string[] args)
{
string ConnectionString = #"Server=<ServerName>.database.windows.net; Authentication=Active Directory Service Principal; Encrypt=True; Database=<DatabaseName>; User Id=<Client/Application Id from app registation >; Password=<Client Secret created earlier >";
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
if (conn.State== System.Data.ConnectionState.Open)
{ Console.WriteLine("Connection is Working "); }
}
}
}
}

Cannot connect to Azure MySQL database from .NET Connector

I tried to connect to the Azure MySQL database using MySQL Workbench and MySQL Shell and it works fine. Now I am trying to connect using following C# code:
var connStringBuilder = new MySqlConnectionStringBuilder
{
Server = "creatur-db.mysql.database.azure.com",
Database = "test",
UserID = "creatur_db_main#creatur-db",
Password = "{my_password}",
SslMode = MySqlSslMode.Preferred,
};
using (MySqlConnection connection = new MySqlConnection(connStringBuilder.ToString()))
{
connection.Open();
connection.Close();
}
Here I replaced {my_password} with password to the database and it gives me an exception inside Open method:
MySql.Data.MySqlClient.MySqlException: 'Authentication to host
'creatur-db.mysql.database.azure.com' for user
'creatur_db_main#creatur-db' using method 'mysql_native_password'
failed with message: The connection string may not be right. Please
visit portal for references.
I also tried different connection strings:
Server=creatur-db.mysql.database.azure.com; Port=3306; Database=test; Uid=creatur_db_main#creatur-db; Pwd={my_password}; SslMode=Preferred
and
Database=test; Data Source=creatur-db.mysql.database.azure.com; User Id=creatur_db_main#creatur-db; Password={my_password}
But none of them worked.
The same exception occurs when I create new connection using Server Explorer in Visual Studio 2013. It seems the error has something to do with .NET Connector. I tried to use different versions of MySQL.Data.dll, .NET Framework and Visual Studio but no luck.
I just created a console application using VS2017 I used
Nuget package MySql.Data and .Net Framework 4.6.1
It works perfectly here What I did.
After Creating the MySQL server I used the CloudShell to connect to the SERVER (not a database).
Using this code:
mysql --host franktest.mysql.database.azure.com --user frank#franktest -p
I got an error
ERROR 9000 (HY000): Client with IP address '40.76.202.47' is not allowed to connect to this MySQL server.
So I add that IP and at the same time my IP from where I'm connected.
So once the IP were saved. I executed the previous command, and this time it worked perfectly. I created a database named: frankdemo using this command:
CREATE DATABASE frankdemo;
Then, back in VisualStudio used this code as my Main method, copied from the documentation.
static void Main(string[] args)
{
var builder = new MySqlConnectionStringBuilder
{
Server = "franktest.mysql.database.azure.com",
Database = "frankdemo",
UserID = "frank#franktest",
Password = "gr3enRay14!",
SslMode = MySqlSslMode.Required,
};
using (var conn = new MySqlConnection(builder.ConnectionString))
{
Console.WriteLine("Opening connection");
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandText = "DROP TABLE IF EXISTS inventory;";
command.ExecuteNonQuery();
Console.WriteLine("Finished dropping table (if existed)");
command.CommandText = "CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);";
command.ExecuteNonQuery();
Console.WriteLine("Finished creating table");
command.CommandText = #"INSERT INTO inventory (name, quantity) VALUES (#name1, #quantity1),
(#name2, #quantity2), (#name3, #quantity3);";
command.Parameters.AddWithValue("#name1", "banana");
command.Parameters.AddWithValue("#quantity1", 150);
command.Parameters.AddWithValue("#name2", "orange");
command.Parameters.AddWithValue("#quantity2", 154);
command.Parameters.AddWithValue("#name3", "apple");
command.Parameters.AddWithValue("#quantity3", 100);
int rowCount = command.ExecuteNonQuery();
Console.WriteLine(String.Format("Number of rows inserted={0}", rowCount));
}
// connection will be closed by the 'using' block
Console.WriteLine("Closing connection");
}
Console.WriteLine("Press RETURN to exit");
Console.ReadLine();
}
Runed it and it works
The documentation I'm referring to is:
Create an Azure Database for MySQL server by using the Azure portal
Azure Database for MySQL: Use .NET (C#) to connect and query data

C# xamarin android Unable to connect to any of the specified MySQL hosts

I am trying to make a simple app that will connect to a database and get some info. I have implented the plugin that allows xamarin app to connect remote mariaDB/MySQL to components. I am using the code below.
public void GetAccountCountFromMySQL()
{
try
{
string sql = " SELECT * FROM Kategorier";
MySqlConnection con = new MySqlConnection("Persist Security Info=False; Server=192.210.241.161; Port=3306; Database=xxxxx; Uid=xxxxx; Pwd=xxxxx;");
MySqlCommand cmd = new MySqlCommand(sql, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetString("Sko"));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I have tried many types of connection strings, also I buileded a simple C# application that connects to the very same database with no problems.
Actual problem was error from MySql "cannot resolve host name" After discussion the decision was not to use this plugin as it is not secured but create a webservice talking to MySql DB and consume it from Android app.

Connecting to mysql on 000webhost using C#

Im simply just trying to read what there is in the batabase on to a console but i always get an exception on the conn.Open() line. Here is all the code:
SqlConnectionStringBuilder conn_string = new SqlConnectionStringBuilder();
conn_string.DataSource = "mysql14.000webhost.com"; // Server
conn_string.UserID = "a7709578_codecal";
conn_string.Password = "xxxxx";
conn_string.InitialCatalog = "a7709578_codecal"; // Database name
SqlConnection conn = new SqlConnection(conn_string.ToString());
conn.Open();
SqlCommand cmd = new SqlCommand("Select name FROM Users");
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{1}, {0}", reader.GetString(0), reader.GetString(1));
}
reader.Close();
conn.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}
You need to build the connection string manually or use MySqlConnectionStringBuilder. MySql uses a different format than SQL Server and the SqlConnectionStringBuilder that you're using. You also need to use a MySQL library, SqlConnection, SqlCommand, etc are all build specifically for SQL Server.
MySQL connectors
For MySQL database you are using wrong provider. Those classes you have used in posted code are for SQL Server. Your code should look like below with MySQL provider related classes
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql14.000webhost.com";
conn_string.UserID = "a7709578_codecal";
conn_string.Password = "xxxxxxx";
conn_string.Database = "a7709578_codecal";
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
Check Related post in SO
Also to point out, you are selecting only one column from your table as can be seen
new SqlCommand("Select name FROM Users");
Whereas trying to retrieve two column value, which is not correct
Console.WriteLine("{1}, {0}", reader.GetString(0), reader.GetString(1))
000webhost free servers does not allow external connections to the server database.
You can only use your database from your PHP scripts stored on the server.
You can get data from database using PHP and it will return.So i advice to you using php from C# like api.

System.InvalidOperationException: Cannot perform CAS Asserts in Security Transparent methods

I have a SQL CLR trigger written in C# 4.0 and deployed on SQL Server 2014. Whenever an insertion happens in a table in SQL Server, this CLR trigger's job is to import that row in an Oracle database. So basically I have to import data in Oracle database whenever an insert query is fired on a table in SQL Server 2014. This is my first CLR SQL trigger project and below is what I am doing:
[SecurityCritical]
[OraclePermission(System.Security.Permissions.SecurityAction.Assert, Unrestricted = true)]
[SqlTrigger(Name = "FetchSurvey", Target = "temp", Event = "FOR INSERT")]
public static void FetchSurvey()
{
SqlTriggerContext triggerContext = SqlContext.TriggerContext;
// Create result set to store data
DataSet resultSet = new DataSet();
// Create a new SQL command
using (SqlCommand command = new SqlCommand("SELECT * FROM INSERTED"))
{
// Create a new SQL connection
using (command.Connection = new SqlConnection("context connection=true"))
{
// Connect to the database
command.Connection.Open();
// Execute procedure
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
adapter.Fill(resultSet);
}
// Disconnect from the database
command.Connection.Close();
}
}
SqlPipe sqlP = SqlContext.Pipe;
// Return data
if (resultSet.Tables.Count > 0)
SaveSurvey(resultSet);
sqlP.Send("Finaly its done!!");
}
public static void SaveSurvey(DataSet dsSurvey)
{
using (OracleConnection con = new OracleConnection("my oracle connection string"))
{
if (con.State == ConnectionState.Closed)
con.Open();
DataRowView drv = dsSurvey.Tables[0].DefaultView[0];
using (OracleCommand cmd = new OracleCommand("AddMetaData", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("V_id", drv["TemplateID"]);
cmd.Parameters.AddWithValue("V_Title", drv["TemplateName"]);
cmd.Parameters.AddWithValue("V_CreatedBy", drv["CreatedBy"]);
cmd.Parameters.AddWithValue("V_IsActive", drv["IsActive"]);
cmd.ExecuteNonQuery();
}
}
}
And this is my code to create assembly/deploy trigger:
CREATE ASSEMBLY TriggerImportSurvey
FROM 'C:\ImportSurvey\SQL-CLR-Trigger.dll'
With Permission_Set = External_Access;
Now the problem is whenever I run an insert query in SQL Server to insert data, I got below error in SQL Server:
Msg 6522, Level 16, State 1, Procedure tri_InsertSurvey_clr, Line 18
A .NET Framework error occurred during execution of user-defined routine or aggregate "tri_InsertSurvey_clr":
System.InvalidOperationException: Cannot perform CAS Asserts in Security Transparent methods
System.InvalidOperationException:
at Triggers.FetchSurvey()
tri_InsertSurvey_clr is the trigger which is responsible for executing the assembly whenever I run an insert statement.
Please tell me what I am missing so that I am getting this error, Also if there a more elegant way of implementing a CLR SQL trigger then please also suggest that.
NOTE: When I tried to save the data using a trigger in SQL Server I was successful, but now when I am trying to save it in Oracle database, I am getting this error. Also the Oracle database is installed on another machine.

Categories