Removed database out of connection string - c#

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.

Related

Store user-specific connection strings for later use in ASP.NET Web API

I am working on complicated project which allows every client to set their connection string information to connect to their own database but after that I didn't now what to do or how to let the client reach his own connection string (I don't have a table to save the connection string I want to be dynamic).
Is there any way to store the connection string in config page for every client and read those page in my web config.
If number of client is managable, then you store it in web config file and you need seperate dbContext implentation if everyones database is different. If same db design is same for all, you can store credentials in dictionary and dynamically prepare connection string run time and connect.
Here is an example for MSSQL (I assume you are not using EF)
Not need to store connectionstring in web config.
Prepare connection string. You can store user wise parameters in DB as well.
public string BuildConnectionString(string dataSource, string dbName, string userId, string password,
string persistSecurityInfo, string encrypt, string trustServerCertificate, string applicationIntent, string multiSubnetFailover)
{
return $"Data Source = {dataSource}; Initial Catalog = {dbName}; User ID = {userId}; Password = {password}; " +
$"Persist Security Info = {persistSecurityInfo}; Encrypt = {encrypt}; TrustServerCertificate = {trustServerCertificate};" +
$" ApplicationIntent = {applicationIntent}; MultiSubnetFailover ={multiSubnetFailover}";
}
DB Connection example:
void CheckDbConnection()
{
string connetionString = BuildConnectionString("WIN-50GP30FGO75", // or IP
"Demodb", "YourUserID", "YourPassword", "True", "False", "False",
"ReadWrite", "False");
string sql = "Select TutorialID,TutorialName from table1";
using (SqlConnection cnn = new SqlConnection(connetionString))
{
using (SqlCommand command = new SqlCommand(sql, cnn))
{
cnn.Open();
dataReader = sqlquery.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + "-" +
dataReader.GetValue(1) + "</br>";
}
Console.Write(Output);
cnn.Close();
}
}
}
You wont be able overwrite or add something to the Web.config during runtime, only read from it.The web.config file is only read once during startup and wont be used afterwards.
A suggestiong to overcome this is either store the connectionstring for your customers in your own database or store them somewhere else. I prefer using Azure KeyVault for these things, as it allows you to let the user change the data using a specific key.
Also this is one of those scenarios where security is a big factor, so you must be very carefull when giving your customers these kinds of actions.

How to `ListCollections` by using only connection string in mongo C# driver?

I'm instantiating MongoClient with full connection string which includes DB :
MongoClient dbClient = new MongoClient("mongodb://***:***#***:27017/myDb");
var dbList = dbClient.ListDatabases();
IMongoDatabase db = dbClient.GetDatabase("myDb");
var collList = db.ListCollections().ToList();
...
This works. But -
If the connection string already includes myDb, then why do I need to write again :
dbClient.GetDatabase("myDb");
?
I've already written myDb in the connection string.
Question:
Is there any option to ListCollections of the DB which already mentioned in the connection string?
One option is to just pull out the database name from the connection string. That might sound a bit messy, but MongoUrl makes it nice and easy. Here's an example:
var connectionString = "...";
var dbName = MongoUrl.Create(connectionString).DatabaseName;
// ...
IMongoDatabase db = dbClient.GetDatabase(dbName);

How can i get the password of oracle user instance from oracle connection string using C#?

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;

change connection string for dataset

How to create authentication window for database when I use dataset - MyDatabaseDataSet?
When I didn't use dataset I simply open new SqlConnection for every operation and use some connection string which was created after I writed Login and Password. But Dataset use some default connection string. How to change it?
I want to connect to database and tables with connection string Data Source=XXXX-PC\MSSQLSERVER2;Initial Catalog=MyDatabase;User ID={0};Password={1} where {0} and {1} - parameters from authentication window.
I don't understand where to put my connection string and then use it as default connection string.
I've had problems in the past with DataSet objects using a default connection string.
To get around this, I pass the connection string into my SqlConnection constructor.
In my case I'm using a web.config to hold the connection string.
var dt1 = new CustomDataSet.CustomDataTable();
var connectionString = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString
using (var connection = new SqlConnection(connectionString))
{
using (var da1 = new GetCustomDataTableAdapter() { Connection = connection })
{
da1.Fill(dt1, id);
}
}

C# - Get file path from connection string

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());
}

Categories