Best way to set up the connection setting - c#

I am new to windows forms programming and I was wondering what would be the best way to create like a connectionstring.config (i dont know how to do this) I have seens it , its like an xml giving all the information to connect to the database, in my case I am connecting to a MySql database. I would like to have so i could do something like this (I KNOW THIS IS WRONG BUT YOU GET MY IDEA):
MySqlConnection conn = new MySqlConnection
(Someconfiguration.thatconnects.toMyXMLOrSomething["MyXMLFile]);
something like that, i know i am probably too far from what it is.. but I have seen this somewhere and i think its clean, instead of putting the data connection information everywhere i need it.
so a few questions:
How do i create that xml file in VS2010?
Where do I place that file?
How should I call it in the functions where i am using it?.
I would really appreciate all the possible help as I am learning and would like to keep everything separate and clean like this.
Thank you for your help and valuable time to help me.

You can put them in a specific node inside your app.config file.
Here's the MSDN documentation for adding the app.config file to your project and it includes adding connection strings: http://msdn.microsoft.com/en-us/library/ms243192(v=vs.100).aspx
<configuration>
<connectionStrings>
<add name="myConnectionString" connectionString="Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;" />
</connectionStrings>
<configuration>
You can then use the built in .NET ConfigurationManager class to pull it out:
ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

Right click your project - Add -> New Item... - General - Application Configuration File (app.config). You can add a connectionStrings section there.
See "Connection Strings and Configuration Files" for details.
If you really want to put you connection strings in a separate file you can set this up as well within your app.config file:
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionStrings configSource="connections.config"/>
</configuration>

How do i create that xml file in VS2010?
Add a new app.config file in the root of your project.
Where do I place that file?
Normally the root of your application.
How should I call it in the functions where i am using it?
string value = System.Configuration.ConfigurationManager.AppSettings[key];
string connection = System.Configuration.ConfigurationManager.ConnectionStrings[key];

Put in in app.config. It should already be in your project.

Here is some Microsoft documentation on the topic.
http://msdn.microsoft.com/en-us/library/ms254494(v=vs.80).aspx
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="ApplicationConnectionString" connectionString="YOUR_CONNECTION_STRING" providerName="System.Data.PROVIDER_NAME"/>
</connectionStrings>
</configuration>

Related

How to define web.config local variables

I have a web application in C# with .NET Framework 4.0 and I'm trying to find a way to define a variable in Web.Config that can be referenced elsewhere within the Web.Config.
I want something like this.
<?xml version="1.0" encoding="utf-8"?>
<LocalWebConfigVars>
<add key="Var1" value="ServerName1"/>
<add key="Var2" value="DatabaseName1"/>
</LocalWebConfigVars>
<configuration>
<connectionStrings>
<add name="AppConnectionString" connectionString="DATA SOURCE=#Var2 ServerName=#Var1"/>
<add name="OtherStuff" value="#Var1"/>
etc...
Currently I have to keep 3 or 4 hard-coded values (some embedded others just the value) updated to the same thing and would like to make it easier to keep in sync.
Is this possible?
Thanks.
Edit:
Just some background. The reason this is becoming problematic is that we define the apps database instance (among other instance specific setting) in the web.config. We have multiple database instances in our test and production environments and if I need to switch to a different one them while testing something and miss one of the hand full of references I get some strange results. I'm trying to avoid this by defining it once and referencing it everywhere else.
Would not doing a simply .config transformation for each of your environments work, by setting up a project configuration & transform, you would be able to swap from environment to environment by the use of solutions configuration dropdown.
See this link
for more info on transforms on .config files

How does AppSettings in VB.NET windows Forms work?

Hello I have build a small app to demo a concept in C# in which I added the application config file etc added System.Configuration dll to the reference and accessed the settings:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="username" value="myknownusername"/>
</appSettings>
</configuration>
No news It worked flawlessly with the code:
private String username = ConfigurationManager.AppSettings["username"];
Now I have been asked to do the port the app to VB.NET and to my biggest surprise. It's been a while that I opened visual studio in VB.NET project. I was surprised to see an already white dashed App.config file so I added my AppSettings section and after 3 hours I still can't get the value of the username using the same ConfigurationManager
Dim username as String = ConfigurationManager.AppSettings("username")
I have included another application configuration app1.config which by the way has generated entries already. I could not get anything with the app1.config either.It also returns Nothing
</sharedListeners>
</system.diagnostics>
</configuration>
I am really perplexed as how a simple reading of configuration file could be this challenging in VB.NET unless I am using the wrong method which I always use in C#.
Kindly point me to whatever I am not doing right.
EDIT
As you can see in the picture below, I have all it needs to work properly.I as expecting to read the setting key from either App.config or app1.config. When I run like shown below the MessageBox is empty
I found the culprit, I needed to right click the generated App.config and choose Include In Project. that's it. it's weird because I never do that in a C# project.

How to encrypt config file ? desktop .NET

Please give me a working example.
I have already created a topic, but I'm not there who are not helped How to encrypt app.config?. Or am I just not what is not understood.
Once again, I beg you give 100% working example.
I need to encrypt connectString to access the DB mysql.
is an example http://www.c-sharpcorner.com/UploadFile/yougerthen/306132008064100AM/3.aspx.
There are two ways the first I have an error.
Second, I do not understand how to use
Do not write a lot of text, I do not understand very well. I'm Russian.
UPDATE:
I decided to use http://msdn.microsoft.com/en-us/library/system.configuration.rsaprotectedconfigurationprovider.aspx.
But I have an error: "Failed to encrypt the section 'connectionStrings' using provider 'RsaProtectedConfigurationProvider'. The error message from the provider: The object already exists."
I Create App WPF. Append file app.config.
app.config body:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="myconnect"
connectionString="myConnectString" />
</connectionStrings>
</configuration>
What do I do next ?
Do this in your installer,
rename app.config to web.config.
Use ASP.NET way to encrypt the data you want to encrypt.
Rename it back to what.exe.config.
Best practice is to do it manualy in your settings class: http://msdn.microsoft.com/en-us/library/system.configuration.rsaprotectedconfigurationprovider.aspx

WebService doesn't read web.config

I've got 3 connectionstrings in web.config, and I used theirs like this:
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SomeName"].ConnectionString))
Every metgod is called by winforms application.
One of webmethods doesn't work properly because it reads only one connectionString:
data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
It's not a connectionString from my web.config .
I invoke every method in the same way.
How it's impossible ??
EDITED:
I use facade: This is structure:
WinForms calls WebMethod SaveItem
SaveItem calls method on Facade: SaveItemAndDoDatabaseStuff
SaveItemAndDoDatabaseStuff does database stuff.
We can't see your web structure, but is it possible that your app isn't configured as an application in IIS, therefore is picking up the master web.config? Which would look exactly like that...
Go into IIS and ensure it is an application (it may have a cog icon).
If your WinForms application talks directly to database X (not via the web service), then the connection string for database X should be in app.config (in the WinForms project).
If your Web Service (as I understand, this includes your facade and your database layer), talks to databases X, Y and Z, then the connection strings for X, Y, and Z need to be in web.config (in the Web Services Project).
It's using the default connection string asp.net has (in the machine.config in the .net installation folders).
Do a clear:
<configuration>
<connectionStrings>
<clear/>
... your connection strings here
</connectionStrings>
</configuration>
Btw, when you say you are using "SomeName" in the connection string. It isn't surely any random connection string you used, its the default: "LocalSqlServer".
You should store the connection-strings in the web.config or app.config in whatever project that you are executing.
In your case, you should have the connection-strings in your app.config for your winforms application.
Why not just add a Trace line to print out the configuration file being used just before you ask for the connection string. Simply add the following line:
System.Diagnostics.Trace.WriteLine(
System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile,
"APP_CONFIG");
Set a breakpoint after this and look at the Output window for a line that starts with "APP_CONFIG:". This will give the full path to the configuration file and allow you to determine where it's being loaded. If you still see a discrepancy between the runtime values and the configuration file then likely something is changing those values at runtime within your application.
This is a late answer, but perhaps worthwhile.
I have a web-service project, and I want to run it in two modes.
One is "local as app" (for testing), and for that, at least in my current system setup, the file where it reads from is
Web.config (which it apparently reads in deug mode INSTEAD of Web.Debug.config, at least for database configuration)
So, one replace the attribute section with and copy in the ones you would use in the "Calling project for hte web service).
So replace
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
with
<appSettings>
<!-- Database Connection -->
<add key="AppDatabase" value="RedactedDatabase"/>
<add key="AppLoginID" value="RedactedLoginID"/>
<add key="AppLoginPwd" value="RedactedPwd"/>
</appSettings>
The above are found in app.config in the "calling project".... To me, this is more elegant anyway.
Now it will work in both modes.
One could use a conditional compile in the C#, but now you just read it in:
C# code:
String whichDatabase = System.Configuration.ConfigurationManager.AppSettings["AppDatabase"];
String appUsedID = System.Configuration.ConfigurationManager.AppSettings["AppLoginID"];
String appUsedPwd = System.Configuration.ConfigurationManager.AppSettings["AppLoginPwd"];
The above works in either mode, without conditional compile directives.

How to make the Setting works for Class Library project in C# 2.0?

I am putting the setting under the property of one of my C# Class Library project for app setting:
EUCAccountService_ConnectionString
EUCTelcoDB_ConnectionString
In the development, it works nicely. Until I deported to production, I realise that the component that use those thing .. it just hang. I found that under \BIN when it compiled dewaCorp.EUC.TelcoDB.Data.dll.config and open up that file and turn out nothing.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>
How to make this works? I thought by compiling it, it turned to some sort config file or something. But it didn't.
I am appreciated your comment.
The properties are not stored in the .config file they are stored in the windows user profiles.
To store setting in the .config file add a config file to the executing assembly (take note is important to use the executing assembly) and store add the settings there for connection strings there is a special note for them.
<ConnectionStrings>
<ConnectionString />
</ConnectionStrings>
You'd better take a look at similar projects, such as log4net, and Enterprise Library.
http://logging.apache.org/log4net/index.html
http://www.codeplex.com/entlib

Categories

Resources