Can't read database name web project - c#

Trying to read the database name but it's not working in the site. Using an asp.net web project with a solution file. I put this in the web.config. This will change depending on development database or production database PRODDB via the web configuration transform files and scripts.
<appSettings>
<add key="databaseName" value="DEVELDB"/>
<add key="operatingEnvironment" value="dev"/>
</appSettings>
Within the Global.asax.cs file:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
var operatingEnvironment = WebConfigurationManager.AppSettings["operatingEnvironment"].ToString();
if (operatingEnvironment == "dev")
{
Application["DBE"] = WebConfigurationManager.AppSettings["databaseName"].ToString();
}
}
Within the login.cs class file:
internal static DatabaseConnection GetDatabaseConnection()
{
return
new DatabaseConnection(
new ConnectionProperties
{
User = Shared.User,
Application = Shared.Application,
DatabaseName = (string)HttpContext.Current.Application["DBE"]
});
}
and within the Web.Development.config file there is:
<appSettings>
<add key="databaseName" value="DEVELDB" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
<add key="operatingEnvironment" value="dev" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
</appSettings>
However, whenever I debug after login, it goes to the code below which is good (the same as coded above) but says Database name was not specified? I have it specified as DEVELDB and using "DBE" to reference it. However, it's not like it debugs to another area and to there, just straight to there and kills it?
...
{
User = Shared.User,
Application = Shared.Application,
DatabaseName = (string)HttpContext.Current.Application["DBE"]
});

Connections to databases go inside the "connectionstrings" tags in you "webconfig" file. If you need SqlServer it is shown below
<configuration>
<connectionStrings>
<add name="TwoWayConn" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\TwoWayData.accdb"
providerName="System.Data.OleDb" />
<add name="TWOWAYDATASQL" connectionString="Data Source=TBIRD\SQLEXPRESS1;Initial Catalog=TWOWAYDATASQL.MDF;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
....
</configuration>
Am I misunderstanding what you are trying to do?

Related

ConnectionString not found have tried multiple ways

Connection string not found i have tried multiple ways but all goes in vein, i have a data access layer project in app.config i have mention connection string
</configuration>
<connectionStrings>
<add name="MySqlConnectionString" connectionString="server=myserver;User Id=myuser;password=mypassword;database=mydatabase"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>
C# Code
public void ConnectionString()
{
try
{
var connectionString = ConfigurationManager.ConnectionStrings["MySqlConnectionString"].ConnectionString; //does not work
var connectionString2 = ConfigurationManager.AppSettings["MySqlConnectionString"];//does not work
}
catch(Exception ex)
{
}
}
What am doing wrong i have try multiple solution it does not work for me
ConnectionString Not Found
Your connection string name is Default. And you should consider this detail when you want to read it. Try like this;
public void ConnectionString()
{
try
{
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
}
catch(Exception ex)
{
}
}
Or you can change connection string name as you wish;
</configuration>
<connectionStrings>
<add name="MySqlConnectionString" connectionString="server=myserver;User Id=myuser;password=mypassword;database=mydatabase"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>
From the picture I can see an "app.config" and a "web.config", so I presume there are different projects. Am I right? If it is, you have to add the connectionString on the execution project (if it is a web site, or a standalone, or whatever it is).
The code you were using is correct
var connectionString = ConfigurationManager.ConnectionStrings["MySqlConnectionString"].ConnectionString;
It has to work correctly.
Thanks Every one for helping my the main issue was i have added connectionstring attribute in the wrong place
Wrong place
<runtime>
<connectionStrings>
<add name="MySqlConnectionString" connectionString="server=myserver;User Id=myuser;password=mypassword;database=mydatabse"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</runtime>
</configuration>
Right place i have cut the connection string under the runtime attribute and paste it alone and the issue is solved
<connectionStrings>
<add name="MySqlConnectionString" connectionString="server=myserver;User Id=myuser;password=mypassword;database=mydatabse"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
Thanks everyone

How to set connectionstring at web.config file programmatically or dynamically?

