In .Net is there a class in .Net where you can get the DB name, and all the connection string info without acutally doing a substring on the connection string?
EDIT:
I am not creating a connection I am attempting to get info out of the connection string. So I am basicly looking for something that takes a connection string arg and has accessors to dbName, connection type, etc....
You can use the provider-specific ConnectionStringBuilder class (within the appropriate namespace), or System.Data.Common.DbConnectionStringBuilder to abstract the connection string object if you need to. You'd need to know the provider-specific keywords used to designate the information you're looking for, but for a SQL Server example you could do either of these two things:
Given
string connectionString = "Data Source = .\\SQLEXPRESS;Database=Northwind;Integrated Security=True;";
You could do...
System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();
builder.ConnectionString = connectionString;
string server = builder["Data Source"] as string;
string database = builder["Database"] as string;
Or
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder.ConnectionString = connectionString;
string server = builder.DataSource;
string database = builder.InitialCatalog;
After you initialize the connection with the connection string, you can get those information from properties of the initialized connection object.
Check System.Data.Common.DbConnection.
ConnectionInfo connectionInfo = new ConnectionInfo ();
connectionInfo = logOnInfo.ConnectionInfo;
connectionInfo.DatabaseName = database;
connectionInfo.ServerName = server;
connectionInfo.Password = password;
connectionInfo.UserID = user;
EDIT: Looks like Nathan beat me to it, as mine is from the same page.
EDIT AGAIN: I should note that ConnectionInfo is in the CrystalDecisions.Shared namespace. As for how to get it from a generic DB connection, I'm not sure.
Yep ConnectionInfo
http://msdn.microsoft.com/en-us/library/ms226340(VS.80).aspx
EDIT: I, along with Chris, realized that this is only works if you have the Crystal Reports namespaces imported. Otherwise I'm not sure
if you build your connection string using the Connection string builder (e.g. OracleConnectionStringBuilde, and it will be different for different database), in that case easily retrieve the information out of it.
here it explained:
http://msdn.microsoft.com/en-us/library/ms254947.aspx
SqlConnection sq = new SqlConnection(ConnectionString);
Reference
Done with "using" statement (from MSDN)
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Do work here; connection closed on following line.
}
Related
I have two questions regarding connecting to an Oracle database using C#.NET.
My program references Oracle.DataAccess.dll (version 2.122.19.1) in my Oracle 19c client 64-bit folder.
I have a using statement:
using Oracle.DataAccess.Client;
and this code to connect:
string connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=myserver.sys.mycompany.com)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=mydb.mycompany.com)));User Id=MyLanId;Password=MyPasswors;Validate Connection=True;"
using (OracleConnection connection = new OracleConnection(connectionString))
{
connection.Open();
}
Question #1:
How do I create an OID connection string that does not specify the DB name but instead queries the LDAP for the detail server/port info that is hardcoded in my TNS-less connection string above?
For example, in a Java program, we connect like this.
base.oracle.db.url=jdbc:oracle:thin:#ldap://oid.gtm.internal.mycompany.com:3060/dbname,cn=OracleContext,dc=mycompany,dc=com
What would the .NET equivalent be?
Question Number #2:
When I compile my C# program I selected "Any CPU" yet my program only works when I reference the 64-bit Oracle.DataAccess.dll. Is this because my PATh variable mentions my 64-bit oracle client folder before my 32-bit folder (I have both)? Right now, my PATH variable is way over the max length of 2048 and I cannot change it without making it shorter and I'm not sure what to delete.
I found this SO post,
How do I query LDAP from C# to resolve Oracle TNS hostname while using managed ODP.NET?
Instead of just passing in a connection string that points to an LDAP server, I can do an LDAP query to get the db descriptor to build the connection string.
It's a 2 step process, so I probably want to cache the connection string once I build it. I normally count on connection pooling and "close" connections when I am done with them but this two step process seems like I have to manually add some caching of the connection string to avoid the overhead of hitting LDAP multiple times.
Is there a better way?
string directoryServer = "oid.gtm.internal.mycompany.com:3060";
string defaultAdminContext = "cn=OracleContext,dc=mycompany,dc=com";
string serviceName = "mydb";
string userId = "mylanid";
string password = "mypwd";
using (IDbConnection connection = GetConnection(directoryServer, defaultAdminContext, serviceName, userId, password))
{
connection.Open();
connection.Close();
}
private static IDbConnection GetConnection(string directoryServer, string defaultAdminContext,
string serviceName, string userId, string password)
{
string descriptor = ConnectionDescriptor(directoryServer, defaultAdminContext, serviceName);
// Connect to Oracle
string connectionString = $"user id={userId};password={password};data source={descriptor}";
OracleConnection con = new OracleConnection(connectionString);
return con;
}
private static string ConnectionDescriptor(string directoryServer, string defaultAdminContext,
string serviceName)
{
string ldapAdress = $"LDAP://{directoryServer}/{defaultAdminContext}";
string query = $"(&(objectclass=orclNetService)(cn={serviceName}))";
string orclnetdescstring = "orclnetdescstring";
DirectoryEntry directoryEntry = new DirectoryEntry(ldapAdress, null, null, AuthenticationTypes.Anonymous);
DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry, query, new[] { orclnetdescstring },
SearchScope.Subtree);
SearchResult searchResult = directorySearcher.FindOne();
byte[] value = searchResult.Properties[orclnetdescstring][0] as byte[];
if (value != null)
{
string descriptor = Encoding.Default.GetString(value);
return descriptor;
}
throw new Exception("Error querying LDAP");
}
I'm trying to connect to a database, but it seems like my connection is not going through. I am using C# MVC for the webpage I'm creating. How can I fix the following error:
System.ArgumentException: 'Keyword not supported: 'metadata'.'.
The error is occuring on the line using (Sqlconnection con = new Sqlconnection(conStr)). What am I doing wrong on this line and is this how you call your SQL query in C# MVC?
string conStr = ConfigurationManager.ConnectionStrings["Training_DatabaseEntities"].ConnectionString;
List<FisYear> YerFis = new List<FisYear>();
using (SqlConnection con = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand("select * from [dbo].[FiscalYear]", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
FisYear fy = new FisYear();
fy.FisDate = rdr["ST_FI"].ToString();
YerFis.Add(fy);
}
SelectList list = new SelectList(YerFis, "ST_FI", "FisDate");
ViewBag.DropdownList = list;
}
You're almost certainly trying to use an entity framework connection string to open a connection via new SqlConnection, which won't work.
If you look in your web.config file you'll probably see something similar to:
<connectionStrings>
<add name="Training_DatabaseEntities" connectionString="metadata=res://*/Entity.csdl|res://*.............provider=System.Data.SqlClient;provider connection string=............." />
</connectionStrings>
You could try parsing the connection string by hand to retrieve the bit you actually want, a brief web search suggests that the EntityConnectionStringBuilder may be of use to retrieve it programmatically, here's an example of doing that in a console app:
var connectionString = ConfigurationManager.ConnectionStrings["Training_DatabaseEntities"]
.ConnectionString;
var entityConnectionStringBuilder = new EntityConnectionStringBuilder(connectionString);
var sqlConnectionConnectionString = entityConnectionStringBuilder.ProviderConnectionString;
Console.WriteLine($"EF Connection String: {connectionString}");
Console.WriteLine($"SqlConnection Connection String: {sqlConnectionConnectionString}");
This gives the output (my emphasis):
EF Connection String: metadata=res:///Models.Model1.csdl|res:///Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=cntrra02-sql-rs;initial catalog=Training_Database;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
SqlConnection Connection String: data source=cntrra02-sql-rs;initial catalog=Training_Database;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework
Which shows a connection string that can be passed into a SqlConnection instance.
What I want to do is have text boxes for the user to input the required fields for the connection to the MySQL table, Here is the code I currently have.
public partial class Form1 : Form
{
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = serverTextBox.Text;
conn_string.UserID = userTextBox.Text;
conn_string.Password = passwordtextBox.Text;
conn_string.Database = dataBaseTextBox.Text;
using (MySqlConnection mcon = new MySqlConnection(conn_String.ToString()));
MySqlCommand mcd;
MySqlDataAdapter mda;
//-----open connection-----//
public void openCon()
{
if (mcon.State == ConnectionState.Closed)
{
mcon.Open();
}
}
//-----close connection-----//
public void closeCon()
{
if (mcon.State == ConnectionState.Open)
{
mcon.Close();
}
}
}
I really have no idea how to setup a MySQL connection properly and this was my (failed) best guess.
here is a new picture that might help http://prntscr.com/bgubj5
There should be a lot of reasons of Your problem. You posted only small piece of code, which is not enaught. If You want to connect do database consider following steps:
-make proper connection string (it depends on the database)
-connection string can be make from user inputs, but must be known before calling MySqlConnection
so, firstly save the user inputs to variable, make connectionstring of them, and finally pass it to MySqlConnection constructor
PS. this would help with making connectionstring: https://www.connectionstrings.com/
What exceptions does it throw?
Build the connection string first. Set a breakpoint and check if it looks good.
Or an even better approach will be to use the MySqlConnectionStringBuilder object
your code will look like this:
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = serverTextBox.Text;
conn_string.UserID = userTextBox.Text;
conn_string.Password = passwordtextBox.Text;
conn_string.Database = dataBaseTextBox.Text;
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{
//query whatever you want, be aware of SQL injection
}
I am using the following code to connect to sql throgh windows authentication.
string connctionstring = "connectionString={0};Database={1};Integrated Security=SSPI;";
string _connctionstring = string.Format(connctionstring, datasource, initialCatalogue);
SqlConnection _connection = new SqlConnection(_connctionstring);
_connection.Open();
But i am getting the following error. Help please.I am able to login through sql server.
The connection string format is not correct
Change to this:
string connctionstring = "Data Source={0};Database={1};Integrated Security=SSPI;";
Or
string connctionstring = "Server={0};Database={1};Integrated Security=SSPI;";
While Peyman's answer does cover the basic issue (connectionString is not a valid key for the string) a better solution is to use a SqlConnectionStringBuilder, this will also help you do proper escaping if you have odd characters in your string (for example if your database name contained a space)
var scsb = new SqlConnectionStringBuilder();
scsb.DataSource = datasource;
scsb.InitialCatalog = initialCatalogue;
scsb.IntegratedSecurity = true;
//You also really should wrap your connections in using statements too.
using(SqlConnection connection = new SqlConnection(scsb.ConnectionString))
{
connection.Open();
//...
}
I'd like to supply the connection string for my database at runtime. I am using the Entity Framework. This is what I have so far
class MyClassDBContext:DbContext
{
public MyClassDBContext(string str) : base(str)
{
this.Database.Connection.ConnectionString = str;
}
}
To use the above code, I tried
//create connection string
EntityConnectionStringBuilder myConn = new EntityConnectionStringBuilder();
myConn.Provider = "System.Data.SqlClient";
myConn.ProviderConnectionString = "user id=xxxx;password=xxxx;server=localhost;database=xxxx;connection timeout=30";
//inject the connection string at runtime
MyClassDBContext a = new MyClassDBContext(myConn.ToString())
The above code gave me an error saying "Provider keyword not supported".
To attempt to debug this error, I tried the following
MyClassDBContext a = new MyClassDBContext("metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=user id=xxxx;password=xxxx;server=localhost;database=xxxx;connection timeout=30")
Now, I got an error saying "metadata keyword not supported". So I changed my code to
MyClassDBContext a = new MyClassDBContext("provider=System.Data.SqlClient;provider connection string=user id=xxxx;password=xxxx;server=localhost;database=xxxx;connection timeout=30")
Now I got an error saying "provider keyword not supported". So I again changed my code to
MyClassDBContext a = new MyClassDBContext("user id=xxxx;password=xxxx;server=localhost;database=xxxx;connection timeout=30")
and now it works!. My question is : how do I specify the provider and metadata at runtime? It looks like only the connection string is being accepted. I am using Entity 4.3.1 from Nuget.
Thanks
edmx file based EF require the "Provider" and "Metadata" content. Code-first based EF doesn't require this, requiring only the regular connection string. You could use a SqlConnectionStringBuilder (instead of EntityConnectionStringBuilder) to build this normal connection string if you'd like. But as you've seen, you need only specify the actual connection details. The Provider and Metadata aren't needed in EF 4.3.1's DbContext Code-first paradigm.
Building on HatSoft's answer:
var entityConnectionStringBuilder= new EntityConnectionStringBuilder();
entityConnectionStringBuilder.Provider = "System.Data.SqlClient";
entityConnectionStringBuilder.ProviderConnectionString = <your SQL Server connection string>;
entityConnectionStringBuilder.Metadata = "res://*";
MyClassDBContext a = new MyClassDBContext(entityConnectionStringBuilder.ToString());
The EntityConnectionStringBuilder class can be used to to specify provider and metadata at runtime
e.g.
var entityConnectionStringBuilder= new
EntityConnectionStringBuilder();
entityConnectionStringBuilder.Provider = "System.Data.SqlClient";
entityConnectionStringBuilder.Metadata =
"res:///Example.csdl|res:///Example.ssdl|res://*/Example.msl";
Please see for more on CSDL, SSDL & MSDL in Metadata
I followed this link
and also this one
How to use EF Code-First without an app.conf file?
Basically what I do is almost like you, create a constructor with a string and calling the base.
But I also set the provider in this constructor.
here's a example
public Context(string ConnectionString) : base(ConnectionString) {
Database.DefaultConnectionFactory = new SqlCeConnectionFactory("Oracle.DataAccess.Client");
}
That way you can specify the provider. And you won't get the provider keyword error since you don't need to specify in the connection string
Here's how I call it.
var dbCont = new ClassLibrary1.Models.Context("DATA SOURCE=xxx;PASSWORD=xxx;USER ID=xxx");
Hope that helps took me long time to find it
It's old question but maybe it will be useful for someone
var provider = (DbProviderFactory)System.Data.Entity.DbConfiguration
.DependencyResolver
.GetService(typeof(DbProviderFactory), "invariant provider name");
var conn = provider.CreateConnection();
//conn.ConnectionString = "sample connection string";
DbInterception.Dispatch.Connection.SetConnectionString(conn, new DbConnectionPropertyInterceptionContext<string>()
.WithValue("sample connection string"));
return new SampleDbContext(conn,true);