Initialization Of Connection String In WinForm And In UserControl - c#

See the Coding below:
**Application Config File**
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="Mystring" value ="server=MyServer;Initial Catalog
MyDataBase;uid=MYUID;pwd=MYPWD"/>
</appSettings>
</configuration>
**Connection Code:**
string connstr = ConfigurationManager.AppSettings["Mystring"];
SqlConnection con = new SqlConnection(connstr);
con.Open();
I have tested it at WinApplication and in Windows Control Library(UserControl) and found that the above code works in WinApplication and the same is not in Windows Control Library instead it throw exception like ” Connection string has not been Initialized”
If SQL assembly present in both VS application then Is it reasionable exception In Winows Control Library?.
What is the Solution?.

If you are using a test project, you need to add the settings (app.config file) there.
If you are debugging directly, DEVENV creates a sample app that host user control, you need to need to read the settings explicitly.
You can use preprocessor directives to differentiate whether user control debugging by DEVENV, or by hosting in under app.
Code like
#ifdef RunningUnderHost
// read app settings
#endif
RunningUnderHost can be defined over library, and not over app.

Related

Connecting to mysql database from windows forms application on another pc? [duplicate]

var connection = ConnectionFactory.GetConnection(
ConfigurationManager.ConnectionStrings["Test"]
.ConnectionString, DataBaseProvider);
And this is my App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Test" connectionString="Data Source=.;Initial Catalog=OmidPayamak;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
But when my project runs this is my error:
Object reference not set to an instance of an object.
You can just do the following:
var connection =
System.Configuration.ConfigurationManager.
ConnectionStrings["Test"].ConnectionString;
Your assembly also needs a reference to System.Configuration.dll
Since this is very common question I have prepared some screen shots from Visual Studio to make it easy to follow in 4 simple steps.
string str = Properties.Settings.Default.myConnectionString;
Also check that you've included the System.Configuration dll under your references. Without it, you won't have access to the ConfigurationManager class in the System.Configuration namespace.
First Add a reference of System.Configuration to your page.
using System.Configuration;
Then According to your app.config get the connection string as follow.
string conStr = ConfigurationManager.ConnectionStrings["Test"].ToString();
That's it now you have your connection string in your hand and you can use it.
//Get Connection from web.config file
public static OdbcConnection getConnection()
{
OdbcConnection con = new OdbcConnection();
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString;
return con;
}
Try this out
string abc = ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;
This worked for me:
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
Outputs:
Data Source=.;Initial Catalog=OmidPayamak;IntegratedSecurity=True"
It is possible that the OP in this question is trying to use an App.Config within a dll.
In this case, the code is actually trying to access the App.Config of the executable and not the dll. Since the name is not found, you get a Null returned, hence the exception shown.
The following post may be helpful:
ConnectionString from app.config of a DLL is null
1) Create a new form and add this:
Imports System.Configuration
Imports Operaciones.My.MySettings
Public NotInheritable Class frmconexion
Private Shared _cnx As String
Public Shared Property ConexionMySQL() As String
Get
Return My.MySettings.Default.conexionbd
End Get
Private Set(ByVal value As String)
_cnx = value
End Set
End Property
End Class
then when you want to use the connection do this in ur form:
Private Sub frmInsert_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim cn As New MySqlConnection(frmconexion.ConexionMySQL)
cn.open()
and thats it. You will be connected to the DB and can do stuff.
This is for vb.net but the logic is the same.
Have you tried:
var connection = new ConnectionFactory().GetConnection(
ConfigurationManager.ConnectionStrings["Test"]
.ConnectionString, DataBaseProvider);
I had the same Issue. my solution was built up from two projects. A Class library and a website referencing to the class library project. the problem was that i was trying to access the App.config in my Class library project but the system was searching in Web.config of the website. I put the connection string inside Web.config and ... problem solved!
The main reason was that despite ConfigurationManager was used in another assembly it was searching inside the runnig project .
The answers above didn't elaborate where the value in connectionStrings index comes from.
As mentioned above, to get your connection string, you say:
string conStr = ConfigurationManager.ConnectionStrings["XXX"].ToString();
To use the correct value of XXX, go to your main projects web.config file and look for the following piece of code:
<connectionStrings>
<add name="Authentication" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=Authentication;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Authentication.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
Where it says name= , the text within those proceeding quotes is the value of XXX you use in the code above. In my example above, it happens to be Authentication
string sTemp = System.Configuration.ConfigurationManager.ConnectionStrings["myDB In app.config"].ConnectionString;
It seems like problem is not with reference, you are getting connectionstring as null so please make sure you have added the value to the config file your running project meaning the main program/library that gets started/executed first.
First you have to add System.Configuration reference to your project and then use below code to get connection string.
_connectionString = ConfigurationManager.ConnectionStrings["MYSQLConnection"].ConnectionString.ToString();
You can use this method to get connection string
using System;
using System.Configuration;
private string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString;
}
You can fetch the connection string by using below line of code -
using System; using System.Configuration;
var connectionString=ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Here is a reference :
Connection String from App.config
I referenced System.Configuration library and I have the same error.
The debug files had not their app.config, create manually this file.
The error is, I solved this copying the file "appname.exe.config" in debug folder. The IDE was not create the file.
I solved the problem by using the index to read the string and checking one by one. Reading using the name still gives the same error.
I have the problem when I develop a C# window application, I did not have the problem in my asp.net application. There must be something in the setting which is not right.
In order to read the connection string from app.cfg (in windows service application) the below code worked for me
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["CONNECTIONSTR"].ConnectionString = #"New Connection String";
Encountered this issue while placing ConfigurationManager.ConnectionStrings in UserControl's constructor, and none of the solution here worked for me.
After some research, seems like ConfigurationManager.ConnectionStrings would be null while trying to access it from the DesignTime.
And from this post, I came up with this following code to detect DesignTime as a workaround to the issue:
public class MyUserControl : UserControl
{
....
public MyUserControl ()
{
InitializeComponent();
bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
if (!designMode)
{
this.connectionString =
ConfigurationManager.ConnectionStrings["xxx"].ConnectionString;
}
}
}

