Web.Config SQL Connection - sql-server

My Web.Debug.Config code:
<connectionStrings>
<add name="NextLevel"
providerName="System.Data.SqlClient"
connectionString="Data Source=DESKTOP-RTOUFCH\\SQLEXPRESS;Database=NextLevel;Integrated Security=True;" />
</connectionStrings>
My CSharp code:
using System.Configuration;
using System.Web.Configuration;
using System.Data.SqlClient;
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["NextLevel"].ConnectionString;
I keep getting a null reference error.
When I attempt to iterate through the connection strings, it finds one named "LocalSQLServer" which is not even in my web.Debug.config file.
What am I doing wrong?

That last comment by ThomasArdal:
I would also suggest you to publish web.config, web.debug.config, and web.release.config. If you have those files.
allowed me to figure out my problem.
I was updating web.debug.config when I should have been updating web.config.

<connectionStrings>
<add name="NextLevel"
providerName="System.Data.SqlClient"
connectionString="Data Source=.;Initial Catalog=NextLevel;Integrated Security=True;" />
</connectionStrings>
Check with this instead!

Related

How to add Azure SQL Server connection string to app.config in Windows Forms?

I'm trying to add an Azure SQL Server connection string into my app.config file, but there are red underlines all over the connection string when I try to copy and paste it from Azure. I'm using Windows Forms in Visual Studio.
Here is my connection string:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="AddSales"
Server="tcp:Sales99.database.windows.net,1433;Initial" Catalog="Sales;Persist" Security="" Info="False;User" ID=""{your_username};Password=""{your_password};MultipleActiveResultSets=""False;Encrypt=""True;TrustServerCertificate="False;Connection" Timeout="30"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Is there a way to fix this issue? Please advise.
Your config is just plain wrong - you need to have an attribute connectionString in your config that contains all the details about the connection - something like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="AddSales"
connectionString="Server=tcp:Sales99.database.windows.net,1433;Initial Catalog=Sales;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
I also had this issue when I try to copy & paste connection string from the Azure database. This is connection string that worked for me.
Server=tcp:[serverName].database.windows.net;Database=myDataBase; User ID=[LoginForDb]#[serverName];Password=myPassword;Trusted_Connection=False; Encrypt=True;
This also works.
<add name="ConnectionStringName"
providerName="System.Data.SqlClient"
connectionString="Data Source=tcp:ServerName.database.windows.net,1433;Initial Catalog=DatabaseName;Integrated Security=False;User Id=username#servername;Password=password;Encrypt=True;TrustServerCertificate=False;MultipleActiveResultSets=True" />
If you need additional info, please visit these sites:
https://www.connectionstrings.com/sql-azure/
https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx

Asp.Net Identity - A network-related or instance-specific error occurred while establishing a connection to SQL Server

I have a code first EF application. The database has been created. Now I am trying to implement Login/Registration module using the Asp.Net Identity. I click the Register link but it gives me the above error.
Web.config:
...
<connectionStrings>
<add name="ConnStr_Dev"
connectionString="Data Source = DELL-MyName; Initial Catalog = MyDB_Dev; user id = sa; password=myPassword;"
providerName="System.Data.SqlClient" />
<!--<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-MyApp-20170328111628.mdf;Initial Catalog=aspnet-MyApp-20170328111628;Integrated Security=True"
providerName="System.Data.SqlClient" />-->
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
...
<entityFramework>
<defaultConnectionFactory
type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source = DELL-MyName; Initial Catalog = MyDB_Dev; user id = sa; password=myPassword;" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
Is there something that needs to be set separately?
1- Use below connection string. I am using here SQL express instance. Replace it with the name you use to connect through sql management studio.
<connectionStrings>
<add name="ConnStr_Dev" connectionString="Server=.\SQLEXPRESS;Database=MyDB_Dev;User ID=sa;Password=myPassword;Trusted_Connection=False;Persist Security Info=False;Pooling=True;Min Pool Size=20;Max Pool Size=100;Connection Timeout=300;multipleactiveresultsets=True;App=EntityFramework" providerName="System.Data.SqlClient"/>
</connectionStrings>
2- Remove <entityFramework> tag from config file. You dont need it.
3- Make sure you are passing 'ConnStr_Dev' as string to DbContext constructor.
Locate the file IdentityModel.cs in the Models folder. In the ApplicationDbContext constructor the name of the connection string is passed in to the base class constructor - this needs to match the name of the your connection string in your web.config
So in your case
<connectionStrings>
<add name="ConnStr_Dev"
connectionString="Data Source = DELL-MyName; Initial Catalog = MyDB_Dev; user id = sa; password=myPassword;"
providerName="System.Data.SqlClient" />
</connectionStrings>
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("ConnStr_Dev", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}

