I'm working with a local dataBase in a Windows Form Application and I'm trying to implement the source for the dataBase as DataDirectory, so in case I'm moving the db from one computer to another, it will work just fine. I wrote the following code, but I get this error, that the value cannot be null, at the line where it gets the Fullpath. Thanks !
var dataDirectory = ConfigurationManager.AppSettings["DataDirectory"];
var absoluteDataDirectory = Path.GetFullPath(dataDirectory);
AppDomain.CurrentDomain.SetData("DataDirectory", absoluteDataDirectory);
var connString = (#"Data Source= |DataDirectory|\Angajati.sdf");
You should have this section in your app.config:
<appSettings>
<add key="DataDirectory" value="DataDirectoryPath"/>
</appSettings>
By the way for accessing DataDirectory you have to use this code:
AppDomain.CurrentDomain.GetData("DataDirectory")
more info.
Related
I have my connection string set up in the app config but I can not get it to find that connectionstring or even see that the connection name currency is in the collection.
I tried to add a version.
I have tried to adding the provider name to the string.
I have moved it in and out and in again of the path where the database and solution are located.
I have carefully made sure that I was pointed to the right location on my computer.
<connectionStrings>
<!-- CHANGE THIS to match where your solution and sqlite database are -->
<add name="currency" connectionString="Data Source=F:\CurrencyExercise\currency.db" />
</connectionStrings>
And then the code that calls the above.
public BaseDataAccess(string connectionName = "currency")
{
_connectionName = connectionName;
Connection = new SQLiteConnection(ConfigurationManager.ConnectionStrings[_connectionName].ConnectionString);
Connection.Open();
}
I would expect the code to actually pull back a SQLiteConnection object rather than erroring out.
So I'm parsing a connection string for an Azure Storage Account and when I get to the page of the app that uses the connection string, the compiler catches an exception stating, "Settings must be of the form "name=value".
Does this mean that I should correct something in the app.config file where I set the appSettings? If so can you immediately spot something wrong with my format that would cause this exception?
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=mykey" />
<appSettings>
</configuration>
Here's the code for creating an instance of CloudStorage object:
CloudStorageAccount storageaccount = CloudStorageAccount.Parse ("StorageConnectionString");
CloudTableClient tableClient = storageaccount.CreateCloudTableClient ();
CloudTable austinBowlingAthletes = tableClient.GetTableReference ("austinBowlingAthletesTable");
Your "StorageConnectionString" should be in the format of:
DefaultEndpointsProtocol=[http|https];AccountName=<YourAccountName>;AccountKey=<YourAccountKey>' as described here
Also, use CloudConfigurationManagerto obtain your connection string:
string connectionString = CloudConfigurationManager.GetSetting("StorageConnectionString");
This gives the added benefit of either using app.config/web.config when your app is running locally or accessing your app setting in azure when running in the cloud. See this link
Then you should beable to parse the connection string and have the benefit of not having to modify app.config/web.config settings between development & production environments.
Add a reference to System.Configuration.dll and add using System.Configuration; in the file.
Then change your first line to this:
CloudStorageAccount storageaccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);
You need to get the value, not just pass the key to Parse.
The reason you're running into this error is because you're asking CloudStorageAccount.Parse method to literally parse "StorageConnectionString" string instead of the value of this setting stored in app.config file. What you need to do instead is read the value of this setting from the config file. For example, in a console application I would do something like this:
var appSettingsReader = new AppSettingsReader();
var connectionString = (string) appSettingsReader.GetValue("StorageConnectionString", typeof(string));
CloudStorageAccount storageaccount = CloudStorageAccount.Parse(connectionString);
I had to add a reference for System.Configuration assembly to do so.
I've been trying to set a connectionstring to the users programdata folder and followed the first step in the answer of this post:
%APPDATA% in connection string is not substituted for the actual folder?
Unfortunately I can't get it to work:
In the onstartup method of my WPF application I run the following:
AppDomain.CurrentDomain.SetData("DataDirectory", Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
var test = AppDomain.CurrentDomain.GetData("DataDirectory");
var connection = System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
Value in App.config
<add name="Conn" connectionString="data source=|DataDirectory|\mydb" providerName="System.Data.SQLite" />
result of test = "c:\programdata" => this is good
result of connectionstring ="|DataDirectory|\mydb" => this is not good
I'm expecting: "c:\programdata\mydb"
I've been looking all around... what am I doing wrong?
thanks in advance,
You are misunderstanding how it works.
Setting the DataDirectory is correct, but the actual connectionstring is not changed on file.
When you open the connection the |DataDirectory| part of the string will be replaced with your path
You just need to try and see by yourself
If you're following the answer you linked to, you seem to be missing the following from Step 2. in the link:
return connection.Replace("%APPDATA%",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
When using WPF and entity-framework I have an APP.CONFIG that looks like the following:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="DatabaseEntities" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=%APPDATA%\Folder\Database.sdf"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
When using this code it always throws the following error:
System.Data.EntityException: The underlying provider failed on Open. ---> System.Data.SqlServerCe.SqlCeException: The path is not valid. Check the directory for the database. [ Path = %APPDATA%\Folder\Database.sdf ]
When I run the path "%APPDATA%\Folder\Database.sdf" from the command prompt it works fine, and if I remove "%APPDATA% and hardcode the path it works fine - so it looks simply like the %APPDATA% is just not being substituted for the actual folder...
Thanks,
As you already reallized, %APPDATA% or any other environtment variables are not replaced with their respective value in connection strings. Environment varialbes are something related to the operating system shell. They work in command prompt because the command prompt explicitly parses the values entered and substitutes environment variables. That's not something that .NET Framwork usually performs.
To achive this, you have to manually provide the value for %APPDATA% (using Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) or Environment.GetEnvironmentVariable("APPDATA")). There are two options:
Change your connection string and use |DataDirectory|:
<connectionStrings>
<add name="DatabaseEntities" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=|DataDirectory|\Database.sdf"" providerName="System.Data.EntityClient" />
</connectionStrings>
(Notice the use of |DataDirectory| in the path to the database file.)
Then provide the value for |DataDirectory| in your application's Main method:
AppDomain.CurrentDomain.SetData("DataDirectory",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
Refer to this MSDN page for more information.
Manually provide the connection string for your ObjectContext class. This way you can parse and change the connection string:
public static string GetConnectionString()
{
var conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DatabaseEntities"].ConnectionString;
return conStr.Replace("%APPDATA%",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
}
And later:
var db = new DatabaseEntities(GetConnectionString());
Or subclass you ObjectContext class and always use the new connection string:
public class MyDatabaseEntities : DatabaseEntities
{
public MyDatabaseEntities()
: base(GetConnectionString())
{
}
public static string GetConnectionString()
{
var conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DatabaseEntities"].ConnectionString;
return conStr.Replace("%APPDATA%",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
}
}
and use the new class anywhere.
I have another option. We don't need to replace anything. I am using below connection string without any replace and it's working fine.
<connectionStrings>
<add name="ProjectManagementDBEntities" connectionString="metadata=res://*/Models.ProjectManagementModels.csdl|res://*/Models.ProjectManagementModels.ssdl|res://*/Models.ProjectManagementModels.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\ProjectManagementDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"/>
</connectionStrings>
Main change is data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\ProjectManagementDB.mdf;integrated security=True;
I hope this will save someone.
You have to replace the %APPDATA% in the code with the relative path -
var connectionString = ConfigurationManager.ConnectionStrings["DatabaseEntities"]
.ConnectionString;
connectionString.Replace("%APPDATA%",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
I want to change the DB string connection I have stored in Web.config file depending on where is run the application.
I know how to read but, do anybody have an idea how to to change it?
http://geekswithblogs.net/AzamSharp/archive/2005/10/09/56457.aspx
Third link to come up on a BING search.
private void GetConfigSettings()
{
string path = Server.MapPath("Web.config");
string newConnectionString = #"(Your connection string here)";
XmlDocument xDoc = new XmlDocument();
xDoc.Load(path);
XmlNodeList nodeList = xDoc.GetElementsByTagName("appSettings");
XmlNodeList nodeAppSettings = nodeList[0].ChildNodes;
XmlAttributeCollection xmlAttCollection = nodeAppSettings[0].Attributes;
xmlAttCollection[0].InnerXml = txtKey.Text; // for key attribute
xmlAttCollection[1].InnerXml = newConnectionString; // for value attribute
xDoc.Save(path); // saves the web.config file
}
New answer based on your comment on my original answer
You can use the String.Replace function. The ConnectionString is just a string.
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
connectionString = connectionString.Replace("TextToReplace", "ReplacementText");
so assuming your connection string is
"Data Source=LiveDbServer;Initial Catalog=MyDataBase;Persist Security Info=True;User ID=someUserId;Password=yourPassword"
You could use the following logic
if(System.Environment.ServerName == "MyTestServer")
{
connectionString = connectionString.Replace("LiveDbServer", "TestDbServer");
}
The following is just based on a guess as to why you might want to change connectionstrings at run-time based on which server the app is running on
ALTHOUGH (added bonus idea) if your goal is to always have your test web server point to your test DB server and your live web server point to your live DB server, an easier method is to edit the HOSTS file. (I'm sure there are other options, but that was a simple enough hack for us, and it works with database connections, web service references, etc.)
Simply set up the hosts file on the test machine so that it maps "MyLiveDbServer" to the ipaddress of "MyTestDbServer", and viola - your apps will point to the test server without any extra code or configuration, automatically, and for all time.
I used to load the connection string into the Application object (for better or worse) in the Application_Start event of global.asax.
Then, I get the option of checking which server I'm running on and loading that connection string into the Application object, rhather than relying on just a single entry in web.config.
Example:
<connectionStrings>
<add name="testservername" connectionString="..." providerName="..."/>
<add name="prodservername" connectionString="..." providerName="..."/>
<add name="localhost" connectionString="..." providerName="..."/>
</connectionStrings>
...in global.asax:
<%# Import Namespace="System.Configuration.ConfigurationManager" %>
...
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
Application("cn") = ConnectionStrings(System.Web.HttpContext.Current.Request.ServerVariables("HTTP_HOST"))
End Sub
So then, every time I would have used ConnectionStrings("cn"), I will instead use Application("cn").
Check to see what HTTP_HOST gives you on each server and name your connection strings accordingly.
Alternately, you could just use ConnectionStrings(System.Web.HttpContext.Current.Request.ServerVariables("HTTP_HOST")) all over instead of storing the whole string in Application.
Another option would be to just store the host name in the Application variable to pass to ConnectionStrings any time you need it.