Khurram Majeed Khurram Majeed - 15 days ago 4
C# Question

Connecting to Oracle using Oracle.ManagedDataAccess

I am using Oracle.ManagedDataAccess Nuget Package Version 12.1.022 in my C# (.NET 4.0) project. The package automatically creates entries in the app.config file. How can I read the datasource string from this file to be able to connect to the data base?


System.Configuration.ConfigurationManager.AppSettings.Get("dataSource");


is not working for me

<?xml version="1.0" encoding="utf-8"?>

<configuration>
<configSections>
<section name="oracle.manageddataaccess.client"
type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</configSections>
<system.data>
<DbProviderFactories>
<remove invariant="Oracle.ManagedDataAccess.Client" />
<add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client"
description="Oracle Data Provider for .NET, Managed Driver"
type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>
</system.data>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<publisherPolicy apply="no" />
<assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
<bindingRedirect oldVersion="4.121.0.0 - 4.65535.65535.65535" newVersion="4.121.2.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>

<oracle.manageddataaccess.client>
<version number="*">
<dataSources>
<dataSource alias="MyDataSource"
descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=100.100.100.100)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=myservice.com)))" />
</dataSources>
</version>
</oracle.manageddataaccess.client>
</configuration>

Answer

Typically, you would refer to the alias in a standard connection string:

  <connectionStrings>
    <add name="MyConnection" connectionString="Data Source=MyDataSource;User Id=scott;Password=tiger;"/>
  </connectionStrings>

Then you would use the standard method for retrieving the string:

ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

Also keep in mind that the data source section is optional. You can embed the descriptor directly in the connection string:

  <connectionStrings>
    <add name="MyConnection" connectionString="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=100.100.100.100)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=myservice.com)));User Id=scott;Password=tiger;"/>
  </connectionStrings>

You can also refer to aliases in a tnsnames.ora file. By default the driver looks for a tnsnames.ora in the exe folder, a directory specified in a TNS_ADMIN environment variable, or the TNS_ADMIN config variable:

http://docs.oracle.com/cd/E48297_01/doc/win.121/e41125/featConfig.htm#autoId6 http://docs.oracle.com/cd/E48297_01/doc/win.121/e41125/featConfig.htm#autoId7