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.
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 a web application in C# with .NET Framework 4.0 and I'm trying to find a way to define a variable in Web.Config that can be referenced elsewhere within the Web.Config.
I want something like this.
<?xml version="1.0" encoding="utf-8"?>
<LocalWebConfigVars>
<add key="Var1" value="ServerName1"/>
<add key="Var2" value="DatabaseName1"/>
</LocalWebConfigVars>
<configuration>
<connectionStrings>
<add name="AppConnectionString" connectionString="DATA SOURCE=#Var2 ServerName=#Var1"/>
<add name="OtherStuff" value="#Var1"/>
etc...
Currently I have to keep 3 or 4 hard-coded values (some embedded others just the value) updated to the same thing and would like to make it easier to keep in sync.
Is this possible?
Thanks.
Edit:
Just some background. The reason this is becoming problematic is that we define the apps database instance (among other instance specific setting) in the web.config. We have multiple database instances in our test and production environments and if I need to switch to a different one them while testing something and miss one of the hand full of references I get some strange results. I'm trying to avoid this by defining it once and referencing it everywhere else.
Would not doing a simply .config transformation for each of your environments work, by setting up a project configuration & transform, you would be able to swap from environment to environment by the use of solutions configuration dropdown.
See this link
for more info on transforms on .config files
I and my team are currently doing a project, where we are using Entity Framework 4.1 (Code First). We want to write some tests, but we don't want them to run on our primary database, as we have a team in Singapore writing a client for what we do, and they are hitting that database constantly.
So to avoid disturbance when running our tests, we would like to have a different database for testing. How do we handle a second database when using Entity Framework? We want a solution that is semi-automatic (at least), so we don't have to fiddle around with Web.config each time we need to run tests.
Fiddling around with the web.config can a process that is prone to error... unless you are using web.config Transformations that is.
I would create a new configuration, "Test" for your project in Visual Studio... it can be a copy of your existing development configuration (or Debug / Release, whatever). Then, right click your Web.config file in Solution Explorer and click Add Config Transforms. Follow the instructions here on how to write a transform file. If you only need to change the EF connection string for the test environment it would look something like this in web.Test.config:
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add name="AdventureWorksEntities"
connectionString="metadata=.\AdventureWorks.csdl|.\AdventureWorks.ssdl|.\AdventureWorks.msl;
provider=System.Data.SqlClient;provider connection string='Data Source=TestDB;
Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;
multipleactiveresultsets=true'" providerName="System.Data.EntityClient"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
Just be sure to build under the correct configuration when you want to run your tests.
There is also a Visual Studio Add-in SlowCheetah Which makes this whole process very seamless from within the IDE.
Solution apprehended from this post:
//Get the connection string from app.config and assign it to sqlconnection string builder
SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(((EntityConnection)context.Connection).StoreConnection.ConnectionString);
sb.IntegratedSecurity = false;
sb.UserID ="User1";
sb.Password = "Password1";
//set the object context connection string back from string builder. This will assign modified connection string.
((EntityConnection)context.Connection).StoreConnection.ConnectionString = sb.ConnectionString;
This allows you to change connection string at runtime. There are couple of other possible solutions:
Create a wrapper property around connection string. From tests, set it to a different value.
Use #IF TEST pragmas to specify correct connection string at compile-time
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.
I have written an ASP.Net 3.5 WCF service and when I created this project VS gave me a web.config file to go with it. Having done this the app now seems entirely blind to connectionstrings, a big problem as the app will be heavily reliant on reformatting and spitting out SQL Server DB data in various web friendly formats.
Most of the references I've seen for getting WCF services equipped with DB Connections tell you to put the connection strings in App.Config files, I was keen to avoid this... and so is VS2008, as when I try to add a new app.config a straight configuration file is not a choice on offer, only a second web configuration file.
Seeing as I already have one perfectly good web.config file I would rather my data access code could just use that. I guess I'm probably missing something really obvious but:
ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString
Doesn't work as in debug the configurationmanager claims there are no connectionstrings defined, despite the fact that I have seven connectionstrings fully defined in the web.config file. I have using statements for System.Configuration, System.Web and System.Web.Configuration.
It seems as if even though the project seems to be designed to refer to a web.config this is not in fact the case. It also seems to be unable to access a regular app.config at present.
Having said all this all the httphandlers and endpoints in the web.config seem fine. If I define the connectionstring specifically when I call the datacontext it all works perfectly. It's specifically the connectionstring section of the config file that seems to be having an issue...
Any thoughts?
EDIT:
FWIW this is the (only slightly doctored) content of the ConnectionStrings section of the web.config.
<connectionStrings>
<add name="D_CS" connectionString="[the_connection_string]" providerName="System.Data.SqlClient"/>
<add name="PV_CS" connectionString="[the_connection_string]" providerName="System.Data.SqlClient"/>
<add name="L_CS" connectionString="[the_connection_string]" providerName="System.Data.SqlClient"/>
<add name="AL_CS" connectionString="[the_connection_string]" providerName="System.Data.SqlClient"/>
<add name="APV_CS" connectionString="[the_connection_string]" providerName="System.Data.SqlClient"/>
<add name="AD_CS" connectionString="[the_connection_string]" providerName="System.Data.SqlClient"/>
<add name="TV_CS" connectionString="[the_connection_string]" providerName="System.Data.SqlClient"/>
</connectionStrings>
Like I said anything else the file is supposed to do to assist in the execution of its duties it appears to do without issue or complaint.
FURTHER EDIT: The application is currently only in development, so is attempting to run through the VSHOST it will in the fulness of time be hosted on the web through IIS.
And yes, I have an explicit project reference to System.Configuration
UPDATE: To try to lock this down I had a go at passing the ConnectionString as a string from an AppSetting, as so far I have been using
DataServiceContext dsc = new DataServiceContext("connection string as string");
It can't see the AppSettings either.
Okay... this is interesting.
I wanted to test my REST URIs through a browser. Just to see that the URI typed into a browser would return the correct data.
Well, after much casting about I found that you need a sort of proxy WCF server to do that, just a little console app that runs a service did it nicely.
It turns out the wcf uses the Proxy's config, not the web.config of the IIS (or in this case VSHOST) hosted service. So if you tool that up with a reference to System.Configuration, bung in an app.config and copy the relevant connectionstrings section into that it works perfectly.
How irritating.
Y'all probably would have worked that out if I'd thought it was in any way relevant, which it shouldn't be... but is... bah.
Thanks for wasting time trying to help out.
WCF is designed to run on different types of bindings (HTTP, TCP, Message Queues, pipes, etc...). The classic webservice (asmx) is always running over HTTP. For this reason, by default, you don't get access to the web.config file.
If you want to be able to use asp.net's HTTPContext, you need to set the ASP.NET compatibility mode to true, like shown below:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
Please see this blog post for a more detailed discussion.
On a web server, you have to use WebConfigurationManager. Unless there is something I didn't know with the default ConfigurationManager.
Try..
using System.Configuration;
or
System.Configuration.ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString