Cannot read connection string from web API configuration when debugging in Visual studio 2010 - asp.net

Cannot read connection string from web API configuration when debugging in Visual studio 2010
I am writing an ASP.net web API application and this is my first one. I am trying to set up my connection string and retrieve it using the configuration manager. There are three configuration files, web.config, web.debug.config and web.release.config. In each of these files I have added my desired connection string and have removed the default connection strings. But configuration manager still pulls up a default database connection string from someplace. Doing a global search through all the files in the solution there is no indication where configuration manager is reading this default string. How can I get my application to read the connection string that I specify in the configuration files? Why is configuration manager not reading any of these configuration files?
This is the string that I get back from configuration manager that I have no idea where it is getting it:
data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
I am attempting to read the configuration string like this:
string CONNECT_STRING = ConfigurationManager.ConnectionStrings["Jobs"].ConnectionString;

Try using this connection string
<connectionStrings>
<add name="Sqlcnn" providerName="SqlClient" connectionString="Data Source=Datasource name; user id=userid; password=pwd; database=DbName" />
</connectionStrings>

Try using the below connection. Other case the connection you are using ./SQLEXPRESS might not exist.

When I encountered this problem I was running unit tests. For some reason when running unit tests the web API application does not read the connection string from the web config file. However, if I call the web API application from my client application the configuration string is read from the configuration file. I'm not exactly sure why the configuration file is not read during unit tests, but I'm sure I will figure it out in time.

Related

Azure App Service Connection string settings not available custom Session provider

