In my data import application I want to allow the user to import data from as much different data sources as possible.
So what is the best way and what are the classes needed to be able to connect to different data sources and then get data from them via SQL queries?
E.g.
// 1. A class I need to allow the user to select the needed data source
ConnectionDialog dlg = new ConnectionDialog();
dlg.ShowDialog();
// 2. A class I need to access the data source using the connection string built above
DataConnection con = new DataConnection(dlg.builtConnectionString);
con.doStuff("SELECT * FROM test");
Currently I'm using the Microsoft connection dialog (http://archive.msdn.microsoft.com/Connection) for the first part. But I can't figure out how to use the connection strings returned by it. An OdbcConnection won't accept it (only tested with an Micrsosoft SQL connection string generated by the dialog). Is it even possible to achieve the above or will I be forced to use different classes for the second part?
Edit: I also want the user to be able to install his own drivers for data sources. I just don't know if ODBC or OleDB or anything else is the way to go and if/how I can use the connection dialog with this.
Use wrapping to list of DB sources. Add a connection strings to web.config for each type of DB connection (MSSQL , MYSQL and Oracle) with {{name}} string and then replace this string with the catalog selected by the user.
<connectionStrings>
<add name="mssql" connectionString="Data Source=.;Initial Catalog={{name}};Integrated Security=True" />
<add name="mysql" connectionString="server=localhost;user id=root; password=PASS;database={{name}};pooling=false" />
<add name="oracle" providerName="Oracle.DataAccess.Client" connectionString="Data Source={{name}};User Id=root;Password=PASS;" />
</connectionStrings>
Now use SqlConnection and MySqlConnection and OracleConnection classes . (You will need mysqlconnector and oracleconnector for these classes).
This line:
WebSecurity.InitializeDatabaseConnection(connectionStringName: "DefaultConnection", userTableName: "UserProfile", userIdColumn: "UserID", userNameColumn: "UserName", autoCreateTables: true);
Is throwing:
'System.ArgumentException' occurred in System.Data.dll but was not handled in user code
Additional information: Keyword not supported: 'metadata'.
My connection string is:
add name="DefaultConnection" connectionString="metadata=res://*/TalyllynModel.csdl|res://*/TalyllynModel.ssdl|res://*/TalyllynModel.msl;provider=System.Data.SqlClient;provider connection string="data source=***********;initial catalog=********;persist security info=True;user id=*********;password=********;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.SqlClient" /></connectionStrings>
Not sure where it is im going wrong.
The string you passed is not a valid database connection string, it's an EF connection string that contains a SQL Server connection string in its provider connection string parameter. WebSecurity.InitializeDatabaseConnection expects a valid database connection string
To avoid parsing the connection string yourself, you can use the EntityConnectionStringBuilder class to parse the string and retrieve the database connection string from its ProviderConnectionString property
When this happened to me it was because the connection string had:
providerName="System.Data.SqlClient"
but it should be:
providerName="System.Data.EntityClient"
because as was said by the other answer, it is an EF connection string.
Just to add another possibility (which I encountered) - which might be the case if you're developing/maintaining an Azure WebApp, using a connection string saved in Azure's Application Settings.
Beside each connection string in the Application Settings is a dropdown for the connection string type - it's very easy to forget to set this to 'Custom' for Entity Framework values and leave it at the default (SQL Database) - which also causes the above error.
Here's some code I use, to extract the database name & server name from a connection string.
Notice how it checks if it's an Entity Framework connection string, and if so, it extracts the "provider connection string" part of that, which can then be passed into SqlConnectionStringBuilder:
If I didn't do this, I'd get that nasty "Keyword Not Supported: Metadata" error.
if (connectionString.ToLower().StartsWith("metadata="))
{
System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder efBuilder = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder(connectionString);
connectionString = efBuilder.ProviderConnectionString;
}
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
DatabaseServer = builder.DataSource; // eg "MikesServer"
DatabaseName = builder.InitialCatalog; // eg "Northwind"
I'm going to throw out another answer, just in case someone else runs into this through the same weird scenario as I did.
To start with, as others have said, ADO connection strings and EF connection strings are different.
An ADO connection string contains a number of semicolon-separated fields, which can very from one connection type to another, but you usually see "data source=xxx", "initial catalog=yyy", etc. You will not see "metadata=zzz".
An EF connection string has the same structure, but it has a "metadata=zzz" and a "provider connection string=www", where "www" is an escaped ADO connection string.
So a normal format for an ADO connection string is:
data source=myserver;
initial catalog=mydatabase;
Persist Security Info=True;
User ID=myusername;
Password=mypassword;
MultipleActiveResultSets=True
While a normal format for an EF connection string is:
metadata=res://*/MyDbContext.csdl|
res://*/MyDbContext.ssdl|
res://*/MyDbContext.msl;
provider=System.Data.SqlClient;
provider connection string="
data source=myserver;
initial catalog=mydatabase;
Persist Security Info=True;
User ID=myusername;
Password=mypassword;
MultipleActiveResultSets=True;
application name=EntityFramework
"
Most folks who are running into this problem seem to have cut an EF connection string and pasted it into a place that needed an ADO connection string. In essence, I did the same thing, but the process wasn't as clear as all that.
In my case, I had a web application that used EF, so its web.config properly contained EF connection strings.
I published a deployment package, and the process prompts you for the connection strings to be used when deploying. These are stored in the deployment package's generated SetParameters.xml file.
I cut and pasted the EF connection strings into the publish dialog's entry fields.
I deployed the web application, tried to access it, and got the "Keyword not supported: metadata" error.
What I didn't realize is that MS's publish tool expected an ADO connection string, and that given it it would construct an EF connection string.
The result was that SetParameters.xml and my deployed web.config had connection strings that looked like this:
metadata=res://*/MyDbContext.csdl|
res://*/MyDbContext.ssdl|
res://*/MyDbContext.msl;
provider=System.Data.SqlClient;
provider connection string="
metadata=res://*/XxDbContext.csdl|
res://*/XxDbContext.ssdl|
res://*/XxDbContext.msl;
provider=System.Data.SqlClient;
provider connection string="
data source=myserver;
initial catalog=mydatabase;
Persist Security Info=True;
User ID=myusername;
Password=mypassword;
MultipleActiveResultSets=True;
application name=EntityFramework
"
""
In other words, the embedded provider connection string was an EF connection string and not an ADO connection string, so when EF tried to use it to connect to the database, it generated this error.
In other words, when you are pasting the connection strings into the publish dialogues, you need to paste a ADO connection string, not an EF connection string, even if what you have in the web.config you are copying from is an EF connection string.
You can extract an ADO connection string from the provider connection string field of an EF connection string, and that's what you will need, if you're using the same connection in the deploy as you did in local development.
For use in Azure Application Settings => Connection Strings:
If the connection string is generated by EF-designer be sure to replace &qout; with " in the string.
Check that provider=System.Data.SqlClient
Choose Type Custom in the dropdown
If the connection is for a model (Entity Framework) ensure that correct path to your model is used
Ex: A model "MyWebRoot/Models/MyModel.edmx" is configured as: metadata=res:///Models.MyModel.csdl|res:///Models.MyModel.ssdl|res://*/Models.MyModel.msl;
Hi,
In my opinion, the connection string for ADO.NET (in this
caseSqlConnection) can't use 'metadata. You're using the one specific
for Entity Framework. The ADO.NET one should be something like:
"data source=KAPS-PC\KAPSSERVER;initial catalog=vibrant;integrated security=True"
So, to sum it up, you need two separate connection strings, one for EF
and one for ADO.NET.
Souce: http://forums.iis.net/post/2097280.aspx
For Azure Web App, Connection string type has not "System.Data.EntityClient", Custom works good.
Dry This,
Remove metadata Info from your ConnectionString.
Change this.
<add name="DefaultConnection" connectionString="metadata=res://*/TalyllynModel.csdl|res://*/TalyllynModel.ssdl|res://*/TalyllynModel.msl;provider=System.Data.SqlClient;provider connection string="data source=***********;initial catalog=********;persist security info=True;user id=*********;password=********;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.SqlClient" /></connectionStrings>
To
<add name="DefaultConnection" connectionString="data source=***********;initial catalog=********;persist security info=True;user id=*********;password=********;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.SqlClient" /></connectionStrings>
Before i give My Solution let me explain something , I got this problem too , im using EntityFramework and Ado.net you cant use Entity framework Connection string in ADo and vice versa , so what i did was in the Web.config file i left the EF Connection string(Metadata one)
and in the Controller for ADO i Added the connection string which i got from the database(properties). add the ADO string like this :
SqlConnection sql = new SqlConnection();
sql.ConnectionString = #"Data Source=.\alienbwr;Initial Catalog=ABTO_POS;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";(dont use my string)
An old post but my solution,
Unfortunately these didn't solve it for me using Azure Functions talking to a separate project (class library) with an EDMX.
I had to edit the Context.CS class constructor replacing the
: base ("Entities")
with
: base (ConfigurationManager.ConnectionStrings["Entities"].ConnectionString)
Hopefully this might help someone else in need.
Check in this place
<add name="ConnectionString" connectionString="Data Source=SMITH;Initial Catalog=db_ISMT;Persist Security Info=True;User ID=sa;Password=#darksoul45;MultipleActiveResultSets=True;Application Name=EntityFramework"
providerName="System.Data.SqlClient" />
As you can see there's a two connection string one for ADO and another for the Login System or whatever you want. In my case, ConnectionString is for Login system so I've used that in:-
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = null;
SqlDataReader dr = null;
protected void Page_Load(object sender, EventArgs e)
When I add a database to a program, Visual Studio automatically creates the following connection string:
<connectionStrings>
<add name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString" connectionString="Data Source=|DataDirectory|\PlayerTeam.sdf" providerName="Microsoft.SqlServerCe.Client.3.5" />
<add name="PlayerTeamEntities" connectionString="metadata=res://*/edmPlayerTeam.csdl|res://*/edmPlayerTeam.ssdl|res://*/edmPlayerTeam.msl;provider=System.Data.SqlServerCe.3.5;provider connection string="Data Source=|DataDirectory|\PlayerTeam.sdf"" providerName="System.Data.EntityClient" />
</connectionStrings>
I am trying to allow the user to select the database that they would like to open. How do I modify the connection string programmatically without losing my associated dataset and tableadapter?
Thanks in advance :)
you can use that method to call your connection string from your App.Config file to be used in the data connection or adapter
public string GetConnectionStringByName()
{
string returnValue = null;
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["Connection Name Here"];
if (settings != null)
returnValue = settings.ConnectionString;
return returnValue;
}
when you add a new database to your project it takes the same connection Name of the existing database plus a number by default.
so you can make the connection string as a variable and add the number to it when you add a new database.
Edit
By considering you will add databases to your project grammatically, then if you added a new data base.
it will take that connection string's Name:
name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString1"
as it add a number at the end of the name of the existing database
so, you can invest the method i provided, to add the specified connection string Something like that:
public string GetConnectionStringByName(int DB_Number)
{
string returnValue = null;
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["Connection Name Here"];
if (settings != null)
returnValue = settings.ConnectionString+Convert.ToString(DB_Number);
return returnValue;
}
as the DB_Number variable could be saved in an XML file in order not to be loosed and its increased each time you add database.
So, if you add a new database to the existing 1 the connection Name should be:
name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString1"
and if you added another database the DB_Number will be increased by 1 to change the connection name to be :
name="TeamSortingTool.Properties.Settings.PlayerTeamConnectionString2"
and enable the user to choose with connection string he wants to use.
on the other hand . if your databases added manually before the application runs.
it will be easier to Handle as what you just have to do is to save your connection string in a data structure as an array and call the wanted connection to use
that is what i figured out from your question
I'm encountering a problem with my database connection.
I started with a new blank solution, then I added a WCF library project, and last but not least a WCF website (service).
In the website i added a reference to the library where I have the interface (data contract), the class that implements the interface and the dataclasses.
what I'm trying to do is to connect to a database on a server and try to retrieve some data from there.
So the connection string looks like:
<add name="myConnectionString" connectionString="Data Source=MyServer; Initial Catalog=MyDatabase; User Id=me; Password=me123;" providerName="System.Data.SqlClient" />
and this is how I'm trying to connect with the database:
public List<string> GetEngagements(string id)
{
string sql = "SELECT myColumn FROM myTable WHERE Id = '" + id + "'";
string connString = string.Empty;
SqlConnection connDB;
connString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
connDB = new SqlConnection(connString);
SqlCommand command = new SqlCommand(sql, connDB);
connDB.Open();
SqlDataReader rdr = command.ExecuteReader();
List<string> numbers = new List<string>();
while (rdr.Read())
{
numbers.Add(rdr[0].ToString());
}
rdr.Close();
return numbers;
}
I'm getting an exception on connDB.Open().
Then exception message says:
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.
I've been getting this message for 2 days now, I've googled a lot and deleted the C:\Documents and Settings\username\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS directory but it didn't work for me..
Any solution???? help please
The error message:
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance.
Suggests that you're using user instancing, and therefore your connection string will point to an .mdf file on disk rather than the name of a database.
So I'll assume that you want to connect to a file instance rather than a server instance.
I'll also assume that you're using SqlExpress rather than the full fat version.
In which case your connection string is wrong. It should look more like this:
"Data Source=.\SQLEXPRESS;
AttachDbFilename=fileOnDisk.mdf;
Integrated Security=True;
User Instance=True;"
User instancing means that this server instance and the DB inside will only be visible to the application opening the connection string.
You don't have to use user instancing - you can set User Instance=False or just leave it out. Then once the application has made the connection you can connect other tools to the server instance and connect to the DB yourself.
I am developing an asp.net application which I have hosted on an IIS server. To open a connection I use:
SqlConnection con = new SqlConnection("Server = INLD50045747A\\SQLEXPRESS;
Database = MyDatabase;User ID = sa; Password = Welcome1; Trusted_Connection = False;");
con.Open();
Is it possible to store this connection string somewhere so that I don't need to write in every aspx.cs file? I am using MSSQL database.
I'm facing an issue which says:
The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached
I read somewhere which asks me to increase the maximum connection pool to 100. Will it affect the performance of my application?
You probably aren't closing your open connections propertly.
Increasing the "pool size" is like putting a bigger bucket under a waterfall - it will help, but barely.
Try and locate areas where something like this is happening:
con.Open();
Ensure that if it's not in a try/catch, that it is in one, and that it includes a finally statement.
try {
con.Open();
//several other data base releated
//activities
} catch (Exception ex) {
// do something
} finally {
con.Close();
}
Also, to avoid having to use the finally block, you can just wrap the SqlConnection in a using statement.
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["yourKey"].ConnectionString))
{
// write your code here
}
In regards to your question about connection string, yes store it in your web.config
<connectionStrings>
<add name="name" connectionString="Data Source=;Initial Catalog=;User ID=sa;password=;Persist Security Info=True;Connection TimeOut=20; Pooling=true;Max Pool Size=500;Min Pool Size=1" providerName="System.Data.SqlClient"/>
</connectionStrings>
Store it in the web.config file, in the connectionStrings section:
<connectionStrings>
<add name="name"
connectionString="Data Source=;Initial Catalog=;User ID=sa;password=;Persist Security Info=True;Connection TimeOut=20; Pooling=true;Max Pool Size=500;Min Pool Size=1"
providerName="System.Data.SqlClient"/>
</connectionStrings>
And then you will be able to access this in your code...
ConfigurationManager.ConnectionStrings["name"].ConnectionString
you can do using also
it will automatically disposes the object
if you use "using" there is no need of con.close and all
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["yourKey"].ConnectionString))
{
// write your code here
}
Store the connection string in the web.config files. you can find numerous examples. Check this for the properties. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring%28v=vs.71%29.aspx
Thanks
Shankar
Use the Help of Both
try
{
con.Open();
}
catch(Exception ex)
{
if(con.State== ConnectionState.Open)
con.Close();
}
finally
{
con.Close();
}
and also add the Connection String in Web.Config, under Configuration. This will help you.
Yes, store it in the web.config file but make sure that if there is an error it doesn't display the content of the web.config file to the user (thus showing the world your password.)
If you use that same connection string in a lot of applications you could consider writing a service to provide the connection strings, that way you only have to change them in one place.
The best option is to use typed settings.
Open your project properties.
Go to Settings tab.
Add new setting, for example MainConnectionString, select setting type (ConnectionString). In the value insert your connection string or hit '...' button to bring a dialog to build connection string.
Now you can reference your connection string in the code like this:
Settings.Default.MainConnectionString
If you open your config file you will see
<configuration>
<connectionStrings>
<add name="WebApplication1.Properties.Settings.MainConnectionString"
connectionString="Data Source=localhost;Initial Catalog=AdventureWorks;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
You can have this connection string
specified:
for one web site in its own web.config.
for a group of web sites
for all web sites on a box: in machine scope web.config.
for all application on a box: in the machine.config.
This can be convenient if you have a lot of applications that connect to the same db and are installed on one box. If db location changes you update just one file machine.config, instead of going to each application's config file.