IIS Express references machine.config versus project web.config - asp.net

I am writing a WsCF service to retrieve data for multiple clients. I have a service layer that references business manager objects. In essence on the service call, I want to retrieve the provider type (a custom enum in my code) and the connection string from the web.config.
For some reason, the code is unable to find the settings in my project web.config. I am gathering the IIS Express AND the VS development web server are referencing the machine.config. How do I override this. It is extremely frustrating. As you can see from the snippet the setting AND the connection string name exist, but the code never picks it up.
My code:
Private Sub GetDBInformation()
Dim config As System.Configuration.Configuration
config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Nothing)
If (config.AppSettings.Settings.Count > 0) Then
Dim Setting As System.Configuration.KeyValueConfigurationElement
Setting = config.AppSettings.Settings("DB TYPE")
If Not (Setting.Value = Nothing) Then
Select Case Setting.Value
Case "SQL SERVER"
provider = ProviderType.SqlServer
Case Else
provider = ProviderType.OleDb
End Select
End If
End If
If (config.ConnectionStrings.ConnectionStrings.Count > 0) Then
connection = config.ConnectionStrings.ConnectionStrings("UMADB").ConnectionString
End If
End Sub
The web.config:
<connectionStrings>
<add name="UMADB"
connectionString="Data Source=***********;Initial Catalog=UMA;UserID=********;Password=***********"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="DB TYPE" value="SQL SERVER" />
</appSettings>

That's a really roundabout way of accessing the configuration settings. I don't know why or how you got to the machine.config, but there's an easier way.
Don't forget to import the System.Configuration namespace.
Dim Setting As String = ConfigurationSettings.AppSettings.Get("DB_TYPE")
If Not String.IsNullOrEmpty(DatabaseSetting) Then
Select Case Setting
Case "SQL SERVER"
provider = ProviderType.SqlServer
Case Else
provider = ProviderType.OleDb
End Select
End If
I don't know how or why you got to the machine.config, but that shouldn't happen. With your current approach, try specifying the application root when getting the configuration file:
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/")

Related

'Connection string "SQLServerConnectionString" was not found.' - Using Azure DB

Basically, I'm busy with a university project and this is the error I keep running into. I've tried multiple solutions from Microsoft's sites, but got nothing.
I added the connection string to my web.config, however, it still doesn't come through for me.
The connection link I took directly off of Azure's connection strings, on the DB I created.
<connectionStrings>
<add
name="SQLServerConnectionString"
connectionString= "Server=tcp:[dblink],1433;Initial Catalog=SACLADB;Persist Security Info=False;User ID=[id];Password=[pass];MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
providerName="System.Data.SqlClient" />
</connectionStrings>
The code used to attempt and connect the database which should use the web.config connection string.
#{
ViewBag.Title = "Papers";
var db = Database.Open("SQLServerConnectionString");
var selectQueryString = "Select * FROM Papers ORDER BY Author";
}
Found the error of my ways;
I was editing the wrong Web.Config. I wasn't editing the one in the root folder where it reads the connection strings, however, all issues are now fixed.

Connection string in web.config not working

I have a very basic ASP.NET web application that is connecting to a SQL Server database (I am using SQL Server 2008 Express). The problem I am having it is very odd: if I set the connection string for the SqlConnection object directly in code, the application works fine, but if I move my connection string to the web.config file, the application fails.
I show you both the variable and the connection section in the web.config to see if you detect any error:
In the variable:
// works fine
string cs = "data source=.; database=myDataBase; integrated security=SSPI";
SqlConnection conn = new SqlConnection(cs);
Now in the web.config:
<configuration>
<connectionStrings>
<add name="myCS"
connectionString="data source=.; database=myDataBase; integrated security=SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>
...
// Now, if I do this in C#, it does not work:
string cs = ConfigurationManager.ConnectionStrings["myCS"].ConnectionString;
SqlConnection conn = new SqlConnection(cs);
It tells me that there is already a database with that name. Now, I have read things everywhere. Some guy said that instead of using "database" in the connectionString, I could use "initial catalog" and all would be fine. Well, it wasn't fine... I have the same problem... Does anyone know what I am doing wrong? Why is working in one place and not in another? If the connection string was wrong, it should fail in both places, and it is only crashing in the webConfig file... Thanks very much...
If you are running this from Visual Studio, have you tried stopping the Dev Server (running in your system tray) and trying? the Web.config file is normally cached and could cause issues.

Only ASPX (HTML) file run through virtual directory but when connect to database it doesn't find web.config connection

Only ASPX (HTML) file run through virtual directory but when connect to database it doesn't find web.config connection.My code..
<appSettings>
<add key="ugs" value="data source=192.168.0.235\SQLEXPRESS,80; Persist Security Info=True; initial catalog=ugs_academy; integrated security=true;" />
That is because you need to put the information in the connectionStrings element.
Read more on MSDN
you can refer this link, how to get the value from AppSetttings and also you cand read an excellent article for appsettings AppSettings
string ConnStr= System.Configuration.ConfigurationManager.AppSettings["ugs"].ToString();
then later you pass this Connection string to your SqlConnection class open.
using(SqlConnection connObj = new SqlConnection(ConnStr))
{
//do some thing with ConnObj.
}

Keyword not supported: 'server'

