Updating my App.config Connection String from a text box - c#

I want the user to be able to edit the connection string, I've set up a file browser dialogue where they can only select .accdb files, and I'm trying to have the save button overwrite the current connection string with the file path from the text box. I've had multiple errors at different times and I've ended up with a setup that seems tantalisingly close to working but I have a NullReferenceException error which says "Object reference is not set to an instance of an object". Hopefully this is a newbie mistake.
var configuration = ConfigurationManager.OpenExeConfiguration(#"\\Mac\Home\Documents\Visual Studio 2015\Projects\tiddlywinks\tiddlywinks\App.config");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["tiddlywinksDatabaseConnectionString1"].ConnectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source ='" + filePathTextBox.Text + "'; Persist Security Info=False;";
configuration.Save();
This is the code that I have atm. Can anyone help?
Also, is there a way to achieve the same without having to tell the program where App.config is, surely Visual Studios knows where it's own config files are?

You can do that this way:
You go to your solution properties
Properties => Settings => Add new Settings
(Make sure Scope is "user")
and add a new sitting for your connection string, let's call it : ConnectionString
like mentioned in this post:
Applications sittings
then all you have to do is
Properties.Settings.Default.ConnectionString = TextBoxConnectionString.Text
Properties.Settings.Default.Save();
Give it a try, Hope it helps !

user cannot change application setting at run time.
It can be modified only at design time.
Use User settings for this.
How to : Using Application Settings and User Settings
Regards

Related

Unable to find connection 'MyConnName' for object 'Web.config' in Table Adapter configure Properties

I want to change the query in table adapter but it's not opening & throwing an error "Configure table Adapter Failed" & in property of connectionString it says "Unable to find connection 'ConnStringName' for object 'Web.config'. The connection string could not be found in application settings, or the data provider associated with the connection string could not be loaded"
I have been looking for a solution for this problem for a long time. Thankfully I found a solution that worked for me.
Close the dataset window with the error.
Right click the dataset in the solution explorer.
Select “Open with…” from the context menu.
Select “Source Code (Text) Editor” from the list and press the “OK”
button.
Near the top of the file, you’ll see a element with several elements within it. Most datasets should only have one element. If you are having trouble like I’ve described above, you’ll have at least two and one will be incorrect. Delete it or otherwise fix it, save the file and reopen normally.
This is the page where I found it out.
See the complete answer here
I faced the same problem which is actually a nightmare and triyed Lorena solution and it was not enough to solve the problem.
The missing part is to modify the Dataset using the XML editor changing the DefaultConnectionIndex to be 0 like this:
<DataSource DefaultConnectionIndex="0"
FunctionsComponentName="QueriesTableAdapter" Modifier="AutoLayout, AnsiClass,
Class, Public" SchemaSerializationMode="IncludeSchema" xmlns="urn:schemas-
microsoft-com:xml-msdatasource">
thanks to Don who pointed this
https://social.msdn.microsoft.com/Forums/windows/en-US/08a48cad-619d-4421-b584-f2b5550ba6c5/dataset-designer-quotunable-to-find-connection-myconn-mysettings1-for-object-mysettingsquot?forum=winformsdatacontrols
Seems like there no ConnStringName parameter in connectionString section of Web.config
<connectionStrings>
<add name="ConnStringName" providerName="" connectionString=""/>
</connectionStrings>
Updated:
The problem is in missing reference to System.Data.OracleClient. To solve this just add reference on missing provider.
Well Same problem I faced in Windows Forms, I just opened Settings.settings file, found the "ConnectionString" and repaired it.
(As you click in Value field of ConnectionString a button [...] appears in last of Value field click it and repair/test your connection again, in my case I re-entered password again.) .
Hope This Helps.!
ConnStringName is case-sensitive.

DataDirectory Set up project

I am doing a SETUP project for a C# winforms, sqlite application.
Connection string seems to a bit of a problem. The user will put the Database he wants to work with at a location(which v will tell him). In this example it is "C:\\Program Files(x86)\\DefaultCompany\\RSetup"; The user can work his own copy of the DB.
So I am setting the data directory to this path in the Program.cs Main
This is the only way I can think of. If there is a better way thats grt!!.
App.config
<add name="ConnString" connectionString="|DataDirectory|\MySQlite.db;Compress=True;Version=3"
providerName="System.Data.Sqlite" />
Program.cs
Setting the datadirectory to the path of the executable. Currently hard coded the path of the executable
static void Main()
{
AppDomain.CurrentDomain.SetData("DataDirectory","C:\\Program Files(x86)\\DefaultCompany\\RSetup");
This doesn't seem to be working. It doesn't give any error except the data is not blank. Doesn't seem to be working in both set up and the regular project
Thank you
JC
You could ask the user where the database is located, store that path somewhere (such as User Settings) and then you can retrieve it at any time. This would give the user more flexibility of where to put it and multiple users on the same machine could have their own database if desired.
Here is some pseudocode...
string dbLocation = Properties.Settings.Default.DatabaseLocation;
if (string.IsNullOrWhiteSpace(dbLocation)
{
dbLocation = AskUserForLocation();
Properties.Settings.Default.DatabaseLocation = dbLocation;
Properties.Settings.Default.Save();
}
AppDomain.CurrentDomain.SetData("DataDirectory",dbLocation);
Using this approach you could also add a menu option to allow the user to change the location if desired.
It also gives you the ability to retrieve the value anywhere, including where you create a connection, you can append the path to the location between where you read the connection string and you create a new connection.
SQLiteConnection myConnection = new SQLiteConnection;();
myConnection.ConnectionString = Path.Combine(Properties.Settings.Default.DatabaseLocation, myConnectionString);
myConnection.Open();

Pointing datasource to correct folder

I have built my application in c# and have an sql compact DB to go along with it. What do I need to change the location to in order for it to point to the same directory as the application.
For example:
Right now my DB is in C\Windows blah blah...
And in my code I make the source point to that...when I build the project my app is in bin\release along with my DB file, but in my code the source is not pointed to this DB file..does anyone know what I need to insert to point it to the correct DB file?
Thanks..
Is it always going to be in the same directory as the application executable? If so, perhaps you can just set the connection string using the path of the current assembly (assuming everything is in the same place):
string curPath = String.Format("{0}\\{1}", System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase), "MyDatabase.sdf");
SqlCeConnection conn = new SqlCeConnection(String.Format("Data Source = {0}; Password ={1}", curPath , ":PASSWORD:");

"Data source name not found and no default driver specified" for creating access connection

This is my connection to an access database in .NET:
OdbcConnection conn = new OdbcConnection("Driver={Microsoft Access Driver (*.mdb)};Dbq=" + path + "\\Access.mdb;Uid=;Pwd=;");
And I got this problem:
base {System.Data.Common.DbException} = {"ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"}
I have tried couple of database connection strings from here: http://www.connectionstrings.com/access but none of them working.
Any suggestions for this?
Thanks in advance.
There is an easy way to get the connection string, try it as follow:
Create a text file and change it's extension to .udl.
Open the new file by double click it and choose to open it with any text editor, notepad for example.
In the opened window, choose your provider and your database and click OK.
Open this file with notepad as a text and you will find the connectoin string inside it.
See This for more details.
as you can see in the same site you have linked above, the default way to connect to access database is specifying the Microsoft.Jet.OLEDB.4.0 Provider:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;User Id=admin;Password=;
does this work and if not what kind of errors do you get?
First, is path a valid field?
Second, try to output the String you are using to connect with the database file, as a sanity check. Make sure the output string matches what you are expecting, and that the file specified exists.
Try this
http://www.connectionstrings.com/
More specifically this one
http://www.connectionstrings.com/access
I would change your code to the following:
OdbcConnectionStringBuilder sb = new OdbcConnectionStringBuilder();
sb.Driver = "Microsoft Access Driver (*.mdb)";
sb.Add("Dbq", "C:\\info.mdb");
sb.Add("Uid", "Admin");
sb.Add("Pwd", "pass!word1");
OdbcConnection con = new OdbcConnection(sb.ConnectionString);
web.config add
add name="odbcConnectionString"
connectionString="Driver={Microsoft Access Driver (*.mdb)};DBQ=|DataDirectory|info.mdb; "
providerName="System.Data.OleDb"

How do I Programmatically change Connection String un LINQ C# Winforms

This question may be redundant, but i could not totally understand how to do this.
I need to be able to, when the users Run my Winforms app, can search for the instance of SQL if the previous one are not available. I already have the check for the DB existence, and also made a dialog wich search for all the available instance, and bulding the connection string isn't a problem. The point here is that, I need to be able to everytime the users open the app it loads the CN from a external file, and if the external file doesn't exist or the instance isn't available, i can use the app in another instance (asuming, offcourse, that the required DB is in that Instance).
The point is that, i don't know how to Programmatically change Connection String, using LINQ in winforms.
Thanks in advance
You should be to pass the connection string to the DataContext constructor.
var db = new MyDataContext(myconnectionstring);
var someConnectionString = "This is my connection String";
using (var db = new SomeConcreteDataContext(someConnectionString)){
//...Do whatever...
}
A DataContext is created per 'unit of work'.
As ichiban says pass the required connection string into the constructor when creating the DC

Categories