Is it possible to have two ConnectionStrings with the same name? - c#

Can it is possible to have same name with two Connection String in an application with two datasource like or condition.
<add name="DefaultConnection" connectionString="Data Source=serverName|serverIpAddress;Initial Catalog=DatabaseName;User=name;Password=Password;"
providerName="System.Data.SqlClient" />
Can any body help me to doing this.

It is not possible because ConnectionStrings are maintained in KeyValuePair and with name being the key.
Please let us know why you need such scenario, then we might be able to help you.

If your two databases are configured with SQL Server Mirroring, then you can actually specify a backup server inside the connection string. You can do this with Failover Partner:
Data Source=Primary_Server;Failover Partner=Secondary_Server; ... other stuff...
Then you just have to edit your existing configuration string with both server addresses and the framework will automatically connect to your secondary server if the primary is unavailable.
There's some idiosyncrasies around the usage of Failover Partner though (from what I've read, I haven't used it myself), so I'd recommend reading up on it in depth before implementing it.
If your databases aren't mirrored, you're going to have to implement the failover yourself, probably by abstracting the acquisition of the database connection.
Specify two distinct connection strings in your config (primary and secondary), and then implement some sort of Connection String service that returns the appropriate connection string based on your criteria (i.e. test primary, if fails, return secondary, else return primary, or whatever you want).
Keep in mind that there is a possibility that your server could go offline AFTER testing the string but BEFORE using it, but this is a pretty big edge case. Just keep it in mind if you need to maintain functionality in that situation.

No you can not have two connection string with same name.
So if you can what is result this code:
var connectionString=ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
Connection string store in KeyValuePair object.
The application can optionally specify the connection name in an
application configuration file that provides the required
keyword/value connection string values. In this case, you cannot
supply them directly in the connection string. The Name keyword is not
allowed in a configuration file.
When the Name keyword is not included in the connection string, a
non-empty values for Provider keyword is required.
This keyword is mutually exclusive with all the other connection
string keywords.

Related

Azure mobile EasyTables connection string

I am fairly beginner in here, so any help would be much appreciated :)
So, I created a SQL Database and I want to connect EasyTables to it. Apparently the automatic option has been removed and I have to do it manually.
I followed "How can I add a connection string manually" page but it lead me to nothing.
Where should i create the connection string, and what to put in the value field?
Or if there is any tutorials out there for the new way please tell me :)
Thank you a lot
You said you have followed tutorial: How can I add a connection string manually.
The Easy Table connection should like this:
SQL Database Connection String format
Data Source=tcp:{your_SQLServer},{port};Initial Catalog={your_catalogue};User ID={your_username};Password={your_password}
{your_SQLServer} Name of the server, this can be found in the
overview page for your database and is usually in the form of
“server_name.database.windows.net”.
{port} usually 1433.
{your_catalogue} Name of the database.
{your_username} User name to access your database.
{your_password} Password to access your database.
Add the connection string to your Web App
In App Service, you can manage connection strings for your application by using the Configuration option in the menu.
To add a connection string:
Click on the Application settings tab.
Click on [+] New connection string.
You will need to provide Name, Value and Type for your connection
string.
If your are adding a connection string to a SQL Azure database choose
SQLAzure under type.
If your are adding a connection to an Azure Storage account, chose
Custom under type.
NOTE If you are adding a connection string because you are planning on using the Easy API or Easy Table features, then the connection strings used by this features expect the following specific names:
Azure SQL database: MS_TableConnectionString
Azure Storage account: MS_AzureStorageAccountConnectionString
For example, this is my connection string:
When you have configured this, go to Easy table, click Add to add the table name in your Azure SQL database.
You can find that esay table has connected to my Azure SQL database now and we can see the data in the table.
Update:
You should first add the connection string in the configuration followed the format provided for you.
Then go to Easy Table, configure Easy table API:
Choose the 2:
When it done, you can add table in your SQL database, please follow my steps in above.
Note:
Your connection string name must be: MS_TableConnectionString.
Hope this helps.

Connection String management for a desktop application