I've been trying to edit my connection string for uploading my website to a server.
I am not really experienced with this. I got this exception: the Keyword not supported: 'server'.
Here is my connection string:
<add name="AlBayanEntities" connectionString="Server=xx.xx.xxx.xxx,xxxx;Database=AlBayan;Uid=bayan;Password=xxxxx;" providerName="System.Data.EntityClient" />
I've tried embed this string into my old connection string which works very well locally, but it didn't fit : S
For Entity Framework (database-first or model-first; when you have a physical EDMX model file) you need to use a special type of connection string which is quite different from the straight ADO.NET connection strings everyone else has mentioned so far...
The connection string must look something like:
<add name="testEntities"
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(local);initial catalog=test;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
Inside this connection string, you'll find the provider connection string= attribute which is basically your ADO.NET connection string:
provider connection string="data source=(local);initial catalog=test;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
So here, you need to change your server name and possibly other settings.
data source=.... stands for your server (you can also use server=.....)
initial catalog=..... stands for your database (you can also use database=....)
In MVC5 using EntityFramework 6.xx and Code First Approach
I had the same problem and I solved this by modifying my providerName
from
providerName="System.Data.EntityClient"
to
providerName="System.Data.SqlClient"
This exception is thrown on azure websites when you store the connection string in the App Service itself (on the 'Application Settings' blade).
If the connection string is an Entity Framework connection string the quotes will be encoded as " by default in your web.config file.
You need to change these back to actual quotes so the connection string can be parsed properly.
I always either run a connection wizard to build my string or I use connectionstrings.com.
Assuming SQL Server:
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Comparing to yours it is very different.
Server=xx.xx.xxx.xxx,xxxx;Database=AlBayan;Uid=bayan;Password=xxxxx;
Same happened to me when using Rider IDE for a .net core 2.2 project.
As Rider automatically sets up Sqlite in Startup.cs in the "ConfigureServices" method.
By changing
services.AddDbContext<ApplicationDbContext>(options =>
options.**UseSqlite**(
Configuration.GetConnectionString("DefaultConnection")));
into
services.AddDbContext<ApplicationDbContext>(options =>
options.**UseSqlServer**(
Configuration.GetConnectionString("DefaultConnection")));
issue was resolved.
Of course, first you have to install nuget packages for EF SQLServer and add the connection string to appsettings.json.
Try this
<add name="AlBayanEntities" connectionString="Data Source=xx.xx.xxx.xxx,xxxx;Initial Catalog=AlBayan;User Id=bayan;Password=1abcd;" providerName="System.Data.EntityClient" />
EntityConnectionStringBuilder bb = new EntityConnectionStringBuilder();
bb.Metadata = "res://*/dao.bdmi.csdl|res://*/dao.bdmi.ssdl|res://*/dao.bdmi.msl";
//same as below client tobe used
bb.Provider = "MySql.Data.MySqlClient";
MySql.Data.MySqlClient.MySqlConnectionStringBuilder mbb = new MySql.Data.MySqlClient.MySqlConnectionStringBuilder();
mbb.Server = "";
mbb.Database = "";
mbb.UserID = "";
mbb.Password = "";
mbb.PersistSecurityInfo = true;
//use providerconnectionstring insted of connectionstring
bb.ProviderConnectionString = mbb.ToString();
return bb.ToString();
Through this way, you can change your ConnectionString as you want.
In my case, I found that my project had the EFSQLLite nuget package installed, which seems doesn't recognise the Server= keyword.
I uninstalled that nuget and installed the full EFSQLSERVER one, and it worked fine

ASP.NET EFCodeFirst not using correct connection string

I am trying to publish a website using ASP.NET MVC3 EF and CODEFIRST with a SQL Server 2008 backend. On my local machine I was using a sql express db for development, but now that I am pushing live, I want to use my hosted production database. The problem is that when I try to run the application, it is still using my local db connection string. I have completely removed the old connection string from my web.config file and am using the <clear /> tag before creating the new connection string. I have also cleaned the solution and rebuilt, but somehow it is still connecting to the old db. What am I missing?
This is the new connection string:
<connectionStrings>
<clear />
<add name="CellularAutomataDBContext"
connectionString=" Server=XXX;
Database=CellularAutomata; User ID=XXX; Password=XXX; Trusted_Connection=False"
providerName="System.Data.SqlClient" />
</connectionStrings>
UPDATE
When I debug and look at the DBCONTEXT object, this is what is showing up for its connection:
Data Source=.\\SQLEXPRESS;Initial Catalog=CellularAutomata.Models.D1K2N3CARuleDBContext;Integrated Security=True;MultipleActiveResultSets=True"
I am unsure why this is happening because I cannot find it being set to this anywhere. Also, under configuration it says LazyLoadingEnabled = true, I assume this may be part of the problem, maybe it is not loading the new connection string. Where do I change these parameters?
UPDATE 2
EFCodeFirst is using a default connection string, I can't figure out how to get it to accept the connection string that I specify in the web.config file.
So, When using EF CodeFirst, there is a default connection string that it uses. If you want to be able to use a custom connection string, there are a few parameters guidelines that you must follow.
name ="this must match the name of your database context class"
connectionString="Server=yourserverurl; Database=yourdatabasename; User ID=youruserid;
Password=yourpassword; Initial Catalog=the name of the database to use;
Trusted_Connection=False"
providerName="System.Data.SqlClient"
So far this is working for me.
The connectionString you show is not an EF connection string. The EF won't use it. So you're changing the wrong thing.
An EF connectionString will include providerName="System.Data.EntityClient"
It will look for the same name as your context and depending on what else you
are using other names as well. I usually use the following for controlling
specific features with either the same or specific connection strings
(I keep app services in a different db for example so EFCF can drop tables as needed):
<connectionStrings>
<add name="MyAppContext" .../>
<add name="ApplicationServices" .../>
<add name="DefaultConnection" .../>
</connectionStrings>

Resources