Connect to Oracle APEX database in C# - c#

I have a database called "sistema" using application apex express, I am trying to connect with this code:
private void button1_Click(object sender, EventArgs e)
{
string constr = "Data Source=sistema;User Id=admin;Password=123;";
string ProviderName = "Oracle.ManagedDataAccess.Client";
using (OracleConnection conn = new OracleConnection(constr))
{
try
{
conn.ConnectionString = constr;
conn.Open();
//Get all the schema collections and write to an XML file.
//The XML file name is Oracle.ManagedDataAccess.Client_Schema.xml
DataTable dtSchema = conn.GetSchema();
dtSchema.WriteXml(ProviderName + "_Schema.xml");
MessageBox.Show("YEAH");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
MessageBox.Show(ex.StackTrace);
}
}
}
This code shows me this error:
ORA-12154: TNS could not resolve the specified connection identified
With this new code:
private void button1_Click(object sender, EventArgs e)
{
string constr = #"Data Source=(DESCRIPTION=
(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost )(PORT=1521)))
(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=SISTEMA)));
User Id=ADMIN ;Password=123";
string ProviderName = "Oracle.ManagedDataAccess.Client";
using (OracleConnection conn = new OracleConnection(constr))
{
try
{
conn.ConnectionString = constr;
conn.Open();
//Get all the schema collections and write to an XML file.
//The XML file name is Oracle.ManagedDataAccess.Client_Schema.xml
DataTable dtSchema = conn.GetSchema();
dtSchema.WriteXml(ProviderName + "_Schema.xml");
MessageBox.Show("YEAH");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
MessageBox.Show(ex.StackTrace);
}
}
}
It returns me
User id 'is an invalid connection string attribute
When I try to connect to the database from VS I get this error:
The listener does not currently know the requested service
The database works correctly on Oracle Apex http://localhost:8080/apex and has tables and records created
Also try with uppercase and lowercase names and nothing changes
I do not understand how to connect to my Oracle Apex database in application express, it is confusing, I do not know what to change with respect to normal databases in oracle.
How can I connect to my apex database in c# ?

Problem is your not putting the tns identifier at the right place. If you had added the oracle manage data access package from nuget there will be an added configuration line on your app config/web config.
<oracle.manageddataaccess.client>
<version number="*">
<dataSources>
<dataSource alias="SampleDataSource"
descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))
(CONNECT_DATA=(SERVICE_NAME=ORCL))) " />
</dataSources>
</version>
</oracle.manageddataaccess.client>
Edi the alias to "sistema" and put your tns connection identifier on the descriptor. like this
<dataSource alias="sistema"
descriptor="(DESCRIPTION=
(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost )(PORT=1521)))
(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=SISTEMA))) " />
</dataSources>
and use your fist attempt connection string. That will resolve TNS identification error.

OracleConnection cannot resolve the alias. According documentation there are several possibilities to resolve the name in following order:
data source alias in the dataSources section under <oracle.manageddataaccess.client> section in the .NET config file (i.e. machine.config, web.config, user.config).
-> this was already provided by yonas in previous answer
data source alias in the tnsnames.ora file at the location specified by TNS_ADMIN in the .NET config file. Locations can consist of either absolute or relative directory paths.
data source alias in the tnsnames.ora file present in the same directory as the .exe.
Actually the documentation is not fully correct, or let's say "not thorough". Item 2 and 3 applies only if you use local tnsnames.ora file. However, in file sqlnet.ora you may specify different NAMES.DIRECTORY_PATH, e.g. LDAP or EZCONNECT.
So, actually it should be like this
data source alias in the tnsnames.ora file resp. naming method as defined in sqlnet.ora file at the location specified by TNS_ADMIN in the .NET config file. Locations can consist of either absolute or relative directory paths.
data source alias in the tnsnames.ora file resp. naming method as defined in sqlnet.ora file present in the same directory as the .exe.

Related

Entity Framework 6 connection string questions

