Changed Database Name -- Datatable Adapters broke - c#

We've recently changed the name of the SQL DataBase our WebApp is using. Now, each of the DataTableAdapters will update to the new ConnectionString.
Our setup is as follows:
1) Interface (WebSite Project)
2) Business Logic (Class Library Project)
3) Data Access (Class Library Project) ---> Contains many DataSet classes
The app.config of the Data Access project contains the only connection string. When creating each of the DataTableAdapters, the wizard points to it correctly. Now, we've had to change the ConnectionString, and all of the existing DataTableAdapters (about ~60) will not work.
Simply changing the ConnectionString has not worked. What am I missing?
Thanks

Make sure the connection string name in your config is the same as the one in the Settings File. Because in the generated code, when it initialzed the connectionstring it setting the connection string as follow :
private void InitConnection() {
this._connection = new global::System.Data.SqlClient.SqlConnection();
this._connection.ConnectionString = global::ConsoleApplication4.Properties.Settings.Default.MyConnectionString;
}
Make sure that in your app config the name of your connectionString is the same. for example
<connectionStrings>
<add name="ConsoleApplication4.Properties.Settings.MyConnectionString"
connectionString="Data Source=MyServer;Initial Catalog=MyDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>

The problem was in the Settings.Designer.cs file. Its an auto-generated file that did not update after the normal updating/clean/build process.
Thanks Everyone :-)

Related

How do I set a default connection string in a console application?

In my MVC projects with a web interface, I'm used to setting the Connection String in the Web.Config file.
However, now I'm making a bog standard console application - also with a database hook, but how do I set the connection string globally for the application?
At the moment, I am setting
var dbIndex = new DBContext();
dbIndex.Database.Connection.ConnectionString =
"Data Source=USER-PC;Initial Catalog=TextProject.DBContext;" +
"Integrated Security=True;MultipleActiveResultSets=True";
but I have to set this connectionstring property every time, in all function calls. Is there a way to set a global connection string when I don't have a web.config?
So I think what your saying is that Entity Framework (I assume that is what you are using) looks for defaultConnection connection string.
You can try putting it in the app.config file as suggested by others, but I'm not sure if this will be automagically picked up by EF.
What you could do, if it doesn't work, is to create new class which inherits DbContext -
public class MyDbContext : DbContext
{
public MyDbContext() : base()
{
var cs = ConfigurationManager.ConnectionStrings["defaultConnection"]
.ConnectionString;
this.Database.Connection.ConnectionString = cs;
}
}
App.config is the equivalent to a Web.config for console or .exe programs.
Add a reference to System.Configuration on any project that you want to use the ConnectionStrings of the app.config
Add a AppConfig to your entry point project. This is the project that is executed. (e.g. console .exe)
Add the connection string in the <connectionStrings></connectionStrings> section of the app.config
Now place the connection string in your app.config
string connStr =ConfigurationManager.ConnectionStrings["ConnName"]
.ConnectionString;
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="ConnName" connectionString="Data Source=USER-PC;Initial Catalog=TextProject.DBContext;Integrated Security=True;MultipleActiveResultSets=True" />
</connectionStrings>
</configuration>
As others have said put your connection string in the App.config file.
Regarding Entity Framework. If you are using Entity Framework (EF) version 6.2.0 perhaps earlier EF will automatically look for a connection with the same name as the class that inherits from DbContext.
If your class is
public class MyDatabaseContext : DbContext
{
// other code
}
EF will look for a connection string with a name like this
<add name="MyDatabaseContext" ...
You can also set the name in the constructor like so
public class MyDatabaseContext : DbContext
{
public MyDatabaseContext() : base ("name=defaultConnection")
{
// other code
}
// other code
}
In this case your connection string name can be <add name="defaultConnection" ...
You can put the same element in a App.config file for the console application and access it the same way you would a Web.config.
Related: What is App.config in C#.NET? How to use it?
The solution is very simple and easy. Just right click and set the project as start-up project. entity framework by default picks the start-up project and uses the connection string inside of App.config or web.config
Please refer to this:

How to set the database name in the connection string with Entity Framework 5

