To get the connection string from my App.config I write this code:
ConnectionStringSettings settings
= ConfigurationManager.ConnectionStrings["livresEntities"];
string connectString = settings.ConnectionString;
Console.WriteLine("Original: "+ connectString);
The result (I use Data Model .edmx file):
Original: metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=MySql.Data.MySqlClient;provider connection string="server=localhost;user id=root;persistsecurityinfo=True;database=livres"
But when I want to change the password or the uid using this line:
MySqlConnectionStringBuilder builder
= new MySqlConnectionStringBuilder(connectString);<br>
It give me the following error:
Keyword not supported
Why? If there is any tutorial on how to secure MySQL's connection string using a Model (.edmx) it will be very helpful for me.
Related
I am trying to open connection with Azure SQL database. Tried creating usual connection = new MySqlConnection("Server=" + server + "Database=" + database + "Uid=" + uid + "Password=" + password); with every string variable ending with ; but yet it always fails to connect even if the data is correct. Tried to use given string for ADO.NET but then I am getting exception "keyword is not supported". I don't what else to actually.. Googled as much as possible but all solutions are quite the same and yet nothing works out for me :/
Firstly, azure databases don't use mysql. so using MySqlConnection() won't work.
instead use
SqlConnection connection = new SqlConnection(connectionstring);
Standard connection strings should be in the format
Server=tcp:[serverName].database.windows.net;Database=myDataBase;
User ID=[LoginForDb]#[serverName];Password=myPassword;Trusted_Connection=False;
Encrypt=True;
See https://www.connectionstrings.com/azure-sql-database/ for more options
var connectionString = #"Server=tcp:<dbname>.database.windows.net,1433;Initial Catalog=<databasename>;Persist Security Info=False;User ID=<userid>;Password=<password>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
That's how I connect to my Azure SQL Database, works for me.
For MySQL In App you can use the fellowing code in c# to get the connection string:
static string getConnectionString()
{
#if DEBUG
string connectionString = "dbname=localdb;host=localhost:3306;user=root;pass=password;";
#else
string connectionString = Environment.GetEnvironmentVariable("MYSQLCONNSTR_localdb");
#endif
string[] options = connectionString.Split(";");
string database = options[0].Split("=")[1]; ;
string serverport = options[1].Split("=")[1];
string server = serverport.Split(":")[0];
string port = serverport.Split(":")[1];
string user = options[2].Split("=")[1];
string password = options[3].Split("=")[1]; ;
connectionString = $"server={server};port={port};database={database};user={user};password={password};";
return connectionString;
}
The standard .Net Framework provider format is:
Server=[serverName].database.windows.net;Database=myDataBase;
User ID=[LoginForDb]#[serverName];Password=myPassword;Trusted_Connection=False;
Encrypt=True;
Azure SQL Database is an SQL Server type database, not MySQL!
Have you followed Microsoft instructions?
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-dotnet-visual-studio
You have to create server-level firewall rule on azure too, to be able to connect.
I want to get the user id and the password of oracle db instance from the connection string that i have stored in my App.config file.
Here is the connection string stored in App.Config File
<add name="MyConnection" connectionString="Data Source=xe;User ID=UsmanDBA;Password=root;" providerName="System.Data.SqlClient" />
I have tried OracleConnectionString Builder but it does not return the password of connection string Here is the code:
public string ConPass()
{
OracleConnectionStringBuilder builder = new OracleConnectionStringBuilder();
builder.ConnectionString = con.ConnectionString;
return builder.Password;
}
this method does return the user id but not the password
Is there something i am missing? or is there any other way to do this?
Kindly help me to sort this out..
ConnectionString property never contains password. That is the security measure. In your code, password has been lost in this line:
builder.ConnectionString = con.ConnectionString;
You have to devise a different approach. For example, to read the connection string from config and then to feed it to the connection string builder. This might not be generally applicable if you only have the connection and no information from which config entry it was constructed...
On a related note, SQL Server connection (SqlConnection) exposes the Credential property which could be used to read password (I haven't actually tried this). I don't know of similar property in Oracle connection implementation.
You can make use of the SqlConnectionStringBuilder
string conString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
OracleConnectionStringBuilder builder = new OracleConnectionStringBuilder(conString);
string user = builder.UserID;
string pass = builder.Password;
I was given a method to get our database connection string to Sql Server:
SqlConnection GetConnectionString()
I call that and get what the connection string should be. If the database does not exist, I need the connection string without the database name in it. If I try to use the connection string with the database name in it, I get an error that it cannot connect to the database, which is it since it does not exist.
I am calling like this:
using (var connection = new SqlConnection(GetConnectionString().ConnectionString))
Is there a way to recreate the connection string easily without the database name?
SqlConnectionStringBuilder aBuilder =
new SqlConnectionStringBuilder(yourConnectionStringWithDatabase);
aBuilder.InitialCatalog = "";
string yourConnectionStringWithoutDatabase = aBuilder.ConnectionString;
It's easy
var connectionString = "data source=someInstance;initial catalog =someDatabase;etc.";
var pattern = "initial catalog[=\\s\\w]+;";
var dbRemoved = Regex.Replace(connectionString, pattern, "");
Note that I haven't handled case sensitivity, but this should be a good start for your requirements.
I'm trying to use Entity Framework and it put it's connection string into app.config. I would like to move it to code as it's easier for me at this stage of development.
metadata=res://*/database.csdl|res://*/database.ssdl|res://*/database.msl;provider=System.Data.SqlClient;provider connection string="data source=computer;initial catalog=database;persist security info=True;user id=user;password=Mabm#A;multipleactiveresultsets=True;App=EntityFramework"
How can I make Entity Framework use connection string from code rather then look at the app.config? Alternatively if it's not possible how can I pass parameters to app.config (like dbname, dbuser, dbpassword)?
You can use EntityConnectionStringBuilder for this purpose.
Check here
public string GetConnectionString()
{
string connectionString = new EntityConnectionStringBuilder
{
Metadata = "res://*/Data.System.csdl|res://*/Data.System.ssdl|res://*/Data.System.msl",
Provider = "System.Data.SqlClient",
ProviderConnectionString = new SqlConnectionStringBuilder
{
InitialCatalog = ConfigurationManager.AppSettings["SystemDBName"],
DataSource = ConfigurationManager.AppSettings["SystemDBServerName"],
IntegratedSecurity = false,
UserID = ConfigurationManager.AppSettings["SystemDBUsername"],
Password = ConfigurationManager.AppSettings["SystemDBPassword"],
MultipleActiveResultSets = true,
}.ConnectionString
}.ConnectionString;
return connectionString;
}
When you create an instance of your ObjectContext derived class, you can simply pass the connection string as a constructor argument.
Rather than use a username and password, why not use Integrated Security? It is more secure and easier to manage.
i.e. 'Trusted_Connection = Yes' in your connection string and securely manage access through AD.
Connection Strings
First, create your context using the constructor with the connectionString parameter.
http://msdn.microsoft.com/en-us/library/gg679467(v=vs.103).aspx
Note that it's not directly this constructor that you must call, but the specific inherited context constructor for your database that your Entity generator created for you.
Furthermore, if you want to pass the username and password at runtime, you can create a connection string using this class:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx
See here:
http://msdn.microsoft.com/en-us/library/bb738533.aspx
If the connection string log in details are always the same then I would suggest that you use ConfigurationManager to retrieve the connection string from your app.config and encrypt the ConnectionStrings section of the file.
Is there an existing method in C# to extract the file path from a string that represents a ConnectionString to a SqlCE .sdf file? I want to check if the file exists at initialization and back it up if the file has been modified.
Sample connection string:
strConn = "Data Source=|DataDirectory|\dbAlias.sdf";
You can use SqlCeConnectionStringBuilder class to parse existing Sql Compact connection string.
A bit late perhaps, but I came across this question wile struggling with the same problem. You can find the location of the |DataDirectory| folder with AppDomain.CurrentDomain.GetData("DataDirectory"). So your connectionstring can be translated like this:
strConn .Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory").ToString())
You could just create the connection and get the data source from it as a property:
string data;
using (var conn = new SqlConnection(connectionString)) {
data = conn.DataSource;
}
For LocalDB and SqlConnection (not CE):
public static string GetFilePathFromConnectionString(string connectionString)
{
var attachDbFileName = new SqlConnectionStringBuilder(connectionString).AttachDBFilename;
return attachDbFileName.Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory").ToString());
}