Change connectionString dynamically - c#

I have a WinForm C# application that uses SQL server which needs to be accessed through VPN, the original connectionstring that we have on the server is:
connectionString="Data Source=localhost;Initial Catalog=MyDB;user id=myuser;password=mypass"
This connection string is at the app.config file
Everyone in the LAN can access the app and execute just fine, now when we connect through VPN, the connection to the SQL database doesn't work (obiously because the connectionstring needs to be different)
The IP we get when we connect using VPN may not always the same so my question is, can I dynamically change the connectionstring so that the user can input the Source when using VPN?
Thanks

Use String.Format() to gernerate the connection string.
string datasource = DatasourceTb.Text; // get value from user input.
string catalog = "MyDB";
string username = "myuser";
string password = "mypass";
string connectionString =
String.Format("Data Source={0}; Initial Catalog={1}; User Id={2}, Password={3};",
datasource,
catalog,
username,
password
);

Related

Visual c#, connect to SQL server using Sql Server Authentication instead of Windows Authentication

I am trying to connect to a database using the following Connection String that will allow me to connect to the database using Sql Server Authentication instead of Windows Authentication. This is because my user name and password for Windows Authentication is different from the Sql Server Authentication.
String connStr =
#"Data Source = mySeverName;
Initial Catalog = PMSystem;
Integrated Security = SSPI;
User ID = myID;
Password = myPassword;";
Here is the rest of the code
DataSet PMSytem = new DataSet();
String sqlProject = #" Select * from Project";
SqlDataAdapter daProject = new SqlDataAdapter(sqlProject, connStr);
daProject.FillSchema(PMSytem, SchemaType.Source, "Project");
daProject.Fill(PMSytem, "Project");
When I run the environment it comes up that the login has failed for my user account that is associated with the Windows Authentication and not Sql Server Authentication. I have looked it up online and I cannot seem to get a direct answer. The error is the connection String. Is there anything I am missing or do you guys have any suggestions on how to go about this? Thanks in advance!
EDITED: Note this is a very small draft project
In your code you set Integrated Security to be used - so by default irrelevant of username/password its trying to use your windows account. If you turn it to false, and just supply "myuser","mypassword" it will use sql authentication.
String connStr =
#"Data Source = mySeverName;
Initial Catalog = PMSystem;
Integrated Security = false;
User ID = myID;
Password = myPassword;";
If it's windows authentication then don't pass credentials. Remove the below statements from connection string
User ID = myID;
Password = myPassword;";
It should be
String connStr =
#"Data Source = mySeverName;
Initial Catalog = PMSystem;
Integrated Security = true;"

Oracle connection with port, service name, and database from C# (ORA-12514

I'm new to Oracle. Trying to connect C# windows app to an Oracle database but can't seem to establish a proper connection. Keep getting exception: "ORA-12514: TNS:listener does not currently know of service requested in connect descriptor". I have to specify the port, service name, and database name in the connection string because the service id has access to multiple databases. I know that the values in the string are valid (valid server, valid serviceid, valid username, password, etc) because I have a third-party tool that is able to connect using the same parameters from a wizard. I've tried a lot of different ways to format the connection string but I always get the same 12514 error. In the code example, you'll see three formats (cxn, cxn2, and cxn3), I've tried each of them but get the same error.
string cxn = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MyServerName)(PORT=MyPortNumber))" +
"(CONNECT_DATA=(SERVICE_NAME=MyServiceId)));User Id=MyUserName; Password=MyPassword;";
string cxn2 = "DATA SOURCE=MyServerName:MyPortNumber/MyUserName;" +
"PERSIST SECURITY INFO=True;USER ID=MyUserName; password=MyPassword; Pooling = False;";
string cxn3 = "DATA SOURCE=MyServerName:MyPortNumber/MyServiceId;" +
"PERSIST SECURITY INFO=True;USER ID=MyUserName; password=MyPassword; Pooling = False;";
using (OracleConnection conn = new OracleConnection(cxn3))
{
string sqlSelect = "SELECT * FROM PERSONS";
using (OracleDataAdapter da = new OracleDataAdapter(sqlSelect, conn))
{
var table = new DataTable();
da.Fill(table);
if (table.Rows.Count > 1)
Console.WriteLine("Successfully read oracle.");
}
}
Again, I've used MyServiceId in the third-party tool's wizard and I connect just fine and select my database. I'm using Oracle.ManagedDataAccess.Client. I consulted a number of articles online including Oracle's guidance in section "Getting Started with ODP.NET, Managed Driver". How can I get the driver to recognize the valid service id and then also accept the database name? Any guidance is appreciated. Thanks.
Well I wish I had a more definitive explanation but as it turns out the code from my original question works NOW using the connection string defined in variable "cxn". I ran it many times before with no success, so my only guess is that the DBA changed something or rebooted the server since initial configuration.

How to create connection string that independent on instance and server name?

i want my application can run on every device that maybe have different server name and instance. my connection string is below:
DBDataContext db = new DBDataContext(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\App_data\DB.mdf;Integrated Security=True;User Instance=False");
If I understand you correctly and the Data Source is always on the local server, why don't you get the ip address of the server with System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"];
string myLocalserverIP = System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"];
then use that in your Data Source string.

MySql access denied for user - can't create the user the software is looking for

My connection string looks like this:
string server = "localhost";
string database = "stman";
string user = "logan";
string pass = "root";
string connStr = String.Format("Data Source={0};Initial Catalog={1}; User Id={2}; Password={3};", server, database, user, pass);
Given my understanding, this means MySql should be using 'logan'#'localhost' for the login, but it isn't.
It looks as though it's using 'logan'#<server's fully qualified name>:
Access denied for user 'logan'#'HP-PL-ML110.young.home'
I'm at a loss right now. SqlYog doesn't allow me to create a user with that hostname, my options for hostname are %, localhost or 127.0.0.1
Can anyone help me make sure that the website is using the specified username here? I have no idea what to look at to fix this
Joe's comment:
Have you tried disabling host name lookup, as in this question
Applying this didn't fix the issue but it did change the settings so that I could use the IP address in the connection string.
This does mean I had to create a new user (I found that, in Sqlyog, you can enter something different in the hostname field in user creation) and grant the new user the required permissions on the target database.
It's not exactly a solution, but it is a viable workaround that's got me back to a point where I can actually progress further in my development now.
Thanks Joe
string connStr = String.Format("Data Source={0};Initial Catalog={1}; User Id={2}; Password={4};", server, database, user, pass);
Should be
string connStr = String.Format("Server={0};Database={1};Uid={2};Pwd={4};", server, database, user, pass);

How do I get the Application Name from either SQL Server connection string or the IIS application name using C#?

How do I get the Application Name from an SQL Server connection string in the web.config file.
I want to use to log escalated error messages from a web application into the Windows Event Log.
Maybe there is a better way of doing this, ie using the IIS/Web application name?
Thanks
Mark
What does the connection string look like?
DbConnectionStringBuilder is good for parsing and inspecting connection-string values by key:
DbConnectionStringBuilder db = new DbConnectionStringBuilder();
db.ConnectionString = connectionString;
Console.WriteLine(db["Application Name"]);
otherwise you can get various details from the http server variables.
SqlConnectionStringBuilder is also useful if you are using SQL Server:
SqlConnectionStringBuilder sc = new SqlConnectionStringBuilder(connectionString);
string applicationName = sc.ApplicationName;

Categories