SubSonic connection string for SQLite - sqlite

I'm writing a desktop app which needs a simple persistence layer - I found out about SubSonic and it's capability to work with SQLite. However I need to keep the database file in user's AppData folder and don't know how to put such value into app.config - I don't want to use absolute paths.
Can app.config somehow access enviroment variables or reference application data folder?

For subsonic v2.x I would ignore the app.config connection string and just set it at runtime before working with the database. The provider name stays the same of course.
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), #"MyApplication\Northwind.db3");
DataService.Providers["Northwind"].DefaultConnectionString =
String.Format(#"Data Source={0};Version=3;New=False;Connection Timeout=3", dbPath);

There's no way to specify the AppData folder in the app.config for a connections string.
But what you could do is write the value to the config file either during install or when the application is first run.

The "framework way" of finding appdata is to use Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
This will find the correct appdata path regardless of platform.

There are several ways if you are using ASP.NET , in either language
Server.MapPath("~") will return the root of the application as a full path name then you can just add "/app_data" to it to get you're full path.
Alternatively inspect the HttpContext.Current.Request and HttpContext.Current.Application
there are numerous ( and much better then the one I just mentioned ) properties that will provide you with the same folder - being the root of the application as s full path.
Note that these should all work even if you have the application as a virtual folder and a regular folder with an application configures in IIS on that folder
However this is only possible at runtime , so it can't really be mentioned in the app.config. you could try using relaltive paths from where the app.config is resident IE "../App_Data" or "/App_data" but I'm not sure of you're exact requirements.
Good luck

Related

Qt - Auto detection of a file in application folder

I have a sqlite database of my Qt C++ application. Suppose I located it on my default build/release folder and I also placed the database file on that same folder. I have login.h and login.cpp. I want that the application may auto detect the database and open it. I will only provide the name of database (Ex: mydb.sqlite).
Database.addDatabase("QSQLITE");
Database.setDatabaseName("I will only provide database file name here.like: mydb.sqlite");
I want that the rest of the directory should automatically detected and the database connection works perfectly.
Suppose, I have the sqlite file in:
C:/Qt/build-myapp-mingw-32/mydb.sqlite.
I am taking a string variable called path. And I want that, the application automatically detect the whole path. And open the database connection.
You do not have to give the complete path to database to make it works.
You can refer to the path from your build dir or maybe use :
QCoreApplication::applicationDirPath();
To get the path of your app and then navigate through your directories with .. ?

IIS Web application and class-library configuration - config file is lost when deployed

I have an ASP.NET web application written in C# 4.0. The application references a class library that comes with its own configuration file. At runtime, the class library uses similar to the following code to load this specific configuration:
var exeConfigPath = this.GetType().Assembly.Location;
var config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
This is done because the library has to load its bundled configuration rather than the application configuration. The application configuration should not be concerned of the library's settings and should not be able to alter them.
Now, there are a few other things that need to be done for this concept to work. I have to set the library's configuration file build operation as Content in the properties window and the Copy to be Copy Always or Copy If Newer. So far so good - the file gets automatically both into the class library's bin directory, and the web applications's bin directory, and is correctly renamed from App.config to CustomLibrary.dll.config (as supposed, the library's dll is CustomLibrary.dll).
Now I am facing two issues.
1) When I publish the web application to a filesystem location (mapped in IIS), the CustomLibrary.dll.config appears back as App.config in the bin folder of the published app. OK - I will rename it in the class library project to match the expected convention - and problem solved.
2) Even when published, the IIS compiles the application again and stores it in the ASP.NET Temporary Files. There is a fancy directory structure with a folder dedicated for each assembly referenced. The folder corresponding to the CustomLibrary.dll does not contain the config file in it. Since this.GetType().Assembly.Location will return the path to the temp folder, the application fails to load the configuration and crashes as it should.
I need to preserve the pattern of having the configuration in the class library, and be able to make it work in the web application. When manually copying the .config to the temp folder, the app works, but see, I really hate manual copying to randomly-named folders.
Is there a way to either prevent IIS from using the temp folders, or to make it copy along the config files? I believe the problem I am facing is configuration-related rather than conceptual since the application works as expected when the config file is in place. I'd prefer not to mess with using hard-coded physical paths to the config file either.
Edit:
To make it clearer, I will point out what and why I want to achieve. The idea is that the library and the web project will be developed as separate products - there will be no user or application specific information in the configuration of the library, so it will not change for different use scenarios. It is also rather specific to the class library functionality rather than the end application. It makes sense for me to keep the library's configuration information bundled within it (similar to Java, where a spring context xml file, or a properties file, get bundled with the jar of the library). I'd like to avoid having to copy the configuration in each app/web config of the consumer application. There will be cases where the consumer application is developed by third parties, and I do not want to rely on them doing their configuration right for my stuff to work. Again, the only issue here is not having the config file copied to the right place.
If those are static, internal settings that nobody should see or change, wouldn't you be better off having a file with the configuration included within the class library as an embedded resource? Either that or just a static class with the settings.
That way you'd be certain that nobody alters it, which in your scenario seems to be a plus.
I have come along a way to work arround the described issue, still not a very pleasant one to my requirements.
The solution is to take advantage of the application configuration (web.config in web apps, or app.config) which is always available. I have added as settings the absolute paths to the config file for each library. So I ended up with:
<!--
THIS IS IN THE WEB.CONFIG FILE
-->
<appSettings>
<add key ="ClassLibrary_ConfigPath"
value ="{My Publish Output Folder}\ClassLibrary.dll.config"/>
</appSettings>
and the class library now uses the following code to load its configuration:
Configuration config = null;
try
{
var exeConfigPath = this.GetType().Assembly.Location;
config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
}
catch (Exception e)
{
if (!IsConfigurationNotFoundError(e))
{
// IsConfigurationNotFoundError logic skipped for brevity
var exeConfigPath =
ConfigurationManager.AppSettings["ClassLibrary_ConfigPath"];
if (exeConfigPath != null)
{
config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
}
}
else
{
throw;
}
}
While this works, I will wait for a better solution if possible. Still, I do not have to copy the entire ClassLibrary.dll.config into the web.config file, but now I must manage filesystem locations and be aware of app-setting names. What I really want is the consumer app of the ClassLibrary.dll not to deal with its configuration in any way. If it were a desktop app, I have this covered, as Visual Studio copies the ClassLibary.dll.config appropriately. I hope there is a way to make it work smoothly for web apps.
The short answer is: you can't. You have to merge both configuration sections and place all settings in the main configuration file of your application. In case of the web application it would be the web.config. Read this

