How to pass connectionstring value from Unity3d to a classlibrary with ConfigurationManager - c#

I created a class named "DB" in a ClassLibrary named "DBLayer" to connect a database named "LinguisticsDB". When I implement this ClassLibrary into another project, it can connect its App.config file via "connectionStrings" tag. But I need to access my ClassLibrary from Unity3d help to some kind of file like App.config. I need a step-by-step guide.
On the other hand, I do not know where should I import App.config file?
My DB class into DBLayer:
public static string connectionString = ConfigurationManager.ConnectionStrings["LinguisticsDB"].ConnectionString;
static SqlConnection connection = new SqlConnection(connectionString);
static SqlDataAdapter sqlDataAdapter;
public static DataSet GetData(string query)
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
DataSet dataSet = new DataSet();
sqlDataAdapter = new SqlDataAdapter(query, connection);
sqlDataAdapter.Fill(dataSet);
connection.Close();
return dataSet;
}
My App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<connectionStrings>
<add name="LinguisticsDB" connectionString="Data Source=DESKTOP-NORA1IP; Initial Catalog=Linguistics; Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
I tried to import App.config file into my Unity project inside Scripts folder; but it did not work.

I solved my problem using static connection string. This is awful but it worked.
I changed this
public static string connectionString = ConfigurationManager.ConnectionStrings["LinguisticsDB"].ConnectionString;
to this
public static string connectionString = #"Data Source=.; Initial Catalog=myDatabase; Integrated Security=True;"

Related

What is wrong in the following connection string?

I am trying to create page in asp.net page and I am getting the following error
Error:-System.NullReferenceException: Object reference not set to an instance of an object. at TestdateAssistor.user_info.Button1_Click1(Object sender, EventArgs e)
at this line
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\SQLEXPRESS;Integrated Security=True"].ConnectionString);
This is my complete code
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"].ConnectionString);
conn.Open();
String insert = "insert into Table (NAME,ADDRESS,MOBILE NO,ADHAR NO,DOB) values (#name,#add,#mob,#adhar,#dob)";
SqlCommand com = new SqlCommand(insert,conn);
com.Parameters.AddWithValue("#name",TextBox1.Text);
com.Parameters.AddWithValue("#add",TextBox2.Text);
com.Parameters.AddWithValue("#mob",TextBox3.Text);
com.Parameters.AddWithValue("#adhar", TextBox4.Text);
com.Parameters.AddWithValue("#dob", TextBox5.Text);
com.ExecuteNonQuery();
Response.Write("Successful Registration!!");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:-" + ex.ToString());
}
What changes should I make in the connection string?
You’re using the connection string as a key to your connection strings defined in the Web.config. So you need to define the connection string there and give it a name, then reference it in the code by name:
Web.config:
<connectionStrings>
<add name="myConnectionString" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True" />
</connectionStrings>
Code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
The ConnectionStrings is a collection automatically built for you by the framework. Its content is retrieved from the web.config where you should have it defined in the proper section.
Then you retrieve its value passing the Name between the square brackets not the whole connectionstring.
string cnString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(cnString);
and in your web.config you add the proper definition for your connectionstring
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"/>
</connectionStrings>
.....
</configuration>
Error:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"].ConnectionString);
Solution 1:
in main program (.cs)
SqlConnection conn = new SqlConnection("Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True");
Solution 2:
in web.config
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"/>
</connectionStrings>
</configuration>
in main program (.cs)
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;);
reference: https://msdn.microsoft.com/en-us/library/d7469at0(v=vs.110).aspx

ASP.NET - System.NullReferenceException: Object reference not set to an instance of an object

I created a project in my laptop and it was working fine.
I transferred my project to another laptop and now it gives me a System.NullReferenceException error.
Somehow, the database doesn't establishes, it gives a NULL exception.
My code:
public partial class registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// error is here
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["registerationConnectionString"].ConnectionString);
conn.Open();
string chekuser = "select count(*) from userdata where uname='" + TextBoxUN.Text + "'";
SqlCommand com = new SqlCommand(chekuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already Exist: ");
}
conn.Close();
}
}
}
WEB.CONFIG
<configuration>
<appSettings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
</system.web>
</configuration>
You don't have any connection string at web.config file with name = registerationConnectionString thus ConfigurationManager.ConnectionStrings["registerationConnectionString"] gives us null value and then when we want to get ConnectionString of null, it gives us System.NullReferenceException. You can resolve this by adding following portion in web.config.
<connectionStrings>
<add name="registerationConnectionString"
connectionString="Data Source=YourServerName;
Initial Catalog=YourDatabaseName;
Persist Security Info=True;
User ID=yourUserId;
Password=yourPassword" />
</connectionStrings>
Since the error is occuring on this line:
SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings
["registerationConnectionString"]
.ConnectionString);
You should assume that the ConfigurationManager.ConnectionStrings is null, and look for your configuration file that was probably not correctly copied over. When you attempt the .ConnectionString from the index accessor of the .ConfigurationManager.ConnectionStrings it returns null as you have not configured one in your web.config. Look in web.config for the connectionStrings portion.
Update
Since you have provided the web.config simply add the connectionStrings as desired:
<configuration>
<connectionStrings>
<add name="registerationConnectionString"
connectionString="Data Source=.;Initial Catalog=DBNAME;Integrated Security=True;Connect Timeout=15;" />
</connectionStrings>
<appSettings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
</system.web>
</configuration>

