Use and call the connection string in the forms/ c# - c#

I'm building desktop application using c# , I put the connection string in the app.config file like this
<connectionStrings>
<add name="ComputerManagement"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0; Data Source=...;Initial Catalog=Computersh;Integrated Security=True"/>
</connectionStrings>
How I can call the connection string in the forms ?

You can get the connection string with ConfigurationManager:
using System.Configuration;
var connection = ConfigurationManager.ConnectionStrings["ComputerManagement"];
But you'll still need to use something to connect to the database with it, such as SqlConnection: http://msdn.microsoft.com/en-gb/library/system.data.sqlclient.sqlconnection.aspx
using System.Configuration;
using System.Data.SqlClient;
var connection = ConfigurationManager.ConnectionStrings["ComputerManagement"];
if (connection != null)
{
using (var sqlcon = new SqlConnection(connection.ConnectionString))
{
...
}
}

Reference System.Configuration and use
System.Configuration.ConfigurationManager
.ConnectionStrings["ComputerManagement"].ConnectionString

Like this:
var constring = ConfigurationManager.ConnectionStrings["ComputerManagement"].ConnectionString;
Also you have to add this using System.Configuration; :)

Using the ConfigurationManager should suffice:
var connection = ConfigurationManager.ConnectionStrings["ComputerManagement"];
Then, check for null, before accessing the actual string:
if (connection != null) {
var connectionString = connection.ConnectionString;
}

Related

trying to connect web API's to oracle db

trying to connect web API to oracle DB.
I have successfully connected with SQL server but I have no idea about oracle DB.what I have done is=> created a controller and write a get and post API method in it. and on the web.config I have added connectionStrings. I am attaching my SQL connection code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace API2.Controllers
{
public class IndexController : ApiController
{
[HttpGet]
[Route("getUsers")]
public HttpResponseMessage Get_Users()
{
DataTable dt = new DataTable();
string str_Msg = string.Empty;
string Query = string.Empty;
string consString = ConfigurationManager.ConnectionStrings["xyz"].ConnectionString;
Query = "SELECT * from xyz";
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlCommand _SqlCommand = new SqlCommand(Query, con))
{
_SqlCommand.CommandType = CommandType.Text;
using (SqlDataAdapter _adapater = new SqlDataAdapter(_SqlCommand))
{
_adapater.Fill(dt);
}
Query = string.Empty;
}
}
return Request.CreateResponse(HttpStatusCode.OK, dt, Configuration.Formatters.JsonFormatter);
}
}
<connectionStrings>
<add name="xyz" connectionString="Data Source= xyz; Integrated Security=false;Initial Catalog= xyz; uid=xyz; Password=xyz;" providerName="System.Data.SqlClient" />
</connectionStrings>
I have no idea how to do the same connectivity with oracle DB. please help me with this.
thank you so much.
Referring to this
Your connection string will look like
Data Source=MyOracleDB;User Id=myUsername;Password=myPassword;Integrated Security=no;

Null reference exception in asp .net

we are working on a project in which we need to show places on google map. For places, we are providing latitude and longitude from database. we are facing null reference exception error in the following place:
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.
ConnectionStrings["Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True"].ConnectionString))
How to resolve this error please guide me.
Cause of Exception:-
When you say:
System.Configuration.ConfigurationManager.
ConnectionStrings["Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True"]
Since there is no connection string with name Data Source=KhUSHAL.., thus ConnectionStrings will return null and on that you are trying to access ConnectionString property which will result in Null reference exception. Read about this error here.
Basically you are mixing both, either do this:-
string CS ="Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;Integrated Security=True";
using (SqlConnection con = new SqlConnection(CS))
{
//Your code
}
Or fetch it from Web.Config(Preferred way):-
First define the connection in Web.Config:
<connectionStrings>
<add name="Test" connectionString="Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Then read it like this:-
using (SqlConnection con = new SqlConnection(System.Configuration
.ConfigurationManager.ConnectionStrings["Test"].ConnectionString))
{
//Your code
}
Do you have the ConnectionString in the Web.Config of the UI project?
Fix:
Copy that ConnectionString and Paste in your Web.Config
Your code,
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.
ConnectionStrings["Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True"].ConnectionString))
is Invalid, this is not the way to declare connection string and access them.
How can we declare Connection Strings and can Access them??
No1:>In a Page
string strConnectionString="server=localhost;database=myDb;uid=myUser;password=myPass;;
Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnectionString))
{
}
No2.>Web.Config you can declare then under configuration and appSeting
And Can Access Like:
using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings("myConnectionString")))
{
}
No3>Web.Config you can declare then under configuration and connectionStrings
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
And Can Access Like:
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString))
{
}