I'm trying to create an ASP.NET website. There I'm using a database. To connect with the database I'm using the connectionstring which I've stored in the web.config file like
<connectionStrings>
<add name="DBConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=G:\CarRentalServices\App_Data\CarRentalServiceDB.mdf;Integrated Security=True"/>
</connectionStrings>
and at code behind
private string _connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
So you can see the database is stored at G:\path\to\db\CarRentalServiceDB.mdf.
But now if my friend want to take the project from me and try to run the project from his machine then he has to change the connectionString at web.config. Say the website is now at D:\path\to\db\foo\CarRentalServiceDB.mdf in my friend's machine, then the connectionString needs to change. Isn't it tedious?
Is there any way to change the connectionString dynamically with any batch file or code so that it will change with respect to the current directory it is residing now?
You shoud use the |DataDirectory| token: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx
<connectionStrings>
<add name="DBConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\App_Data\CarRentalServiceDB.mdf;Integrated Security=True"/>
You would add multiple connections strings in your web.config file and call the one you need like
Web.config File
<connectionStrings>
<add name="DBConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=G:\CarRentalServices\App_Data\CarRentalServiceDB.mdf;Integrated Security=True"/>
<add name="DBConnectionStringTwo"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\path\to\db\foo\CarRentalServiceDB.mdf;Integrated Security=True"/>
</connectionStrings>
Code for connection strings
//Connection String 1
private string _connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
//Connection String 2
private string _connectionString2 = ConfigurationManager.ConnectionStrings["DBConnectionStringTwo"].ConnectionString;

ConfigurationManager.ConnectionString reads app.config from different location

The app.config of my C# windows application has the following ConnectionString
<connectionStrings>
<add name="DS1" connectionString="Data Source=DataSource1;" providerName="" />
<add name="DS2" connectionString="Data Source=DataSource2;" providerName="" />
<add name="DS3" connectionString="Data Source=DataSource3;" providerName="" />
<add name="DS4" connectionString="Data Source=DataSource4;" providerName="" />
</connectionStrings>
After installing the setup, the same connection strings exist in the projectname.config of installation directory C:\ProgramFiles\ProjectName\ProjectName.config.
When i run the application, i have the following code to access the connection string
foreach (ConnectionStringSettings key in ConfigurationManager.ConnectionStrings)
{
Display ConfigurationManager.ConnectionStrings[key.Name].Name,
}
The Key names are not displaying as DS1, DS2, DS3 and DS4 .
Instead it is reading the ProjectName.config file present in
C:\Users\UserName\AppData\Local\VirtualStore\Program Files\ProjectName\ProjectName.exe.config
This was saved long back when project was installed but when uninstalled it doesn't get removed.
How can i make changes in C# to read the proper ProjectName.config file from installation dircectory and not from AppData folders.
Try this
string theConfigFileName ="FilePath";
ExeConfigurationFileMap userConfigFileMap = new ExeConfigurationFileMap() { ExeConfigFilename = theConfigFileName };
Configuration userConfig = ConfigurationManager.OpenMappedExeConfiguration(userConfigFileMap, ConfigurationUserLevel.None);
foreach (var item in userConfig.ConnectionStrings.ConnectionStrings)
{
}
On app startup you could check for the existence of the original config and delete it.
string originalConfig = string.Format("C:\Users\{0}\AppData\Local\VirtualStore\Program Files\ProjectName\ProjectName.exe.config", Environment.UserName);
if (System.IO.File.Exists(originalConfig))
{
System.IO.File.Delete(originalConfig);
}
If you wanted to do it during the uninstall, you could execute this code in a custom action:
System.IO.Directory.Delete("%APPDATA%\ProjectName");
See msdn for creating a custom action

How to change the content of my app.config after installation of the application

