I have a console app containing an application configuration file containing one connection string as shown below:
<configuration>
<connectionStrings>
<add name="Target"
connectionString="server=MYSERVER; Database=MYDB; Integrated Security=SSPI;" />
</connectionStrings>
</configuration>
When I pass this to my Connection using:
ConfigurationManager.ConnectionStrings[1].ToString()
I have two values in there, hence using the second in the collection, my question is where is this second coming from?
I have checked the \Bin version and original and its not mine! Its obviously a system generated one but I have not seen this before? Can anyone enlighten me?
The mystery connection string is:
data source=.\SQLEXPRESS;
Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;
User Instance=true
This isn't a problem as such I would just like to know why this is occuring? Thanks in advance!
For future reference to those who may or may not stumble on this, after discovering the machine.config, it's become apparent it is bad practice to refer to a config by its index as each stack will potentially be different, which is why "Keys" are used.
In this instance my code would be:
ConfigurationManager.ConnectionStrings["Target"].ToString()
Cheers all!
Check your machine.config. If you only want your entry, you can add a <clear /> element to the <connectionStrings> element like so ...
<connectionStrings>
<clear />
<add name="Target"
connectionString=
"server=MYSERVER; Database=MYDB; Integrated Security=SSPI;" />
</connectionStrings>
Check your machine.config (under WindowsDir\Framework). I just checked mine and I have the same thing.
It's defined in the machine.config file, and it's global to all .Net applications on the machine.
Connection strings "stack" through the configuration hierarchy, which is why the element name for your own connection string is tagged "add". You're adding your own connection string to the list of machine-level connection strings.
It might be preferable to use:
ConfigurationManager.ConnectionStrings["Target"].ConnectionString
to ensure you get your own connection string, even if the machine.config is modified.
The Index first Element in the Connection Strings tag is stored By default And it's represents the > MemberShip database Connection String.
Cause of the Consideration for CLR is to be used during your application , So that the CLR On your behalf attaches it By default .
Like what is the CLR Doing with Default Constructor in the Class Creation without Constructor.
Related
I am looking to make it possible for my application to change it's connection string at runtime. I have a connection string in the Web.Config file, but when I update the config file and restart the application, the connection string does not update. Also, I do not seem to be able to use the configuration manager from within my application. Is changing the connection string in the Web.Config file the best way to go about making this a dynamic connection?
<add name="486f1ab5-d3c4-4fc5-805b-0afbcf0fa46b" connectionString="Data Source=.\MyServer;Initial Catalog=Mydatabase;Integrated Security=True" />
Here is a blog post that goes over what you need to do:
LightSwitch Dynamic Connection Strings Now Supported
I have the following connection string:
<?xml version="1.0" encoding="utf-8"?>
<connectionStrings>
<add name="MyContext" connectionString="metadata=res://*;provider=System.Data.SqlClient;provider connection string='data source=SQLSERVERDB;initial catalog=TestDB_CodeFirst;user id=***;password=***;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
When I try to enable migrations I first get a warning:
Cannot determine a valid start-up project. Using project 'MyApp.Model' instead.
Your configuration file and working directory may not be set as expected.
Use the -StartUpProjectName parameter to set one explicitly.
Then I get this exception:
Argument 'xmlReader' is not valid. A minimum of one .ssdl artifact must be supplied.
Is the connection string wrong and why should I need ssdl if I'm using Code First?
NOTE
My context is in MyApp.Model project where my Migrations folder should be located.
I don't have connection strings in my main startup project because connection strings are retrieved from a second database and the user can select one of them when logging in to the application.
I have just one connection string shown above in my MyApp.Model project which points to my development database.
Also, my second question is:
If I use CF migrations, will all databases be migrated each time a user selects a different database for the first time?
EDIT
I changed the connection as mentioned below, and I get the following exception:
The item with identity 'table1' already exists in the metadata collection.
Parameter name: item
It must be noted that I reverse-engineered an existing database. So I don't know what possibly went wrong!
I've also deleted the Migrations folder and checked the database but there is no migration_history table created.
You are trying to use a connectionString designed to work with Database First / Model First. You can tell because your providerName is System.Data.EntityClient instead of System.Data.SqlClient.
Your connection string should look like this:
<connectionStrings>
<add name="MyContext"
connectionString="Data Source=SQLSERVERDB; Initial Catalog=TestDB_CodeFirst;user id=***;password=***;"
providerName="System.Data.SqlClient" />
</connectionStrings
Although I would suggest using Integrated Security instead of a user/password. Just personal preference, though.
I am trying to set up a simple ASP.NET MVC 4 webapp using DB first migrations from a SQL Server (2005). I have created the tables in the database and used Entity Framework to create the objects in the code. I can access the data using these objects.
The problems come when I try to initialize the WebSecurity using WebSecurity.InitializeDatabaseConnection("FLMREntities", "UserProfile", "UserId", "UserName", true); in the Global.asax.cs file. I have tried using the InitializeSimpleMembershipAttribute filter that came with the template and got the same issue. I get the error message:
Unable to find the requested .Net Framework Data Provider. It may not be installed.
Here is the relevant connection string:
<add name="FLMREntities"
connectionString="metadata=res://*/Models.FLMR.csdl|res://*/Models.FLMR.ssdl|res://*/Models.FLMR.msl;
provider=System.Data.SqlClient;
provider connection string="data source=notes.marietta.edu;
initial catalog=muskwater;
user id=muskwater;password=********;
MultipleActiveResultSets=True;
App=EntityFramework""
providerName="System.Data.EntityClient" />
Also, I have created the membership tables in the database to match what the template creates. If I change the final parameter in the Initialize call to false (so that it does not try to create the tables automatically) it returns that it cannot find the UserProfile table. I have also tried variations on the names, such as [dbo].[UserProfile].
All I need is to have a simple account model to allow users to log in and allow certain users to see more content.
I had a similar problem, what I've done:
I modified the default connection. I already had a connection string for the edmx model, which looked like this:
<add name="ChemicalReporterEntities" connectionString="metadata=res://*/ChemicalDB.csdl|res://*/ChemicalDB.ssdl|res://*/ChemicalDB.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLExpress;initial catalog=ChemicalReporter;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
But I cannot used it with the SimpleMemebrship provider. So in Visual Studio I opened the Server Explorer > Data Connections, I selected my connection, right click, properties and I copied the connection string from there and pasted it to defaultConnection:
<add name="DefaultConnection" connectionString="Data Source=.\SQLExpress;Initial Catalog=ChemicalReporter;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework" providerName="System.Data.SqlClient" />
After that I changed WebSecurity.InitializeDatabaseConnection to use the DefaultConnection.
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", true);
This could be a duplicate of this.
From what I remember about this problem, you need to make sure that the sqldata provider is registered. Sometimes, in your machine.config there is a duplicate entry that you need to delete and if I remember correctly, there could be an erroneous entry that you need to remove. Have a look at this msdn post, the info for this is about halfway down the page.
The link to the other SO has some links that could be helpful. If this ends up not being marked as a duplicate question, I can add them here as well or whatever is the proper thing to do.
The section you are looking for will look similar to this I think:
<system.data>
<DbProviderFactories>
<add name="SqlClient Data Provider"
invariant="System.Data.SqlClient"
description=".Net Framework Data Provider for SqlServer"
type="System.Data.SqlClient.SqlClientFactory, System.Data,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
/>
</DbProviderFactories>
</system.data>
From the information you have provided in comments, it seems that this is missing in your machine.config. Unless I am mistaken (possible) that means that the SQL Provider isn't registered on your machine. You'll need to add the above section to your web.config. You'll also need to make sure that System.Data.SqlClient is referenced in your project.
If this isn't installed on your target machine, you'll have more work to do, getting it installed. I wish I could help you with that more, but when I did this, it was for SqlServerCE, so the files I used are much different.
Good luck!
EDIT:
A critical piece of information, is the version needs to match the file that you are using. in type="blabh..blah..blah..Version=2.0.0.0, blah blah" that needs to be the version of the file you are using so right click your file and get the file version. If it fails, try variations of the version. I believe my file was 2.0.0.1 but Version=2.0 is what worked when I did it. Just try a few different versions based on your version number (2.0, 2.0.0, 2.0.0.1 for example).
Just wanted to chime in here, that I had this issue, by looking at my machine.config for the targeted .NET version that I was running off of... within the structure:
ensure that your targeted data providers are correctly inputted within there, only one per provider (I have seen duplicates cause problems), as well as, ensure that it is valid XML, and you only have one DBProviderFactories entry. In my case, I had a entry after the initial entry (essentially two entries, one with my providers, one blank), and the blank was was causing all the issues.
Hope this helps someone with the same issue :)
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient Provider, not valid."
I have a working console project. However when I tried to copy the exe and the app.config (same folder) to a live server it didn't work and got the following error. Could it be a domain issue, or some setting that's baked in? I'm pretty sure it has access to databases since I have used other projects except this time is different because I chose edmx.
<connectionStrings>
<add name="AdvWorksEntities" connectionString="metadata=res://*/GroupsModel.csdl|res: //*/GroupsModel.ssdl|res://*/GroupsModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=abcd;Initial Catalog=AdvWorks;Persist Security Info=True;User ID=user;Password=pass;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
Solution
The app.config is a file name used in a project. However, when it is compiled, the file name becomes application's exe name + .config.
For example, if the application name is "sample.exe", then the configuration name should be "sample.exe.config".
I've got 3 connectionstrings in web.config, and I used theirs like this:
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SomeName"].ConnectionString))
Every metgod is called by winforms application.
One of webmethods doesn't work properly because it reads only one connectionString:
data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
It's not a connectionString from my web.config .
I invoke every method in the same way.
How it's impossible ??
EDITED:
I use facade: This is structure:
WinForms calls WebMethod SaveItem
SaveItem calls method on Facade: SaveItemAndDoDatabaseStuff
SaveItemAndDoDatabaseStuff does database stuff.
We can't see your web structure, but is it possible that your app isn't configured as an application in IIS, therefore is picking up the master web.config? Which would look exactly like that...
Go into IIS and ensure it is an application (it may have a cog icon).
If your WinForms application talks directly to database X (not via the web service), then the connection string for database X should be in app.config (in the WinForms project).
If your Web Service (as I understand, this includes your facade and your database layer), talks to databases X, Y and Z, then the connection strings for X, Y, and Z need to be in web.config (in the Web Services Project).
It's using the default connection string asp.net has (in the machine.config in the .net installation folders).
Do a clear:
<configuration>
<connectionStrings>
<clear/>
... your connection strings here
</connectionStrings>
</configuration>
Btw, when you say you are using "SomeName" in the connection string. It isn't surely any random connection string you used, its the default: "LocalSqlServer".
You should store the connection-strings in the web.config or app.config in whatever project that you are executing.
In your case, you should have the connection-strings in your app.config for your winforms application.
Why not just add a Trace line to print out the configuration file being used just before you ask for the connection string. Simply add the following line:
System.Diagnostics.Trace.WriteLine(
System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile,
"APP_CONFIG");
Set a breakpoint after this and look at the Output window for a line that starts with "APP_CONFIG:". This will give the full path to the configuration file and allow you to determine where it's being loaded. If you still see a discrepancy between the runtime values and the configuration file then likely something is changing those values at runtime within your application.
This is a late answer, but perhaps worthwhile.
I have a web-service project, and I want to run it in two modes.
One is "local as app" (for testing), and for that, at least in my current system setup, the file where it reads from is
Web.config (which it apparently reads in deug mode INSTEAD of Web.Debug.config, at least for database configuration)
So, one replace the attribute section with and copy in the ones you would use in the "Calling project for hte web service).
So replace
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
with
<appSettings>
<!-- Database Connection -->
<add key="AppDatabase" value="RedactedDatabase"/>
<add key="AppLoginID" value="RedactedLoginID"/>
<add key="AppLoginPwd" value="RedactedPwd"/>
</appSettings>
The above are found in app.config in the "calling project".... To me, this is more elegant anyway.
Now it will work in both modes.
One could use a conditional compile in the C#, but now you just read it in:
C# code:
String whichDatabase = System.Configuration.ConfigurationManager.AppSettings["AppDatabase"];
String appUsedID = System.Configuration.ConfigurationManager.AppSettings["AppLoginID"];
String appUsedPwd = System.Configuration.ConfigurationManager.AppSettings["AppLoginPwd"];
The above works in either mode, without conditional compile directives.