Error when filling DataGrid with SQL table

I am trying to populate a WPF DataGrid with a SQL Server table, but I am getting this exception when I try to start the App (and it enters Break Mode):
An unhandled exception of type 'System.TypeInitializationException'
occurred in PresentationFramework.dll
Additional information: The type initializer for
'System.Windows.Application' threw an exception.
MY CODE
App.config
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionstrings>
<add connectionstring="Data Source=*.*.*.*; User Id=**;Password=*****; Initial Catalog=Visitas;" name="ConString"/>
</connectionstrings>
MainWindow
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Fill()
{
string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
string CmdString = string.Empty;
using (SqlConnection con = new SqlConnection(ConString))
{
CmdString = "SELECT * FROM employees_ext";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("EMPLOYEES_EXT");
sda.Fill(dt);
dataGridE.ItemsSource = dt.DefaultView;
}
}
private void button_Click(object sender, RoutedEventArgs e)
{
Fill();
}
}
Pretty simple code, but already checked everything and read tons of google info, but I am still not able to solve it :\
Since the XML is case-sensitive your connectionstring spelling is incorrect. So you should note that attribute names are case-sensitive. The s in connectionString should be Uppercase:
<connectionStrings>
<add connectionString="Data Source=*.*.*.*; User Id=**;Password=*****; Initial Catalog=Visitas;" name="ConString"/>
</connectionStrings>

How can I connect C# with Db with App.config?

I need to connect C# with SQL Server database using app.config.
My code is:
public partial class Form1 : Form
{
string connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
public Form1()
{
InitializeComponent();
}
public void InsertDeleteUpdate(string query)
{
try
{
SqlConnection Conn = new SqlConnection(connectionString);
Conn.Open();
SqlCommand comm = new SqlCommand(query, Conn);
comm.ExecuteNonQuery();
Conn.Close();
MessageBox.Show("Succeeded");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
and in app.config I have:
<connectionStrings>
<add name="Test1"
providerName="System.Data.SqlClient"
connectionString="Data Source=KSPR1WS126;Initial Catalog=Test1;User ID=sa" />
</connectionStrings>
but I get an error and I can't fix it:
ConfigurationErrorExeption was Unhandled Configuration system
failed to initialize
Can anyone help me please ?
Try:
var connectionString = ConfigurationManager.ConnectionStrings["Test1"].ConnectionString;
You're referencing Conn as the connection string name but referenced it as Test1 in the App.Config
Try this..
<connectionStrings>
<add name="Conn" providerName="System.Data.SqlClient"
connectionString="Data Source=KSPR1WS126;Initial Catalog=Test1;User ID=sa" />
</connectionStrings>
Try below code and then check
string connectionString = ConfigurationManager.ConnectionStrings["Test1"].ConnectionString;

how to read the connection string from App.config file by C#

I'm using this code to read the connection string from my app.config file but it always return a null value. My App.config file is under my project. Both methods are resulting null values:
public SqlConnection getConnection()
{
try
{
// connectionString = ConfigurationManager.AppSettings["dbConn"];
connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
connectionString = System.Configuration.ConfigurationManager.AppSettings["dbConn"];
sqlConnection = new SqlConnection(connectionString);
sqlConnection = new SqlConnection(connectionString);
}
catch (Exception ex)
{
}
return sqlConnection;
}
This is my app.config file declaration:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConn" providerName="System.Data.SqlClient"
connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</connectionStrings>
</configuration>
I think your problem that you try to read connection string twice, first you do it right, and second time you do it wrong, so just remove second line:
connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
sqlConnection = new SqlConnection(connectionString);
ConfigurationManager.AppSettings used to access <appSettings>...</appSettings> section of the config.
Can you please try
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConn" providerName="System.Data.SqlClient"
connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</connectionStrings>
<appSettings>
<add key="dbConn" value="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</appSettings>
</configuration>
Then use the second method.
Make sure you select the App.Config file in the solution explorer and in the property window select Copy to Output Directory to Copy Always. Now Build the application and try again.
You simple define connection string in one class and call that string.....
public class Connection
{
/// <summary>
/// Connection String
/// </summary>
public static string ConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
}
}
}
//Returning connction string
sqlConnection conn = new SqlConnection(Connection.ConnectionString);
connectionString=global::myProject.Properties.Settings.Default.myConnectionString

Categories

Resources