I am working on WPF application that soon has to be ready for installation but there is a functionallity that allows the user to make changes to the app.config file and I don't know how to do that from the code-behind of the application.Also I don't know how this is going to work after the installation of the app.
Simply said: I have a window that allows the user to enter a text that is going to be searched for in the web.config of another application.So in my app.config I have a different searches and I want after the installation the user to be able (after entering values in the window's textoxes) enter new values in the app.config of the application.
Can somebody tell if that is possible and eventually how I could achieve this?
How I did in my application. I have app.config as following
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="StoreConnectionString"
connectionString="Data Source=.\;MultipleActiveResultSets=True;Initial Catalog=Store;Integrated Security=False;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="ExportPath" value="D:\" />
<add key="CompanyName" value="My Company" />
<add key="mail" value="email#mail.com" />
<add key="phone" value="+992918254040" />
<add key="ExpDate" value="Pink" />
<add key="Print" value="No" />
<add key="EnforcePassw" value="Yes"/>
</appSettings>
</configuration>
So I can change and save app Settings from my application, here is code
private void btnSave(object sender, RoutedEventArgs e)
{
//returns path of folder where your application is
string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
//combines path of folder and file
string configFile = System.IO.Path.Combine(appPath, "MyApp.exe.config");
//Defines the configuration file mapping for an .exe application
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = configFile;
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
config.AppSettings.Settings["ExportPath"].Value = txtExport.Text;
config.AppSettings.Settings["CompanyName"].Value = txtComapny.Text;
config.AppSettings.Settings["mail"].Value = txtEmail.Text;
config.AppSettings.Settings["phone"].Value = txtPhone.Text;
config.AppSettings.Settings["Print"].Value = print;
config.AppSettings.Settings["EnforcePassw"].Value = password;
config.AppSettings.Settings["ExpDate"].Value = color;
config.Save();
}
Hope it will be help you!
If you want to add new strings use this code;
config.AppSettings.Settings.Add("Key", "Value");
this may be helpful
Configuring Application/User Settings in WPF the easy way.

How to declare a variable in the app.config file?

I am working on a Windows application.
I have a form with labels like
HOST:
UserName:
Password:
How I can declare the connection string in the app.config file so that it takes the initial catalog, userID and password as variables that I can use in further to check the user whether which database the user wants to get connected with the entered userID and password.
I am using SQL Server 2008 and Visual C# 2008 Express Edition.
As I'm reading your question, you want to have a generic connection string that you want to inject username/password variables into. To do that you would need to have a key with this format:
<add name="myDBKey" connectionString="Data Source=myDB;Initial Catalog={0};Persist Security Info=True;User ID={1};Password={2}" providerName="System.Data.SqlClient"/>
Then in your code, you would need to have these variables declared and assigned, and then use String.Format to complete it.
string dbCatalog = "myCatalog";
string dbUser = "myUser";
string dbPW = "myPW";
string myDBConnectionString = String.Format(
ConfigurationManager.ConnectionStrings["myDBKey"].ConnectionString,
dbCatalog, dbUser, dbPW);
This will inject your variables into the string.
There is a <connectionString> section to the app.config file.
<connectionStrings>
<add name="MyDatabase" connectionString="Data Source=sqlserver,1433;Network Library=DBMSSOCN;Initial Catalog=MyDatabase;User ID=xxx;Password=xxxx;" />
</connectionStrings>
For your Host, User ID and Password, you can define these in the <appSettings> section.
Try this
<connectionStrings>
<add name="ConString" connectionString="Server=Servernae;Database=DBName;User Id=username;password=yourpassword"/>
</connectionStrings>
For more information try Connection Strings
Start by declaring the variables by going to your project's property tab, then going to the Settings tab (on the left), declaring your variables by mentioning the name, default value, and scope (which will be Application).
In your code, to fetch the values:
using System.Configuration;
//....
ConfigurationSettings.AppSettings["ConnectionString"].ToString();
// or
ConfigurationSettings.AppSettings.ConnectionString;
Please note that you can't change the value in code for an Application setting.
EDIT:
Alternately, there is also the connectionStrings node which can be set (but it must be done in the app.config file itself. See MSDN for documentation.
Example of XML:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="ConnStr1" connectionString="LocalSqlServer: data source=127.0.0.1 Integrated Security=SSPI;Initial Catalog=aspnetdb"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
In C#, you will get a System.Coonfiguration.ConnectionStrings, which is a collection of ConnectionStringSettings.
Example of usage in C# code: http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings.aspx
You can do some thing like this,
<appSettings>
<add key="SettingName" value="SettingValue" />
</appSettings>
or go to "Variables within app.config/web.config".
My library Expansive is designed with this as a primary use-case.
Moderate Example (using AppSettings as default source for token expansion)
In app.config:
<configuration>
<appSettings>
<add key="Domain" value="mycompany.com"/>
<add key="ServerName" value="db01.{Domain}"/>
</appSettings>
<connectionStrings>
<add name="Default" connectionString="server={ServerName};uid=uid;pwd=pwd;Initial Catalog=master;" provider="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Use the .Expand() extension method on the string to be expanded:
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
connectionString.Expand() // returns "server=db01.mycompany.com;uid=uid;pwd=pwd;Initial Catalog=master;"
or
Use the Dynamic ConfigurationManager wrapper "Config" as follows (Explicit call to Expand() not necessary):
var serverName = Config.AppSettings.ServerName;
// returns "db01.mycompany.com"
var connectionString = Config.ConnectionStrings.Default;
// returns "server=db01.mycompany.com;uid=uid;pwd=pwd;Initial Catalog=master;"
Advanced Example 1 (using AppSettings as default source for token expansion)
In app.config:
<configuration>
<appSettings>
<add key="Environment" value="dev"/>
<add key="Domain" value="mycompany.com"/>
<add key="UserId" value="uid"/>
<add key="Password" value="pwd"/>
<add key="ServerName" value="db01-{Environment}.{Domain}"/>
<add key="ReportPath" value="\\{ServerName}\SomeFileShare"/>
</appSettings>
<connectionStrings>
<add name="Default" connectionString="server={ServerName};uid={UserId};pwd={Password};Initial Catalog=master;" provider="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Use the .Expand() extension method on the string to be expanded:
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
connectionString.Expand() // returns "server=db01-dev.mycompany.com;uid=uid;pwd=pwd;Initial Catalog=master;"

Categories

Resources