Unable to determine the provider name for connection of type 'Oracle.DataAccess.Client.OracleConnection'

I'm trying to pass existing connection to DbContext, but I get this error:
Unable to determine the provider name for connection of type
Oracle.DataAccess.Client.OracleConnection
What am I doing wrong here?
var oracleConnectionString = ConfigurationManager.ConnectionStrings["OracleConnectionString"].ConnectionString;
var transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = IsolationLevel.ReadCommitted;
using (var scope = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
{
using (var conn = new OracleConnection(oracleConnectionString))
{
conn.Open();
using (var context = new MainDbContext(conn, false))
{
var cmd = #" some sql commandd here ...";
context.Database.ExecuteSqlCommand(cmd);
context.SaveChanges();
}
}
scope.Complete();
}
Connection string:
<add name="OracleConnectionString" connectionString="Data Source=SERVER;Persist Security Info=True;User ID=USER;Password=PASS" />
When you have your edmx file in a different class project, to say your web project, you also need to have the same connection string in the web project.
so...
Class Project:
edmx file
App.Config (connection string for edmx file)
Web Project
Web.Config (same connection string as above.)
Also, take a look here Problems switching .NET project from unmanaged to managed ODP.NET assemblies in case you're missing some Oracle
assemblies.
If using Database First, looks like you can't create new DbContext from Oracle connection string, because EF doesn't know, where to look for metadata. You need to use EF connection, instead of Oracle connection. This is what solved it for me:
var efConnectionString = ConfigurationManager.ConnectionStrings["MainDbContext"].ConnectionString;
using (var conn = new EntityConnection(efConnectionString))
{
conn.Open();
using (var context = new MainDbContext(conn, false))
{
}
}

C# Sql Connection String

I'm a 17 year old software engineering student and am having trouble with linking my sql database to my C# Win App. I was able to accomplish this task using a access database but the database needs to be in SQL. Any Help would be greatly appreciated!
The code i have so far is :
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb; // all Non-SqlServer Databases ie oracle, access, sqlLite
using System.Configuration;
namespace SqlWinApp
{
public partial class Form1 : Form
{
// Declare and init data objects
// Connect to an external data source
//OleDbConnection cnDataCon =
// new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=H:/SEWD/ASP/dataTestJr/App_Data/dbWaxStax.accdb");
SqlConnection cnDataCon =
new SqlConnection(ConfigurationManager.ConnectionStrings["cnExternalData"].ConnectionString);
// dataset: Container object for data tables
DataSet dsData = new DataSet();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
cnDataCon.Open();
{
loadDdlTitles();
}
}
catch (Exception errDesc)
{
string strMsgError = "Error encountered on open: " + errDesc.Message.ToString().Replace('\'', ' ');
MessageBox.Show(#"<script language='javascript'>alert('" + strMsgError + "')</script>");
MessageBox.Show(#"<script language='javascript'>alert('Application will terminate')</script>");
return;
}
}
private void loadDdlTitles()
{
//Response.Write(#"<script language='javascript'>alert('loadDDlTitles')</script>");
// store sql into a string in order to be utilized at a later time.
string strSqlTitles = "SELECT * FROM tblTitles ORDER BY title";
// data adapters act as data filters
OleDbDataAdapter daTitles = new OleDbDataAdapter();
// command syncs the data source with the filter (data sdapter) and readies it for instantiation
OleDbCommand cmNameTitles = new OleDbCommand(strSqlTitles, cnDataCon);
// select command syncs the filter with the data
daTitles.SelectCommand = cmNameTitles;
try
{
daTitles.Fill(dsData, "tblTitlesInternal"); // blow pt.
}
catch (Exception errDesc)
{
string strMsgError = "Error encountered in data adapter object: " + errDesc.Message.ToString().Replace('\'', ' ');
MessageBox.Show(#"<script language='javascript'>alert('" + strMsgError + "')</script>");
MessageBox.Show(#"<script language='javascript'>alert('Application will terminate')</script>");
}
// Connect control obj to datasource and populate
ddlTitle.DataSource = dsData.Tables["tblTitlesInternal"];
ddlTitle.DisplayMember = "nameTitle";
ddlTitle.ValueMember = "nameTitlesID";
}
}
}
In my App.config i have:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="cnExternalData" connectionString="Data Source=|DataDirectory|215-6576.All-Purpose Handyman.dbo; Provider=Microsoft.ACE.OLEDB.12.0" />
<add name="SqlWinApp.Properties.Settings.ConnectionString" connectionString="Data Source=215-6576;User ID=sa"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Finally, My database is named 215-6576.All-PurposeHandyman.dbo and the table i am using is named tblTitles. Any help again would be greatly appreciated! Thank you!
An invaluable website I've gone to repeatedly is ConnectionStrings.com.
Assuming everything you already have is correct, you just need to modify your SQL connection string in the config file:
<add name="SqlWinApp.Properties.Settings.ConnectionString" connectionString="Server=215-6576;User ID=sa; Database=All-PurposeHandyman; Password=password"
providerName="System.Data.SqlClient" />
If your sa account has a password, you will need to provide that as well via "Password=[Password]" in that same connectionString attribute.
EDIT
In your C# code, you don't need the braces around your call to loadDdlTitles();, you can safely remove those.
EDIT2
Added password attribute into modified connection string to make clear how it should work.
Well, I see 3 problems just off the bat (and there might be more if I looked more closely). The two that are causing you trouble are:
You're still calling your Access connection string
Your SQL connection string is formatted incorrectly.
The third problem isn't major, but it'll be annoying when you go to fix #1: your connection string name is really long.
Modify your sql connection string thusly:
<add name = "SqlConnection" connectionString="[yourConnectionStringHere]" />
Then modify your calling code:
SqlConnection cnDataCon =
new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString);
For the specific connection string, I recommend heading to http://connectionstrings.com and taking a look. But it will be something like this:
Server=myServerAddress;Database=myDataBase;User Id=myUsername; Password=myPassword;
You need to have the server/machine name in the connection string. This link has some information and examples to use:
http://msdn.microsoft.com/en-us/library/jj653752%28v=vs.110%29.aspx

How To Work With SQL Database Added As Item In Visual Studio 2008?

If I'm letting Visual Studio take care of adding an SQL Server database to an existing project, it adds the connection string to app.config. How can I use use THAT connection string to make my own connections and datasets?
Use the ConfigurationManager.AppSettings to read the connection string when required.
For example, if you opening a SQL Connection, use the assign the "Connection String" property to the value retrieved from ConfigurationManager.AppSettings ("MyConnectionString")
If it is placed in the appropriate section in the app config file, then you can use ConfigurationManager.ConnectionStrings to retrieve it as well.
Read more here http://msdn.microsoft.com/en-us/library/ms254494.aspx
Place the connection string in your app.config then use
ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
to get the connection string.
For example:
private string GetConnectionString(string str)
{
//variable to hold our return value
string conn = string.Empty;
//check if a value was provided
if (!string.IsNullOrEmpty(str))
{
//name provided so search for that connection
conn = ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
}
else
//name not provided, get the 'default' connection
{
conn = ConfigurationManager.ConnectionStrings[ConnStr].ConnectionString;
}
//return the value
return conn;
}
Then you can reference the connection using ado.net or Linq
For Example:
your app.config would contain an entry like:
<connectionStrings>
<add name="nameofConnString" connectionString="Data Source=SQLDATA;Initial Catalog="nameofdatabase";Persist Security Info=True;User ID=username;Password=password;Connection Timeout=30;Pooling=True; Max Pool Size=200" providerName="System.Data.SqlClient"/>
'
Then you could call
conStr = GetConnectionString("nameofConnString")
With Ado.net
You could then establish the connection with:
sqlConn = new SqlConnection(conStr);
sqlConn.Open();
Or with Linq
LinqData ld = new LinqData();
DataContext dataContext = new DataContext(ld.GetConnectionString(sqlConn));
where LinqData is a class that contains the GetConnectionString() method.
Well, both of those helped get me on the right track. I found this quite simple, yet highly annoying. The solution I used was:
using System.Configuration;
add a reference System.configuration
create a new connection with SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabaseConnectionFromApp.Config"].ConnectionString)

Categories