I created a desktop application in C#/WPF which connects to a SQL Server 2008 instance through a constant connection string specified in code as follows (for testing purposes):
private string GetConnectionString()
{
//test
return "Data Source=[server IP]; Initial Catalog=[database name]; User ID=[user ID]; Password=[smart password];";
}
The application will be used by various users and will be deployed via ClickOnce, a .zip archive or a custom installer. It also has a separated custom login functionality by requesting an application-access username and password.
Which is the best practice to store the connection string details for my desktop application (IP, database, SQL Server user, password)? If the connection string changes over night, which is the best method to update it without forcing users to update to the latest version of my application? Users should not be able to see/intercept/decompile the connection string, so I guess I must use some sort of encryption.
Do you have any kind of suggestion for my inquiry?
Even if you compile your connection strings into the application, they still can be viewed using the Ildasm.exe (MSIL Disassembler) tool because strings are a part of assembly's metadata.
Maybe this question can help you.
In a desktop application, you can't prevent a determined user from seeing the connection string. Even if you use encryption, a determined user will be able to find and use the encryption key.
If the client is connecting to the database then the connection can be hacked.
This is a sample of connection data in App.Config
<appSettings>
<add key="dbServer" value="svr"/>
<add key="dbDataBase" value="db1"/>
<add key="dbUser" value="sharedUser"/>
<add key="dbPassword" value="easyPassword"/>
</appSettings>
Need a reference to system.configuration
string SvrName = ConfigurationManager.AppSettings["dbServer"];
string DBName = ConfigurationManager.AppSettings["dbDataBase"];
string DBUser = ConfigurationManager.AppSettings["dbUser"];
string DBPassword = ConfigurationManager.AppSettings["dbPassword"];
As for security the answer is a 2 tier application where only the secure server side code connects to the database. This code sample from server side code.
The other benefits of server side is repeated queries from the same connection can gain from indexes in memory from prior query.
You could salt and hash the password read from the AppSettings and obsfuscate the application but you would have to use a static salt so it could be hacked. It would just slow down the hacker.
You need to add an "Application Settings" file to your application. Just right click on your solution -> add -> find something similar to "app configuration". In order to do this you will need some kind of external config file to store the connection string. You could even use a simple file. If worried about people finding the file, you can always encrypt the string and decrypt it in your app.
My opinion is that the safest solution is to have a local DNS entry point to the current SQL machine and the authentication to be Windows authentication.
For example : SQLMACHINE host name pointed to 192.168.1.3 in the DNS server.
This way if the name/IP of the SQL machine changes, only the DNS server needs updated (and possibly the local DNS caches to be invalidated).
Having Windows authentication means that no password will be stored on the local machine so you can safely store the connection string in the .config file with no worries.
My 2 (euro)cents.

SQL connection string on domain C#

I moved a webapp from my personal machine to my work machine, along with the database I've been using to test. When clicking the submit button that inserts the data, I get the error, can't find server/instance. I'm thinking that being on a domain here is part of the problem. Here is my connection string, and I've tried several forms of it already.
Data Source=\\bkirkland_lpt.domain.com\brandon;Initial Catalog=STATUS;integrated security=SSPI;persist security info=False;Trusted_Connection=Yes;");
I see a couple problems here.
First, it looks like you are using the wrong data source. The data source should be in the format [ServerName]\[InstanceName]. Based on your code, I would suggest
Data Source=bkirkland_lpt.domain.com\brandon;Initial Catalog=STATUS;integrated security=SSPI;persist security info=False;Trusted_Connection=Yes;
Additionally, I notice you are using Integrated Security. This means that the user you are running under must be granted permissions on the database. My guess is that your domain user does not have access to the database that you moved.
\bkirkland_lpt.servicesource.com\brandon is a shared folder path, not a host name. Try bkirkland_lpt.servicesource.com
Try to enclose the server name in []. Try to replace the servername with localhost and see if it makes any difference (if it is all on your local machine). I also would use proper casing and True vs Yes as parameter value.
Data Source=[bkirkland_lpt.domain.com]\brandon;Initial Catalog=STATUS;Integrated Security=SSPI;Persist Security Info=False;Trusted_Connection=True;
Data Source=localhost\brandon;Initial Catalog=STATUS;Integrated Security=SSPI;Persist Security Info=False;Trusted_Connection=True;