How to use various connection strings in WPF and DataSet in Debug and Release mode?

I have a lot of CRUD applications written using WPF and DataSet
My connection strings are:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Depboard.Properties.Settings.DepartmentConnectionString"
connectionString="ReleaseServer" providerName="System.Data.SqlClient" />
<add name="Debug"
connectionString="DebugServer" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
And these applications have many rows of code:
private static string ConnStr = ConfigurationManager.ConnectionStrings["ReleaseServer"].
ConnectionString;
Moreover, DataSet uses by default "ReleaseServer" connection string.
I am really scared to change all of lines of code with the connection string when I will switch between Debug and Release mode.
Is there a simple approach to change connection string in DataSet and in program between Debug and Release modes without modifying code?
How about using #if DEBUG?
Create a static class that you will use to obtain your server name:
public static class ServerName
{
#if DEBUG
const string SERVER = "DebugServer";
#else
const string SERVER = "ReleaseServer";
#endif
public static string Name => SERVER;
}
Then use that when initialising your connection string:
private static string ConnStr = ConfigurationManager.ConnectionStrings[ServerName.Name].ConnectionString;
This is, however, a bit of a dirty fix in my opinion.
The applications should really be using dependency injection and possibly a dependency container, along with patterns such as the Repository Pattern, to keep all the initialisation code in one place (at a suitable "seam"). If you use DI correctly, there's only one place where you need a connection string.

NUnit appSettings file attribute (linked config file) is not seen by ConfigurationManager in test

I have NUnit test (version 2.6.4) test. It uses ConfigurationManager.AppSettings["foo"] to retrive a configuration setting from the app.config file (which is in the test project). This is my App.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="bar.config">
<add key="thisSettingIsVisible" value="yes, indeed"/>
</appSettings>
</configuration>
and this is bar.config file:
<appSettings>
<add key="foo" value="this setting isn't visible"/>
</appSettings>
I'm using ReSharper 10 test runner to execute the test. bar.config file is copied to the bin/Debug directory. In fact, that configuration was working some time ago, but stopped. Any clues what can be wrong?
Now, I've figured out a workaround, but I'm not happy with this solution:
private static void InitializeAppSettings()
{
var exeAssembly = System.Reflection.Assembly.GetExecutingAssembly();
var assemblyName = exeAssembly.GetName().Name + ".dll";
var testDllFolder = new Uri(System.IO.Path.GetDirectoryName(exeAssembly.CodeBase)).LocalPath;
var openExeConfiguration = ConfigurationManager.OpenExeConfiguration(Path.Combine(testDllFolder, assemblyName));
foreach (var setting in openExeConfiguration.AppSettings.Settings.AllKeys)
{
ConfigurationManager.AppSettings[setting] = openExeConfiguration.AppSettings.Settings[setting].Value;
}
}
BTW. I can't abstract away ConfigurationManager usage form existing, legacy code.
I replicated your use case and found that my additional config worked in the context of an ASP.NET site but the additional appSetting was null in a test project until I changed the Copy to Output Directory property to Copy Always
If you use R# 10.0.0 or R# 10.0.1 - it is a known issue for such builds and it has been fixed in R# 10.0.2 build.

Is there a standard method to create a configuration file for C# program?