Connection String in a .Net Windows Program

I'm working on my first Windows .Net application (as opposed to a .net web app, which I've done a lot of), and I have a question about database connection strings - is there an equivalent to the section in web.config?
I want to be able to have the program run against our test database (which will required a different connection string. What is the "canonical" way to define connection string objects in a Windows .Net application?
Thanks
Rather than write this all down again, here's a good article on this subject:
Storing and Retrieving Connection Strings
Add an "application configuration" file to your project. It will add a file called "app.config" Put your connection in there.
When the app is compiled it will change the name of the config file to match your executable. For example: MyApp.config.
I'm not sure what you mean by "canonical" way to define connection string objects. Name them whatever you want. Sometimes we use the name of the database, sometimes just the name of the project.
With regards to having multiple config files, we use Config Transforms. Which name them app.config, app.debug.config, app.release.config, etc. and use configuration manager to define which one to use based on where it's being deployed.
Non ASP.Net apps simply use app.config instead of web.config. See here.
Connection strings can be stored as key/value pairs in the
connectionStrings section of the configuration element of an
application configuration file.

Configuration madness, I have an app.Config but my object looks to web.Config

if you have a class library project that acts as ur DAL and it has an App.Config file with connectionstrings, how can I force it to use that config file? It keep getting values from the web.config in my Web Application project.
The DAL project uses LinqToSql. When I instansiate a DataContext object in my Web Application, from the referenced DAL Class Library project, can I make it use it's app.Config connectionstrings? It seems to ignore this file and tries to pick up connectionstrings from the web.Config connectionstrings node. There are no connectionstrings present there.
Any help is appreciated. A colleague mentioned making the app.Config in the DAL and embedded resource. Does that sounds like a good idea?
Thanks,
~ck in San Diego
Web applications always use web.config. Desktop applications always use app.config.
how can I force it to use that config file? It keep getting values from the web.config in my Web Application project.
You can't. If you use the System.Configuration classes, they will always pull from the active application's .config file (app.config for executables, web.config for asp.net websites).
Workarounds include using file i/o for reading your settings out (as opposed to the System.Configuration namespace) or putting your DAL configuration information in the appropriate .config file (the more common choice).
I'm not sure, but take a look at that:
using System.Configuration;
ExeConfigurationFileMap Map = new ExeConfigurationFileMap();
Map.ExeConfigFilename = FileName;
Configuration Conf = ConfigurationManager.OpenMappedExeConfiguration(Map, ConfigurationUserLevel.None);
AppSettingsSection section = (AppSettingsSection)Conf.GetSection("???");
Here's how I think of a *.config file. Say you have a method in your DAL:
DoSomething(connectString, SqlDialect, businessObject)
Since connectString and SqlDialect don't change with every call to this method, it would be nice to be able to remove those parameters and get those through some other means.
Well, *.config files are there for that reason--they are not only environment-specific, they are also app-specific. It's so your Web app can say, "Hey everybody, connectString = "..." and SqlDialect = "...", for every method call, until I say otherwise."
Let's say you want one app to log into SQL with one set of credentials, and another app to use another set of credentials (with different perms if necessary) so that the DBA can keep track of which app is doing what (if he/she so chooses). Well, *.config files make this happen.
That's why the app that you're running is the one that provides the *.config file. So just cut all the contents from your DAL's app.config file and paste it into your Web.config file, then delete App.config. You should be good-to-go after that.

Specifying connection string in config file for a class library and re-use/modify in ASP.NET Web Application

How can one specify the connection string in a config file of a class library and later modify this when used in a ASP.NET Web Application?
The Class library is a data access layer that has a Dataset connecting to a database based on a connection string specified in a config file (Settings.settings/app.config).
This class library is used in a web application where user inputs data and is written to the database using the DAL classes & methods exposed in the class library.
Now, I want to migrate this application from development environment to testing environment and later to production. The problem I'm facing is that after migrating to testing, the app in testing still connects to development database. I've changed the connection string mentioned in <class library>.dll.config file but this seems to have no impact.
Can someone explain the right way to achieve this? Thanks in advance for any help. Cheers.
With the .config files the name has to match the main executing assembly. For example I had a situation like yours, I needed a class library to have its settings in a .dll.config file. While it was able to reference it the actual application would not be able to read the config file because it was expecting .exe.config. Renaming the .dll.config to .exe.config fixed the problem.
In your case migrating your connection strings from .dll.config to web.config should fix your problem!
Good luck!
Joshua is partly right ... For posterity I would like to add a bit more to this answer as I have delt with the same problems on several occasions. First, one must consider their architecture. There are several issues you can run into with .config files in ASP.NET based on deployments.
Considering the architectural ramifications:
Single tier (one server):
A simple web application may be able to leverage a reference to the sites Web.config file and resolve your issues. This would be a fine solution for a single tier application. In the case of a windows application leveraged as a .exe file, the App.config will work too.
Multi-tier (more than one server):
Here is where things became a bit hairy for me the first time I was working with .config files across boundries. Remember the hierarchy of the config structure and keep this in mind (MSDN Article on .Config structure) - there is a machine.config at the root in the appropriate ASP.NET folder. These reside at each physical server. These are overridden by the site Web.config (or App.config) which are in turn overridden by subfolder .config files. If you have more than one .config file you may want to use one of the methods to pass the file path for the specific .config you want to use. More importantly, these files each may have connection information. ASP.NET's machine.config holds some for the framework ... so you should at least be senstive to the fact this is an "inheritance" chain. Second, any changes to the Web.config file once deployed will tell the application to restart. This will result in loss of state (bad if you have active users on the site). The way around this is to keep a separate .config file (e.g. connections.config) and put a reference to that file in the Web.config. This will allow you to change the connection information (e.g. password) without having to restart the application. Here is a link to more info: MSDN: Working with Configuration Files. This article lays out all the details you need to be aware of in a normal server / IIS deployed application. Keep in mind that the .config files are mainly intended for applications, not libraries. If you have several tiers, chances are you are using some communicaiton / messaging layer (e.g. WCF). This will have / allow its own Web.config. You can keep connection strings there (and encrypt them if needed), but better yet, put them in a second file referenced by the Web.config for manageability. One final point, if you are ever going to consider the cloud, .config files are wrapped for application deployments which in effect removes all of the benefits they offer in terms of "not having restart or redeploy". Azure deployments will want to consider this article to save themselves from nightmares of maintenance: Bill Lodin blog - Configuration files in Azul / Cloud. One other point on this article – great example on how to programmatically select configuration depending on deployment! Be sure to check that out if you want to add flexibility to deploy in or out of the cloud .
I hope these points saves all of you time and headaches. I know I lost a couple days of programming time dealing with these issues ... and it was hard to find all the reasons in one place why may app was not "implementing" its connection object. Hopefully this will save you all from the same fate I had.

Resources