So I have Solution with two projects. The first projects should act as a Data Access Layer so there in the app.config file I have this:
<connectionStrings>
<add name="BloggingContextCF"
connectionString="provider=System.Data.SqlClient;
provider connection string="
data source=*****\SQLEXPRESS;
initial catalog=CodeFirst.Blogging;
integrated security=True;
MultipleActiveResultSets=True;
App=EntityFramework""
providerName="System.Data.EntityClient" />
The second Project is a ASP.NET Web Forms project, where I removed the default connection string pointing to the (local) instance leaveing only one connection string, the one from the first Data Access Layer project. Which actually works and the database is created on my SQL 2008 R2 server, but instead of the desired (and expected) database name - CodeFirst.Blogging the name is DataAccessLayer.BloggingContextCF where DataAccessLayer is the name of the project and BloggingContextCF is the class extending DbContext.
What I need to change in my connection string so I can get the desired name?
Try
public BloggingContextCF ():base("CodeFirst.Blogging") {}
make the connections string like
Point it to sql client
providerName="System.Data.EntityClient"
to
providerName="System.Data.SqlClient"
For full connection string do it like
<add name="BloggingContextCF" connectionString="Server=YOUR_SERVER;Database=DATABASE_NAME;User ID=USER_ID;Password=PASSWORD;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.SqlClient" />
For more connectionstring example follow the link
and don't forget to modify your dbcontext
public class YourContext : DbContext
{
public UsersContext()
: base("BloggingContextCF"){ }
}

EF 6.0 Code first Compact Edition: incorrect connection string or app.config problems?