I have a C# ASP.NET MVC code first project that works as intended to connect to my database. It has the connection string set in the web.config file and all seems to work great.
<connectionStrings>
<add name="HorstMFGContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|HorstMFG.mdf;Initial Catalog=aspnet-HorstMFG;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Now I need to connect to the same database from a different application that needs to be a WinForms based class library. I don't have access to the source code of the program that uses my dll because my application is just a plug-in for Autodesk Vault.
There are numerous examples such as this one that show how to set the connection string in the application that calls the dll, but that obviously won't work in my case.
This link here seems to very close to what I need, but I haven't been able to get it to work. Here is my version of the 'Create' function.
public static HorstMFGEntities Create(string nameOrConnectionString)
{
var entityBuilder = new EntityConnectionStringBuilder();
// use your ADO.NET connection string
entityBuilder.ProviderConnectionString = nameOrConnectionString;
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/HorstMFG.ssdl|res://*/HorstMFG.msl";
return new HorstMFGEntities(entityBuilder.ConnectionString);
}
Here is the line that calls the function:
using (var db = HorstMFGEntities.Create(#"data source=(localdb)\MSSQLLocalDB;attachdbfilename=C:\Users\lorne\source\repos\HorstMFG\HorstMFG\App_Data\HorstMFG.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"))
{
foreach (string l in lineList3)
{
....
....
Here is the actual line that throws the exception.
// calculate material
Material mat = db.Materials.Where(m => m.StructuralCode == l.Split('\t')[6]).FirstOrDefault();
The exception message "Error: Keyword not supported: 'metadata'.
Any help to point me in the right direction is appreciated. Thanks.
I updated my code as per the first comment, and also added the 'provider' that I had missed as well.
public static HorstMFGEntities Create(string nameOrConnectionString)
{
var entityBuilder = new EntityConnectionStringBuilder();
// use your ADO.NET connection string
entityBuilder.ProviderConnectionString = nameOrConnectionString;
entityBuilder.Provider = "System.Data.SqlClient";
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/HorstMFG.csdl|res://*/HorstMFG.ssdl|res://*/HorstMFG.msl";
return new HorstMFGEntities(entityBuilder.ConnectionString);
}
Now I get the error "Error: Unable to load the specified resource."
I now followed the instructions in the link you provided. I think I must be getting close, but I'm a little foggy on the metadata format yet. There seems to be a portion commented out in the example. I replaced it with this:
entityBuilder.Metadata = "res://*/HorstMFG.csdl|res://*/HorstMFG.ssdl|res://*/HorstMFG.msl";
Now I get the error: "Unable to load the specified metadata resource"
I confirmed that the files I am referencing do exist, they are in the ...\obj\Debug\edmxResourcesToEmbed\ folder in my project. I also changed the 'build action' for the 'HorstMFG.edmx' object from 'None' to 'Embedded Resource'. That didn't help anything.

Backup localDB database in ClickOnce

I've created a WPF 4.5 .NET application it with a database backup feature. The functions and the backup works fine when debugging but when I publish it in ClickOnce and install it in target machine everything works except the backup won't work because ClickOnce obfuscate the app folder location so it becomes too long for the backup statement to work! Is there a way to make the backup statement shorter? here's my code and the error I get:
code:
SaveFileDialog sfd = new SaveFileDialog();
string stringCon = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\whdb.mdf;Integrated Security=True";
string dbPath = Application.StartupPath + #"\whdb.mdf";
if (sfd.ShowDialog() == DialogResult.OK)
{
using (SqlConnection conn = new SqlConnection(stringCon))
{
string backupStmt = string.Format(#"backup database #whdb to disk='{0}' WITH INIT ", sfd.FileName);
using (SqlCommand sqlComm = new SqlCommand(backupStmt, conn))
{
sqlComm.Parameters.AddWithValue("#whdb", dbPath);
conn.Open();
sqlComm.ExecuteNonQuery();
conn.Close();
}
}
)
************** Exception Text **************
System.Data.SqlClient.SqlException (0x80131904): Invalid database name 'C:\Users\Abubaker\AppData\Local\Apps\2.0\52WR4JTO.12O\D6M4D7OQ.Z3D\sa3a..tion_fef19ab42c2b8f22_0001.0000_9fc10c82bbf23ed2\whdb.mdf' specified for backup or restore operation.
BACKUP DATABASE is terminating abnormally.
The whdb.mdf database file is create by another existing application? And your WPF application is only for Backup the existing whdb.mdf database?
I also struggled for days for this kind of situation. I tried |Data Directory| and Application.StartupPath and some other approaches as you've found as well.
However, I finally chose this way and successfully launched(published) my service.
According to my experience, |Data Directory| indicates different places depending on circumstances, in other word, it's not always same..
And I could read (SQL Select command) database with |Data Directory| setting in connectionString but couldn't insert or update the database. You can find some people are having this difficulties by searching on interent. I think when we set |Data Directory| in connectionString, the database plays a role as read-only data file like the nuance of |Data Directory|.
Instead the |Data Directory|, I chose more obvious path which indicates always same place(directory).
#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + Environment.GetEnvironmentVariable("APPDATA") + #"\whdb.mdf;Integrated Security=True";
Above Environmental variable indicates always C:\Users\Abubaker\AppData\Roaming directory.
For this scenario, you're needed to create the whdb.mdf database file with above path first.
And further, you may create your own additional directory like mybackup with the connectionString as,
#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + Environment.GetEnvironmentVariable("APPDATA") + #"\mybackup" + #"\whdb.mdf;Integrated Security=True";
I couldn't find the official document from Microsoft how the |Data Directory| works but failed. Understanding |Data Directory| would be your key, otherwise, there's alternative way like my case.
My case is also WPF, ClickOnce, SQL Database (it was localDB but I changed to normal SQL Database because of remote networking)
Solved the problem by adding Initial catalog=whdb in the connection string and then replace the full path Application.StartupPath + #"\whdb.mdf" with just the database name "whdb"!

What is the command to connect to a database(MS Access) saved anywhere on the PC without specifying the full path name

public void DatabaseConnection()
{
connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source =..\\..\\TaxApp.accdb;Persist Security Info=False");
connection.Open();
}
If you're in a language that allows you to construct the path, such as C#:
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
will, by default, give you the path to c:\ProgramData folder, which is shared among all users.
So:
string AccessDbPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"YourAppFolder\\TaxApp.accdb");
Usually you don't store fixed paths in your code. This will make your application very difficult to install on your customers PCs.
Knowing this, the NET framework provides an infrastructure to store this kind of informations in external XML based file (named yourexename.exe.config when you release the application and simply app.config inside your project).
You can store there this kind of information that need to be changed on a customer by customer base.
So you app.config could have a section made in this way
<appSettings>
<add key="DatabasePath" value="C:\programdata\MyApp\Database.accdb" />
</appSettings>
Inside your program you could read and use this value using this code
string dbFile = ConfigurationManager.AppSettings["DatabasePath"].ToString();
connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data source =" + dbFile +
";Persist Security Info=False");
You could even store the whole connection string using the project properties menu and adding a new entry of type ConnectionString in the Settings page.
Again, what you type there will be stored in the app.config file in a specific section
<connectionStrings>
<add name="MyDb" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;
Data source=C:\programdata\MyApp\Database.accdb;
Persist Security Info=False";/>
</connectionStrings>
and you can read it with
string myConnectionString = ConfigurationManager.ConnectionStrings["MyDb"].ConnectionString;
See ConfigurationManager class on MSDN

C# ODBC ConnectionString

I was currently create a ODBC Connection to the remote server of the web-hosting.
The Access File is at the ftp home directory.
When running in this code , at the m_connection.Open();
var m_result = new DataTable();
try
{
using (OdbcConnection m_connection = new OdbcConnection(connectionDBString))
{
string sql = "SELECT * FROM product";
m_connection.Open();
OdbcDataAdapter dataadapter = new OdbcDataAdapter(sql, m_connection);
dataadapter.Fill(m_result);
m_connection.Dispose();
m_connection.Close();
}
}
catch (Exception e)
{
}
return m_result;
The following exception fails
ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not
found and no default driver specified
Is there anyway to claim the dataSource for the ODBC Connection ?
In the cPanel, I only set the DSN and the Path as follows:
DSN : wealthhonesthk-website
Path : e:\virtualhost\domains\wealthhonesthk\home\website.mdb
The below is my part of the web.config
<connectionStrings>
<add
name="ODBCDataConnectionString"
connectionString="DSN=wealthhonesthk-website;Driver={Microsoft Access Driver (*.mdb)};FILEDSN=ftp:/210.245.166.72/home/website.mdb;Dbq=ftp:/210.245.166.72/home/website.mdb;Uid=;Pwd=; curly=false;"
providerName="System.Data.Odbc"
/>
</connectionStrings>
You tend to use a DSN when you don't define a connection string in a config file (like in old VB6 days). Since you're using a config file, you really don't need a DSN. Why not use a connection string like:
Driver={Microsoft Access Driver (*.mdb)};Dbq=ftp://210.245.166.72/home/website.mdb;Uid=Admin;Pwd=;?
Also, having your MDB file mapped to a FTP location may be a problem; why not map a network drive to that location? This way, your connection string might look like:
Driver={Microsoft Access Driver (*.mdb)};Dbq=X:\myNetworkLocation\website.mdb;Uid=Admin;Pwd=;
Lastly, why are you defining a FILEDSN and a Dbq parameter for your connection string?
In short, I'd recommend getting rid of the DSN part of your connection string and use a non-ftp location for your MDB file.
Here is all the information you need on connection strings:
http://www.connectionstrings.com/access
http://www.connectionstrings.com/access-2007
Have a look at following
http://www.connectionstrings.com/
Should help you.
As you are trying to connect to Oracle Database, you might need to have Oracle Client installed.

How to connect published Visual C# solution to a different database

So here's the what's up. I just created and "published" a staff management tool in Visual C#. During development, I used a string saved in Properties.Settings.Default to connect to the database I was using for development. Now since the solution is published and ready to go, the boss wants to connect to the real staff database. I was under the impression that connection to the new database would be as simple as changing the connection string in some properties file somewhere. Unfortunately I can't seem to find the proper file/string to connect to the database I want to. Any ideas?
Thanks!
JB
Look here:
Connection Strings and Configuration Files
By using a config file you just have to change the config file connection string once your application has been deployed.
Here's a way of doing what you want:
From http://www.dreamincode.net/forums/topic/70745-connection-string-in-appconfig/
Your config file content:
<connectionStrings >
<add name="YourName"
connectionString="Provider=msdaora;Data Source=MyOracleDB;Persist Security Info=False;Integrated Security=Yes;"
providerName="System.Data.OracleClient" />
</connectionStrings>
Method to get the connection string at runtime:
public static string GetConnectionString(string strConnection)
{
//Declare a string to hold the connection string
string sReturn = new string("");
//Check to see if they provided a connection string name
if (!string.IsNullOrEmpty(strConnection))
{
//Retrieve the connection string fromt he app.config
sReturn = ConfigurationManager.ConnectionStrings(strConnection).ConnectionString;
}
else
{
//Since they didnt provide the name of the connection string
//just grab the default on from app.config
sReturn = ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString;
}
//Return the connection string to the calling method
return sReturn;
}
Using the method:
string connectionString = GetConnectionString("YourName");
I've had to change the entry in the Properties.Settings text file, recompile and redeploy to get the new connectionstring to take. In the future consider reading your connection string from your .config file under either the ConnectionStrings or AppSettings node. When you store it there you simply need to change a production text file to switch your database...

Categories

Resources