Connect to a MSSQL DB using Web.config - c#

I have created a ASP.NET C# MVC project. I am trying to connect it to a MSSQL DB. In the Web.config file i added the following;
<connectionStrings>
<add name="sdbconnection" providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename="C:\Users\o\documents\visual studio 2012\Projects\ppl\ppl\App_Data\ppldb.mdf";Integrated Security=True" />
</connectionStrings>
But, the above code is incorrect ; I want it to be as follows;
<connectionStrings>
<add name="sdbconnection" providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|ppldb.mdf;Integrated Security=True" />
</connectionStrings>
But What is DataDirectory ? Where do i specify it ?
What is name="sdbconnection" ? Can i give any name that i want ?

First question
Quoting MSDN:
The |DataDirectory| portion of the connection string specifies that
the MDF file is located inthe App_Data directory
Moreover you can change it using following function:
AppDomain.CurrentDomain.SetData("DataDirectory", "D:\database");
Second question
name="sdbconnection" allows you to use specified conection string. So in your code you can write:
string connectionString = ConfigurationManager.ConnectionStrings["sdbconnection"].ConnectionString;
to acces this connection string

Name is use to identify and use code your applications
Please refer this article http://www.connectionstrings.com/Articles/Show/store-connection-string-in-web-config
Data Directory is usually App_Data folder and in web.config file name is use to use connection string in the application
Ex:String conn=ConfigurationManager.ConnectionStrings["Your name at web.config file"].ConnectionString;
or
String conn=ConfigurationManager.ConnectionStrings["Your name at web.config file"].toString();

Related

I have two web.config files. Which one should I use?

I recently built an application using visual studio express. This application was built using a local DB provided by VS express. I now have a subscription (free trial) to Microsoft Azure. What changes do I need to make to my project in order to point my project to the newly created Azure DB?
I also noticed I have 2 web.config files. one in the root directory and one in the views folder.
I believe I have to make an update to my connection string, but in a specific config file or both?
Here is my root directory web.config connection string:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source= LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcMovie-20160922101748.mdf;Initial Catalog=aspnet-MvcMovie-20160922101748;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="MovieDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
and my (views) web.config connection string:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcMovie-20130603030321.mdf;Initial Catalog=aspnet-MvcMovie-20130603030321;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="MovieDBContext" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"/>
Any help would be highly appreciated.
I believe only one web.config with connection strings should be enough. Keep the one in the root.
Download Azure DB connection strings from the Azure portal and replace connectionString values in the web.config file with the Azure DB connection string(s).
You might also need to whitelist your machine's IP address in the Azure Portal to allow connections to Azure DB.
You only need to change the web.config on the root folder as thats the one used by the application.
And you are right, you need to point the connection string to your Azure database.
You definitely only need to update the one web.config in the root of the application with the connection string. The other web.config in the views folder is needed for your views to use html helpers and to make routing work as you expect in an mvc application so do not remove it.

Why my connection string is null

i am accessing store proceudre from sql database but it throws at connection string point:
"Object reference not set"
Code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=HOME-PC;Initial Catalog=LMS;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
string conStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
i am using windows forms in c#.net and i am newbie.
From one of your comments, it seems perhaps your connection string is defined in the app.config file of a class library. If that's the case, you'll need to copy the connection string entry in the config file to the configuration file of the actual application - in this case, the Windows Forms application that is calling the business layer library.
I found two possible solutions:
A. Removing the providerName="System.Data.SqlClient" part from the connection string definition on the App.config file
or
B. Adding a "using System.Data.SqlClient;" line on the using section of the client code where you are attempting to get and use connectionString, like this:
using System.Data.SqlClient;
//(...other code...)
string conStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
My guess is that the use of the providerName option on the connectionstring forces a call to the specified provider on execution.

Connection string in C# for a local db in a desktop application

I'm trying to use a local db for my application, and want it to reside in a folder inside my application. Unlees I'm missing something, this shouldn't be a problem with user rights, since it is in the application folder.
The connection string is this:
<connectionStrings>
<add name="Calendario2DB"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=\AppData\Database1.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I'm Using a code first aproach, so the database should be generated (filled) at run time, but I have a problem with
AttachDbFilename=\AppData\Database1.mdf
This should be pointing to a folder in my app (called appdata) but is not working with an error:
A file activation error occurred. The physical file name '\AppData\Database1.mdf' may be incorrect. Diagnose and correct additional errors, and retry the operation.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
So how do I have to write the path name to the phisical file?
You should use the built in |DataDirectory| feature.
<connectionStrings>
<add name="Calendario2DB"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Then the database would be located in:
\Program Files\Application Location\App_Data\Database1.mdf
According to the documentation you cannot use relative paths without using |DataDirectory|:
The path may be absolute or relative by using the DataDirectory substitution string. If DataDirectory is used, the database file must exist within a subdirectory of the directory pointed to by the substitution string.

relative path for ms-access db in app.config while creating .exe file

i have project in c# and access 2010 i configure my db link in app.config file as seen below <connectionStrings>
<add connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\projecty bashi nawxoyy\Bashi Nawxoyy\Bashi Nawxoyy\db_file.accdb" name="connectionString"/>
</connectionStrings> an then in all my forms i use string conString = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ToString();
db_con = new OleDbConnection(conString); it works good ... but know i want to make .exe file for my project and i want to make db link work in any machine that i install the exe file?? can any one help me an explain it for me but in detail please?
You can use relative path: db_file.accdb if database is placed in the same diractory as the exe file.
<connectionStrings>
<add connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=db_file.accdb" name="connectionString"/>
</connectionStrings>
System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ToString();
db_con = new OleDbConnection(conString);

App.config seems to be ignored

I've this Class Library, as a result of a refactor action.
I added an App.config file and added something like this:
<configuration>
<connectionStrings>
<add name="MyDatabase" connectionString="Data Source=server;Initial Catalog=database;User ID=userid;Password=password" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
But when I run the application, debugging learns me this is totally ignored. The immediate window tells me:
ConfigurationManager.ConnectionStrings[0]
{data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true}
base {System.Configuration.ConfigurationElement}: {data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true}
ConnectionString: "data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
Key: "LocalSqlServer"
Name: "LocalSqlServer"
Properties: {System.Configuration.ConfigurationPropertyCollection}
ProviderName: "System.Data.SqlClient"
I've checked generated config file in the bin directory and its contents are identical to the App.config.
I try to read the App.config using:
ConfigurationManager.ConnectionStrings[Constants.Connections.DevConnection].ConnectionString
Nothing out of the ordinary I'd say, but what is going wrong?
A class library doesn't get its own config; for an app named Foo.exe you need your configuration to be in Foo.exe.config. The exception here is web apps, where web.config is the naming convention.
This connectionString should be in the corresponding app.config of the exe that you are running.
Is the file being copied to output? Secondly the connection string should be accessible from the AssemblyName.Settings.Properties class which is generated from your code.

Categories