Entity Framework Provider Configuration

I'm using EF 6.1 Code First. I'm programmatically configuring the connection string at runtime like:
myContext.Database.Connection.ConnectionString = "Data Source=(localdb)\v11.0;Initial Catalog=MyDb;Integrated Security=True;"
This works fine, but only if I keep some boiler plate connection information in my app/web.config:
<connectionStrings>
<add name="MyDb" connectionString="Data Source=NOTUSED;Initial Catalog=NOTUSED;" providerName="System.Data.SqlClient" />
</connectionStrings>
I suspect this is because I'm not providing the provider information. I am specifying the provider and defaultConnectionFactory sections (SQL Server / LocalDbConnectionFactory), but it doesn't seem to care:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
If I remove the connection strings section, it attempts to attach to a mdf file that doesn't exist:
System.Data.SqlClient.SqlException: Cannot attach the file 'C:\My
Project\App_Data\MyDb.mdf' as database MyDb.
Normally, the localdb connection string results in a path to c:\users\my_user\MyDb.mdf. So it seems like it's not using the LocalDb factory unless I've got the connection string section in my .config file.
How can I specify - on a per context basis - the providerName information that EF is getting from that connection string node? Or am I barking up the wrong tree here?
This may have something to do with the way you are constructing your connection. If you are using the default constructor on the DataContext, then it will attempt to find your connection string from the config file:
MyDbContext myContext = new MyDbContext() <- this uses the default constructor
myContext.Database.Connection.ConnectionString = "_conn_str_"
If you pass the connection string in the constructor, then you should not need the config file entry:
using (MyDbContext myContext = new MyDbContext("_conn_str_")) {
// the above line should not need an entry in the config file
}
Hope this helps.

How to add password connection string

How to add password in below mentioned connection string
<connectionStrings>
<add name="Gate_App.My.MySettings.GateDbConnectionString1" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\GateDb.accdb;Persist Security Info=True "
providerName="System.Data.OleDb" />
</connectionStrings>
Use this
<connectionStrings>
<add name="Gate_App.My.MySettings.GateDbConnectionString1" connectionString=" Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\GateDb.accdb; User ID=*******; Password='*******';Persist Security Info=True "
providerName="System.Data.OleDb" />
</connectionStrings>
<connectionStrings>
<add name="Gate_App.My.MySettings.GateDbConnectionString1" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=|DataDirectory|\GateDb.accdb;Persist Security Info=True;User ID=myUsername;Password=myPassword;"
providerName="System.Data.OleDb" />
</connectionStrings>
Access connection strings
Try this,
<add name="Gate_App.My.MySettings.GateDbConnectionString1" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\GateDb.accdb;User Id=id;Password=pass;" providerName="System.Data.OleDb" /

Change the connection strings in MVC3 to publish in IIS

I need to change the connection strings in my mvc proyect because is local and now I need publish in a server but I dont have idea how write the connection strings and they are the next
<add name="cnn" connectionString="Data Source=SISTEMAS-PC\SQLEXPRESS;Initial Catalog=FoodGroups;User ID=FoodGroup; Password=Food" providerName="System.Data.SqlClient" />
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(SISTEMAS-PC\SQLEXPRES)\v11.0;Initial Catalog=aspnet-MvcApplication1-20130730182253;Integrated Security=SSPI;AttachDBFilename=C:\Users\Sistemas\Desktop\proyectos TI\foodGroup2\foodGroup\App_Data" />
<add name="FoodGroupsEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=SISTEMAS-PC\SQLEXPRESS;initial catalog=FoodGroups;user id=FoodGroup;password=Food;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
You have a web.config which should have a section for all your connection string.
What you need to do, is to have a web.release.config that will change the connection string when you build in release mode.
For example, web.config when you are debugging in your dev environment:
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<configSections>
<connectionStrings>
<add name="YourConnectionString"
connectionString="Data Source=YourServer; initial catalog=YourDatabase; Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configSections>
And inside the web.release.config
<?xml version="1.0"?>
<connectionStrings>
<add name="YourConnectionString"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
</configuration>
When you are building, you will see that the string "YourConnectionString" will be replaced. This way, you can deploy/publish your application depending of the build mode (debug or release) without having to modify your code and just relying on web.config.

Resources