I added all my connection strings to the App Service -> Settings screen.
I'm using Redis to share Sessions between the different instances. Everything is good if I have the connection in the ConnectionString section in the web.config but if I remove it from there and just add it to the Connection string section under the settings screen then it all breaks.
I'm running a classic .net web application on .net 4.7
I've tried the following so far:
Added a connection string in web.config without a value hoping it will overwrite it
Completely removed the connection strings in the web.config file.
Just for a test, I added an extra connection string which I can later retrieve and show on a web page.
How early do the connection strings from azure get applied? Is there a workaround or is this a known issue (haven't managed to find anything about it)?
EDIT: Here is a sample of what I'm trying to do.
I have a connection string called <add name="redis.sessions" value=""/> and a session state provider that points to that connection string
<add name="redis" type="Sitecore.SessionProvider.Redis.RedisSessionStateProvider, Sitecore.SessionProvider.Redis" applicationName="private" connectionString="redis.sessions" pollingInterval="2"/> and in the session provider on Initialization it tries to initialise the Redis connection with a blank connection string. Even through one has been provided in the App Service Settings.

Setting EF Connection String in Azure Web App

We have an ASP .NET (MVC) app and are using Entity Framework 6 to connect to our databases. The DbContext is constructed in a standard way and it loads the connection string on our behalf. The generated code looks like this:
public partial class MyContext : DbContext
{
public MyContext(string connectionName)
: base("name=" + connectionName)
{
}
}
We set the connection string in a local web.config also in a standard way:
<configuration>
<connectionStrings>
<add name="DefaultConnection"
connectionString="metadata=...;provider connection string="...""
providerName="System.Data.EntityClient" />
When we publish the app to Azure we navigate to the Azure Portal, then to the Web App's Settings, then to the list of Connection Strings. There we add the EF connection string that we had used locally. When we restart and visit the app we get a run-time error depending on the type of connection string we choose.
For a Custom type we get the following run-time error:
Keyword not supported: 'data source'.
For SQL Server or SQL Database we get the following run-time error:
Keyword not supported: 'metadata'.
This really seems like a straightforward story so we are wondering what is going wrong.
The problem is the escaped quotes: ".
The connection strings in web.config have quotes escaped because they are serialized in an XML attribute. When entering a connection string in the Azure portal you should provide the raw unescaped string. Something like this:
metadata=...;provider connection string="Data Source=..."
David Ebbo's answer is good for confirming that the Environment is set up as you expect. It is also helpful to pay attention to the .pubxml file when publishing via the wizard in Visual Studio: it will try to populate connection strings as well.
'custom' should be correct here. In that case, the providerName is left unchanged, so if you have System.Data.EntityClient in your config, that should remain after the Azure runtime changes it.
Try going to Kudu Console and click on Environment to make sure the conn string looks correct there.
If you have this line in web.connfig
<add name="Entities" connectionString="metadata=res://*/TestDB.csdl|res://*/TestDB.ssdl|res://*/TestDB.msl;provider=System.Data.SqlClient;provider connection string="Data Source=XXXXXXXX.database.windows.net,1433;Initial Catalog=YourDB;User ID=YourUser;Password=XXXXXX"" providerName="System.Data.EntityClient" />
Add this in azure portal:
Name Column => Entities
Value Column => metadata=res://*/TestDB.csdl|res://*/TestDB.ssdl|res://*/TestDB.msl;provider=System.Data.SqlClient;provider connection string="Data Source=XXXXXXXX.database.windows.net,1433;Initial Catalog=YourDB;User ID=YourUser;Password=XXXXXX"
"Custom" - In the drop selection box
Make sure (as stated in first answer) to replace " with "
Just recording my own experiences in addition to answers already recorded here
This was my final connection string (on mutliple lines for clarity)
metadata=res://*/Models.mBT.csdl|res://*/Models.mBT.ssdl|res://*/Models.mBT.msl;
provider=System.Data.SqlClient;
provider connection string="
Data Source=tcp:myazureserver.database.windows.net,1433;
Initial Catalog=databasename;
User ID=z#myazureserver;
Password=xyz"
To convert from a "normal" connection string to one that is accepted by EF:
The connection string type in the application settings has to be "other" not "SQL Azure"
The connection string value automatically replaces anything published in web.config
The metadata name Models.mBT.csdl (and the other two) comes from this:
Firstly, mBT is the name of my .edmx file
With regards to the Model. bit, see the answer from #leqid here: MetadataException: Unable to load the specified metadata resource
You can inspect your obj directory and see these three metadata files are in a subfolder called Models, so you need to prepend with Models.

Unable to connect using sql authentication through an asp.net web app

I cannot get my web app to connect to the database when running the app. I can connect in the SQL Server object explorer and I took the connection string from the connections properties
Here is my connection string :
<add name="Quotes.DAL.QuotesConnection"
connectionString="Data Source=(localdb)\v11.0;Initial Catalog=TestDB;Integrated Security=False;User ID=sa;Password=***;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"
providerName="System.Data.SqlClient" />
I can connect as SA and I can create the database that it points to in Management Studio. When my app tries to connect via Entity Framework I get the following error :
System.Data.SqlClient.SqlException (0x80131904): Login failed. The login is from an untrusted domain and cannot be used with Windows authentication. at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject,
I'm running Windows 7 as a home dev machine so there is no Active Directory.
Can anybody explain why this might happen?
I have found that this is probably because I have Entity Framework in another assembly. I created a new web application and its connection string works. When it try the same connection string in my DAL it fails with this same error!
Thanks
It may be because of setting Integrated Security=False, I have never set it to false. I normally use just the bare minimum Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword; when setting up my connection strings with sql authentication, only adding things as I need them.
The other issue I see is using SA to connect to the database. This breaks almost every best practice in the book and I would recommend creating an app specific password for when you roll out the program. The reason being is the GOD ACCESS account for the server will have its password in plain text in the app.config file. Just something to keep in mind.
EDIT: After some comment discussion the connection string was in the wrong config file.

problem in connectionstring in asp.net

private string conString = "Data Source=173.56.33.6;Database=musicapp;User ID=guest;Password=guest";
I was working on local database at that time my application was successfully interacting with mysql database.when put the database on server, my application still taking the old connection string and data is stored in local database and not on server.
what is wrong?
I'd remove hard coded connection strings all together. There is a dedicated section of your config file for this very purpose:
<connectionStrings>
<add name="MusicApp" connectionString="Data Source=173.56.33.6;Database=musicapp;User ID=guest;Password=guest;" />
</connectionStrings>
Which you can then read out:
string connection = ConfigurationManager.ConnectionStrings["MusicApp"].ConnectionString;
I think your problem is that you have the connection string hard-coded in your code (as a private string that you show above). A much better way is to store it in the config file, use Settings in VS and select ConnectionString as type.
Make sure whether you updated your connection string when you transfered your DB to server. In any case it is best to store connection string in web.config, so that you can modify it when ever your db is changed or transferred to another location. This change in connection string in your web.config wouldn't require you to rebuild your application. Although if your connection string is hard-coded in code, then you would require to rebuild your application when ever you change the connection string.
if Data Source=173.56.33.6; is the location of your server database try this instead Data Source=\173.56.33.6;

instance failure error in asp.net web site

I have a website included login module.when i hosted the website in iis there is an error
Server Error in "/" Application.
system.invalid operation Exception: Instance Failure
My ConnectionString is like this
<add name="MyConnectionstring" Connectionstring="Data Source=IP Address,1433;Network Library=DBMSSOCN;initial catalog=Databasename;integrated security=True" Provider Name="System.data.sqlclient"/>
How can i solve this problem?Any one knows Please help me
Simply change DataSource=My-PC\\\SqlServer2008 to DataSource=My-PC\SqlServer2008 in your Web config because the previous one is valid one you are writing in Code Beind file but not in Web config file as it is an XML file.
The first thing I noticed is that you need to replace IP Address in your connection string with the actual IP address and Databasename with the actual database name. You also don't need ",1433" after the IP Address since 1433 is the standard port.
Second, is the SQL you are connecting to the default instance on the machine? If it is a named instance, you need to make sure to include the name in the data source setting.
Third, does the ID the ASP.NET process is running under have authority to connect to the SQL Server instance?

Resources