C# and SQL Server CE - Data Source Keyword Not Supported - c#

I am trying the following solution and not having much luck:
How can i update app.config connectionstring Datasource value in C#?
The code I have is:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Because it's an EF connection string it's not a normal connection string
// so we pull it into the EntityConnectionStringBuilder instead
EntityConnectionStringBuilder efb = new EntityConnectionStringBuilder(
config.ConnectionStrings.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.TestDBConnectionString"]
.ConnectionString);
// Then we extract the actual underlying provider connection string
SqlConnectionStringBuilder sqb = new SqlConnectionStringBuilder(efb.ProviderConnectionString);
// Now we can set the datasource
sqb.DataSource = "|DataDirectory|\\TestDBa.sdf";
// Pop it back into the EntityConnectionStringBuilder
efb.ProviderConnectionString = sqb.ConnectionString;
// And update...
config.ConnectionStrings.ConnectionStrings["WindowsFormsApplication1.Properties.Settings.TestDBConnectionString"]
.ConnectionString = efb.ConnectionString;
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
My app.config file has:
<?xml version="1.0" encoding="utf-8" ?><configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="WindowsFormsApplication1.Properties.Settings.TestDBConnectionString"
connectionString="Data Source=|DataDirectory|\TestDB.sdf"
providerName="Microsoft.SqlServerCe.Client.4.0" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup></configuration>
Where am I going wrong?

I've only been fiddling with SQL CE for a few days myself, but if you're doing anything with SqlCE database, you probably want to use SqlCe classes rather than Sql ones - try SqlCeConnectionStringBuilder?
Other than that, as long as |DataSource| is supported in CE the connection string you've posted looks like the examples I've seen & used.

I ended up creating my own XML file which stores the database string and lets the user update it if it is invalid or if they wish to connect to a different database. I think it works out better than trying to update the app.config.

Related

ConfigurationManager ConnectionString not working

I have this project I am working on and I want to "hide" my connection string from my main class and place it to the App.Config.
While trying to access the connection string from the main class I get this error "System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null."
This is my main class code that I use to get the conn string:
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString.ToString();
This is my App.Config code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="ConnString" connectionString="Password=XXXX;Persist Security Info=True;User ID=XXXX;Initial Catalog=XXXX;Data Source=XXXX"/>
</connectionStrings>
</configuration>
Note: I have to add the app.config by myself as a new class.
Also the connection string works perfect when it's in the main class, so it's not its fault.
The WebConfig connection string should be like this:
<connectionStrings>
<add name="DBCS" connectionString="server=.;database=MVCCrud;integrated security=SSPI" providerName="Sql.Data.SqlClient" />
</connectionStrings>
The main class connection string should be like this:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
I added config, added you code and configuration and it worked.
I can't add this as a comment, as I can't post images there, that's why I am writing an answer.
So, just to make sure you added the file in a correct way:
right click your project, add -> new item:
and then just find appropriate file to add (you can make use of search text box):

Incorrect connection string? Error: An attempt to attach an auto-named database failed

Solution: Add the directory to your connection string in the app.config file and the Settings.setting file in the properties section of your project. My working connection string ended up being <Value Profile="(Default)">Data Source=(LocalDB)\v11.0;AttachDbFilename=F:\hi\prgrm\ProgramName\Database1.mdf;Integrated Security=True</Value>
Once I run my program I get the following error:
An attempt to attach an auto-named database for file F:\Graded unit
2\SimplyRugby\LollipopUI\bin\Debug\Database1.mdf failed. A
database with the same name exists, or specified file cannot be
opened, or it is located on UNC share.
The method that makes the error happen:
public bool CheckUsername(string username)
{
var usernameResult = (from person in dbContext.Persons
where (person.Username == username)
select person.Username).FirstOrDefault();
//stores username if a username is found
return !(string.IsNullOrEmpty(usernameResult));
// if no correct user found from query return false else true
}
After some research apparently it's that the connection string is wrong. I had a little play with some suggestions online but I'm not too sure what is incorrect and how to fix it so I've been going around in circles for the past five or so hours.
My app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="LollipopUI.Properties.Settings.Database1ConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Thank you for your time.
Try to make User Instance property as true like
User Instance=True
in your connection string.
You can also refer to this related thread which says that your connection string should looks something like this:
<connectionStrings>
<add name="Sales_DBEntities"
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string='server=YourServerNameHere;database=Sales_DB;integrated security=True;App=EntityFramework'"
providerName="System.Data.EntityClient" />
</connectionStrings>
I have faced that situation and I resolved it like this.
Go to Setting of DataBase and set option **Copy to output Directory** to **Copy if Newer**
the problem will solve
Late response is better than no response at all:
The issue was that my connectionString wasn't mapped to the database location.
Edit: I'm not sure what the path I used was as it was so long ago but if you have this issue try using a full hardcoded path to the .MDF file. After you've confirmed it works then you can start fiddling around with it.

PetaPOCO with MS Access database

I'm trying to test PetaPOCO with MS Access database.
Connection string in web.config
<add name="ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Data.mdb; Persist Security Info=False" providerName="System.Data.Oledb" />
Accessing MS Access database-
var db = new PetaPoco.Database("ConString"); //throws exception here
var rows = db.Query<Model>("SELECT * FROM Table");
Exception thrown-
"Could not match `System.Data.Oledb` to a provider.Parameter name: providerName"
Is there any way to do it? If yes, how?
Starting with PetaPoco version 5.1.127 or later, MS Access support is backed in and no custom DB provider is required.
Sample config file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<clear />
<add name="msaccess" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|Databases\MSAccess\petapoco.accdb" providerName="OleDb"/>
</connectionStrings>
</configuration>
Fluent configuration
var builder = DatabaseConfiguration.Build().UsingConnectionName("MyConnection");
var db = builder.Create();
Constructor configuration
var db = new Database("MyConnection");
As stated by their documentation "Works with SQL Server, SQL Server CE, SQLite, MySQL, MariaDB, and PostgreSQL. (Oracle supported but does not have integration tests).", it doesn't support MS Access
To use it, you would need to write your own provider. Samples of providers can be found here
I think what you really want is this
using System.Configuration;
and
var db = new PetaPoco.Database(ConfigurationManager.AppSettings["ConString"]);

connection string is not working in asp.net webforms

i registered my website on somee.com. for that i have uploaded MS SQL database. i was wrting this connection string in my code:
connectionString="metadata=res://*/nrcsaEntities.csdl|res://*/nrcsaEntities.ssdl|res://*/nrcsaEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=My-PC;initial catalog=nrcsa;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
now as i registered somee.com is providing me new connection string that is:
workstation id=nrcsadb.mssql.somee.com;packet size=4096;user id=DuaZoya_SQLLogin_1;pwd=abcd;data source=nrcsadb.mssql.somee.com;persist security info=False;initial catalog=nrcsadb
i have changed connectiong string in file web.config by replacing this first connection string with provided connection string by somee.com
PROBLEM:
This replacement is generating warning that:
System.ArgumentException: Keyword not supported: 'user id'.
how to solve this problem?
In the web.config file ....
<connectionStrings><add name="nameofConnection" connectionString="Data Source=servername; Initial Catalog=DatabaseName; User ID=UserName; Password=Password;"/> </connectionStrings>
<system.web>
<compilation debug="false" targetFramework="4.0" /> </system.web>
you can edit target Framework according to you.
from : http://dotnet-developers-cafe.blogspot.in/2013/08/create-connection-string-in-aspnet.html
You're using Entity Framework.
Entity Framework has its own connection string which contains a reference to the EF metadata (metadata=...) as well as the inner connection string to connect to the actual database.
You need to insert your actual database connection string inside the EF connection seting, in the provider connection string=... section.
You will also need to add multipleactiveresultsets=True to their connection string; EF needs that setting.
As you are using entity famework, then your connection string will look like
<connectionStrings>
<add name="BlogContext"
connectionString="metadata=res://*/BloggingModel.csdl|
res://*/BloggingModel.ssdl| res://*/BloggingModel.msl;
provider=System.Data.SqlClient
provider connection string="data source=[you somee.com connetion string];"" providerName="System.Data.EntityClient" />
</connectionStrings>
what you need to do is simply change the value of data source from the actual connectionstring provided by somee.com
Don't replace the whole connection string. You will need to remove the Integrated Security = true section and replace it with user=DuaZoya_SQLLogin_1;password=abcd.
Also change the data source to nrcsadb.mssql.somee.com.
You pretty much just need to replace values in your existing connection string with the values provided.

The underlying provider failed on ConnectionString

I am getting the following error trying to connect to DB2 Entity with .Net 4.0
The underlying provider failed on ConnectionString.
I get it on this line within the generated code of my entity cs file
public DOCUMAKRContainer() : base("name=DOCUMAKRContainer", "DOCUMAKRContainer")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
My App.config (which is created when you create entity the looks like this
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections />
<connectionStrings>
<add name="DOCUMAKRContainer"
connectionString="metadata=res://*/Documakr.csdl|res://*/Documakr.ssdl|res://*/Documakr.msl;provider=IBM.Data.DB2;provider connection string="Database=DCCPDEVL;User ID=documakr;Password=Dcpd#123;server.com:60000"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
I have tried to delete and rebuild the entity and get the same results every time. All of this is generated code when you add an entity object, so I am wondering if it is a VS 2010/IBM DB2 issue. Internet has not really given me any help.
Thoughts?
This site is a good resource: http://www.connectionstrings.com/
It looks you have have some garbage in your connection string:
provider connection string="Database
Actually, it looks like you've got a conection string jammed into your connection string.
Also, you might want to edit your post and remove or ##### the login info.

Categories