ask your advices about this:
I am trying to create db compact edition,
first time it was successfully with default dbName (ProjectName.dbContextName).
But i decided to define my own name, and added in app.config in connectionString sections my connection string. After db was not created.
From here MSDN Use code first with connection by convention i have done similar connection string:
<connectionStrings>
<add name="TestContext"
providerName="System.Data.SqlServerCe.4.0"
connectionString="Data Source=TestDb.sdf;"/>
</connectionStrings>
(section name is equal to my dbcontext's name class.)
Just to be sure before dbContext will be created:
Database.SetInitializer(new DropCreateDatabaseAlways<TestContext>());
Db still is not created. What am i doing wrong? Thanks in advance.
VahidN, i tried to add call of base class constructor, but doesn't work. Don't understand. It should be very easy. And as were aforementionted in ref above, if name of connection string in config section and name dbContext class are equal - object finds its connection string without problems.
Well, debugger says that conString is defined correctly (equal to string in config section), but actually db is not created - i can't find it nor in appfolder nor in sql server folders.
You need to include the full namespace in the name of the connection-string. See here.
Something like this
<connectionStrings>
<add name="YourNameSpace.TestContext"
providerName="System.Data.SqlServerCe.4.0"
connectionString="Data Source=TestDb.sdf;"/>
</connectionStrings>
Oh, sorry me for giving insufficient information, db was not created cause entities in dbContext was defined as List, not dbSet. inadvertency (

How to separate connection string and get connection string from a class in C#

I'm newbie in C#. I want to ask, how can I separate the connection string config into a class?
Because every time I want to write code, I need to re-write the connection string and test the connection. So, I need to make a class so that every time I make a connection to the database, this class will test the connection first. Then after it works, the class will send the connection string to my coding.
Besides, if I want to change my source data, I just need to change in the class only. No need to search all my coding
So if I can make a class, how do I call and get the connection string from class?
Can it be like that?
This is my current coding for connection string in C#
FileInfo file = new FileInfo(Application.StartupPath + "\\conn.txt");
if (file.Exists)
{
StreamReader r = File.OpenText(Application.StartupPath + "\\conn.txt");
connString = r.ReadToEnd();
r.Close();
// Open SQL connection
SqlConnection openCon = new SqlConnection(connString);
try
{
Cursor = Cursors.WaitCursor;
openCon.Open();
}
catch
{
MessageBox.Show("Error to established connection\nPlease check Data Source");
openCon.Close();
Cursor = Cursors.Arrow;
}
else
{
MessageBox.Show("File config is missing");
}
}
Hope you can teach me as a newbie in C#. Thanks for the help. And sorry for bad english.
You should store connection strings in your configuration file. If you don't have a configuration file, add one by right-clicking the project and 'adding new item...' If you are writing a web app it will be a web.config file; if you are writing a client app it will be an app.config file.
You add a connection string to the configuration file in the connectionStrings node, normally at the top of the file.
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<!-- add a string -->
<add name="MyConnectionString"
connectionString="Data Source=localhost; ... // etc
providerName="System.Data.SqlClient" />
</connectionStrings>
// and keep all the other configuration in the file
And then you simply refer to the configuration file using the ConfigurationManager class - you'll need to add a reference to System.Configuration if you don't already have one.
ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
You're trying to reinvent the wheel here. The .Net framework already include some simple techniques to handle this. If you're creating a Windows form project, you can store the connection string in App.Config using the connectionString attributes. If this is a web app, then you store it in web.config, here is how it would look like:
<connectionStrings>
<add name="Prod" connectionString="Server=myServer;Database=DB1;user=sa;password=myPassword;Trusted_Connection=false" providerName="SQL" />
</connectionStrings>
Then, in your code, you read the connection string from web.config as follow:
string connString = System.Configuration.ConfigurationManager.
ConnectionStrings["Prod"].ConnectionString;
You're asking a very basic question here and it indicates that you're trying to bully your way into learning c#. My advice to you is to grab a good C# book and go through it cover to cover to learn things the right way.
Instead of putting the connection string into a separate file, store it in your app.config or web.config file. .NET configuration files van contain a section that allows you to store connection strings:
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
You can retrieve this connection string using the following code:
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
I think Poster's question is pretty much valid. Although we can write connection string in Web.config or app.config once and use it in whole project, but there is a drawback of using this technique.
Connection string in web.config or app.config is never safe. These two files are ultimately like text files. There are ways to get the password from them. The security could be broken. So its better to use the connection string in a separate class file and get it in your whole project.
you could create a class which returns a sqlConnection...
public class DBConn
{
private string ConnectionString = "123456789Connection";
public SqlConnection getSqlConn()
{
return SqlConnection();
}
}

Entity Framework Connection String Trouble

I am making a little library(DLL) to manage users and their roles/privileges. The plan is to be able to add this dll to an MVC project and be able to manipulate users/roles/etc. All the data resides in a SQL db.
I am using entity framework for data access.
So when I initialize a new RoleManager(this is the name of the main class in the lib I'm making) I supply it with a connectionString like so:
RoleManager roleManager = new RoleManager(string connectionString);
Then inside the constructor I do this:
db = new RoleManagerEntities(connectionString); //This is the EntityFramework
And I am trying to supply this connection string (among many others)
"metadata=res://*/RoleManager.csdl|res://*/RoleManager.ssdl|res://*/RoleManager.msl;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60; multipleactiveresultsets=true'"
And I get the following error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
This question is a result of having trying to instantiate the EF from my new project without supplying a connection string and without having anything inside my app config for it to default to. Too bad I can't delete it now.
Just copy the connection string information from your DLL config file to your executable config file.
Basically you are trying to instantiate an ObjectContext via this ObjectContext Constructor (String) without passing the string parameter in its expected format and that's the problem.
Here is what you need to do:
1. First create an entry in your in your "test project" app.config because that is the place that the CLR is looking at to find the connection string at runtime.
<configuration>
<connectionStrings>
<add name="RoleManagerEntities" connectionString="metadata=res:///RoleManager.csdl|res:///RoleManager.ssdl|res://*/RoleManager.msl;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60; multipleactiveresultsets=true'" />
</connectionStrings>
</configuration>
2. Now change the code to pass the connection string name instead of the actual connection string:
db = new RoleManagerEntities("name=RoleManagerEntities");
The constructor might be looking for a connection string in the connectionStrings setting of your web.config with the name that you pass it as the parameter.
So if you call:
db = new RoleManagerEntities("Foobar");
It is looking for:
I'm not positive that this is the solution but that's what the error message seems to indicate.
I am not an expert on EF, but I don't think that connection string is valid. Try:
metadata=res://*;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60; multipleactiveresultsets=true'

Categories