In the past I would just create a text file with key value pairs for example WIDTH=40 and manually parse the file. This is getting a little cumbersome is there a standard way to do this preferably with inbuilt support from Visual Studio or the .NET framework.
Configuration files are one of the built-in templates. Right-click on your project, choose Add->New Item. In the template box, select configuration file.
You could to create an Application Configuration File in Visual Studio. It's basically and XML file which you can to use to save your application configuration data, but it's not meant to be read as an XML file: .net framework provides some classes to interact with it.
This link can provide some background and sample code: Using Application Configuration Files in .NET
You could to place this code inside your .config file:
<configuration>
<appSettings>
<add key="SomeData" value="Hello World!" />
</appSettings>
</configuration>
And you can read it this way in C# (requires a reference to System.Configuration assembly):
Console.WriteLine(
"Your config data: {0}",
ConfigurationManager.AppSettings["SomeData"]);
Note you'll need to escape your data ti fit into a XML file; for instance, a & character would became &
In your C# project look in the folder: Properties and open the file Settings.setting.
Here you can specify settings at the user or application level.
The following code sample shows how to use the settings:
public partial class MyControl : UserControl
{
MyProject.Properties.Settings config_;
public MyControl
{
InitializeComponent();
config_ = new MyProject.Properties.Settings();
}
public void SaveToConfig()
{
// save to configuration file
config_.ReportFileName = dataFileName.Text;
config_.Save();
}
public void LoadFromConfig()
{
string dataFileName = config_.ReportFileName;
}
}
You can also use settings when starting your application, and to modify your settings as you upgrade you application.
static void Main()
{
// if user setting program version user setting is less than
MyProject.Properties.Settings config = new MyProject.Properties.Settings();
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
if (config.Version != version)
{
// migrate from version 1.0.2 to future versions here...
if (config.Version == null)
{
}
config.Upgrade();
config.Reload();
config.Version = version;
config.Save();
}

How to obtain build configuration at runtime?

Does anyone know how to get the current build configuration $(Configuration) in C# code?
If you unload your project (in the right click menu) and add this just before the </Project> tag it will save out a file that has your configuration in it. You could then read that back in for use in your code.
<Target Name="BeforeBuild">
<WriteLinesToFile File="$(OutputPath)\env.config"
Lines="$(Configuration)" Overwrite="true">
</WriteLinesToFile>
</Target>
There is AssemblyConfigurationAttribute in .NET. You can use it in order to get name of build configuration
var assemblyConfigurationAttribute = typeof(CLASS_NAME).Assembly.GetCustomAttribute<AssemblyConfigurationAttribute>();
var buildConfigurationName = assemblyConfigurationAttribute?.Configuration;
Update
Egors answer to this question ( here in this answer list) is the correct answer.
You can't, not really.
What you can do is define some "Conditional Compilation Symbols", if you look at the "Build" page of you project settings, you can set these there, so you can write #if statements to test them.
A DEBUG symbol is automatically injected (by default, this can be switched off) for debug builds.
So you can write code like this
#if DEBUG
RunMyDEBUGRoutine();
#else
RunMyRELEASERoutine();
#endif
However, don't do this unless you've good reason. An application that works with different behavior between debug and release builds is no good to anyone.
Conditional Compilation Symbols can by used to achieve this. You can define custom symbols the Properties > Build settings pane for each project, and the use the #if directives to test them in the code.
Example showing how the define the symbol UNOEURO and how to use it in code.
bool isUnoeuro = false;
#if UNOEURO
isUnoeuro = true;
#endif
Install the SlowCheetah Visual Studio extension.
Right-click on your config file and select 'Add Transform'.
Notice a transform for each build configuration.
Place a "Build" appSetting into the root config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<appSettings>
<add key="Build" value="" />
</appSettings>
</configuration>
And place a "Build" directive in each transform:
<?xml version="1.0" encoding="utf-8"?>
<!--For more information on using transformations see the web.config examples at http://go.microsoft.com/fwlink/?LinkId=214134. -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="Build" value="Debug" xdt:Transform="Replace" xdt:Locator="Match(key)"/>
</appSettings>
</configuration>
Then obtain the "Build" appSetting value in your C# code:
ConfigurationManager.AppSettings["Build"]
Please be mindful that you will not see the transforms when you are debugging: https://stackoverflow.com/a/17336009/109941
You can use a common static method with Conditional Attribute to set the flag to detect DEBUG or RELEASE mode. The SetDebugMode method will be called only when running in the DEBUG mode otherwise it is ignored by Runtime.
public static class AppCompilationConfiguration
{
private static bool debugMode;
private static bool IsDebugMode()
{
SetDebugMode();
return debugMode;
}
//This method will be loaded only in the case of DEBUG mode.
//In RELEASE mode, all the calls to this method will be ignored by runtime.
[Conditional("DEBUG")]
private static void SetDebugMode()
{
debugMode = true;
}
public static string CompilationMode => IsDebugMode() ? "DEBUG" : "RELEASE";
}
You can call it in the code like below
Console.WriteLine(AppCompilationConfiguration.CompilationMode);
I don't believe you can inject that at compile time into the assembly but one way you could achieve it would be to use MSBuild and add it to the config file of the application.
See this blog post about how to do multi-environment config files using MSBuild - http://adeneys.wordpress.com/2009/04/17/multi-environment-config/
Alternatively you could write an MSBuild task which would edit a certain compiled file (your C# or VB file) and have that run in the BeforeBuild task. It'd be rather tricky as you'd need to work out where to inject it into the file, but provided you had some kind of tokenization set up you should be able to do it. I also doubt it would be pretty!

Categories