Sharing SQL Server Between Multiple System

I have three computer in a office and I have installed my C#-2005 Project on all three
computers. But Problem is that Boss wants Sql-server-2000 on One PC out of three and other
would share the same.
I don’t know how to share Sql-server-2000 between three PC?. How to do?.
Confusion:-
Thanks for your co-operation but here I have a confusion on majority people said to check
TCP/IP address and consider the Connection string as per main server from client PC.
Suppose I have financial project and there would be thousand of connection string in a
project. As per above I have to change thousand of connection string as per main pc.
Now think it is a one customer's need If I have ten cutomer having same offer than think How much time I have to waste on it?. I have to modify thousand of connection string ten time more?.
If it is true than it will take lots of time on installation to each customer.
I don’t know if it is only way?.
The Connection string I have utilized on my each winform is as below:
string connstr = "server=.;initial catalog=maa;uid=mah;pwd=mah";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
Here suggested about Config File and same I don't know if some body give me idea about how to consider it with my C#2005 project than it will save my lots time.
When you connect to the database in your code, you'll a database connection string of some sort somewhere in there. Figure out the connection string for the Database server and set your code to point to that database server's connection info; I'd bet you currently you have it pointed at localhost
If you're using SQL Server you may need to enable remote connections on the database server.
added: you may need to modify firewall settings as well to allow SQL Server traffic (thanks Jared)
.
Edit: For putting the configuration string into a central location.
Your posted code
string connstr = "server=.;initial catalog=maa;uid=mah;pwd=mah";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
Change to
Assuming your application has a App.Config file then you'd add an entry in there like
<add key="DBConnectionString" value="server=.;initial catalog=maa;uid=mah;pwd=mah"/>
And change your C# code to be like
string connstr = ConfigurationManager.AppSettings["DBConnectionString"];
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
Putting the ConfigManager call into a class might be a good idea if you have a lot of settings to retrieve and/or believe the configuration storage methodology might change down the road. Going with the above example is WAY better than having the string literal scattered throughout your code.
Enable theTCP/IP connection in SQL Server. So that you can connect remotely from any pc within the network
check here
If your problem is that you embedded your connection string in the code, then you are going to have to do some refactoring. These would be the general steps, you will have to tailor them a bit to your situation.
Add your connection string to the app.config file.
Create a static/shared method that will read the connection string from the
config file.
Do a find and replace in your solution to replace all
of the hard coded connection strings in your code with the (class
and) name of the method that gets the connection string.
This is probably going to be easier than rewriting all of your data calls to use something like enterprise library or EF.
You will need to do as the others suggested, such as changing the connection string and enabling TCP/IP within SQL Server, but you will also likely need to configure your firewall to allow requests to SQL Server (default port of 1433) through.

Is there a generic way of dealing with varying connection strings in C#?

I have an application that needs to connect to a SQL database, and execute a SQL Agent Job.
The connection string I am trying to access is stored in the registry, which is easily enough pulled out.
This appliction is to be run on multiple computers, and I cannot guarantee the format of this connection string being consistent across these computers. Two that I have pulled out for example are:
Data Source=Server1;Initial Catalog=DB1;Integrated Security=SSPI;
Data Source=Server2;Initial Catalog=DB1;Provider=SQLNCLI.1;Integrated Security=SSPI;Auto Translate=False;
I can use an object of type System.Data.SqlClient.SqlConnection to connect to the database with the first connection string, howevever, I get the following error when I pass the second to it:
keyword not supported: 'provider'
Similarly, I can use the an object of type System.Data.OleDb.OleDbConnection to connect to the database with the second connection string, howevever, I get the following error when I pass the first to it:
An OLEDB Provider was not specified in the ConnectionString'
I can solve this by scanning the string for 'Provider' and doing the connect conditionally, however I can't help but feel that there is a better way of doing this, and handle the connection strings in a more generic fashion.
Does anyone have any suggestions?
The normal way of handling this is storing the ADO.NET provider unique name (separately from the connection string) and using a DB Provider Factory.
Use a SqlConnectionStringBuilder, initialize it with the connection string you find in registry and then read its ConnectionString property, which would normalize the connection string to proper SQL Client syntax.

Categories

Resources