how do i connect to oracle with the info i have? - asp.net

i have the info below from the oracle DBA and want to connect to oracle from a .net application. i just got done installing the oracle tools/ drivers for windows/ .net and now want to get a console app to connect tot he oracle DB and extract data from oracle into SQL server.
another solution would be to have SQL server pull from oracle all the records in the bugs table. i have no clue what the oracle connection string is and have tried to create a system DSN but failed at that prior to turning to the SO gurus...
ORACLE SQL user name is ‘USER_dev’,
password is ‘welcome’.
Connection string is
‘jdbc:mercury:oracle://qct-ds2-p.apps.com:1139;sid=QCTRP1’

i got lucky and found a simple solution that is all in .net and requires nothing more than this syntax by way of a connection string. all the .ora stuff is presented in the connection string and works well.
static void getData()
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
//Console.WriteLine("State: {0}", connection.State);
//Console.WriteLine("ConnectionString: {0}", connection.ConnectionString);
OracleCommand command = connection.CreateCommand();
string sql = "SELECT * FROM BUG";
//string sql = "SELECT table_name FROM user_tables";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//string myField = (string)reader["Project"];
string myField = (string)reader[0];
Console.WriteLine(myField);
}
}
}
static private string GetConnectionString()
{
return "User Id=USER_dev;Password=welcome;Data Source=(DESCRIPTION=" +
"(ADDRESS=(PROTOCOL=TCP)(HOST=111.123.479.24)(PORT=1139))" +
"(CONNECT_DATA=(SID=QCTRP1)));";
}

go into your ORACLE_HOME\network\admin directory. Create a file called tnsnames.ora if it is not there already. Add this into it:
QCTRP1.WORLD =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = qct-ds2-p.apps.com)(PORT = 1139))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = QCTRP1)
)
)
I'm making some assumptions here...
does qct-ds2-p.apps.com resolve?
looks like the DBA set it up the listener on port 1139... default is normally 1521 so you'll need to confirm.
You can then set up a connection string as follows:
Connection conn = DriverManager.getConnection
("jdbc:oracle:oci8:#QCTRP1.WORLD", "dev", "welcome");

now that you have the tnsnames created from #erbsock, you will need to get the .net side of
things working. Oracle has several tutorials available to help you in this matter.
When you install the Oracle ODP (in the link you will see samples as well as the downloads) drivers you will get a directory created in the
%oracle_home%\odp.net\samples\4\DataSet\DSPopulate\src
(this appears to be the same example as located # http://www.oracle.com/technology/sample_code/tech/windows/odpnet/DSPopulate/ViewProducts.cs.html)
as an initial test I would recommend just changing around the id/passwrd/sql/etc and trying it out.
it is not that fundamentally different than using System.Data; but there are a few gotchas and remember that each computer will need to have ODP/Oracle client installed to have them work with the ora connection.
if you have any problems post the exact error msg that is displayed as well as a snippet of your .net code that establishes the connection, does the query, and where it is breaking

Related

Passing datatable to SQL Server stored procedure not working

I have an ASP.NET application that passes a Datatable to a web service, then from the web service to a SQL Server stored procedure. When I publish the web application and web service to the server and run, it fails. When I run the application from the local host pointing to the web service on the server, it works fine. When I run the both the web application and web service from localhost, it works fine.
I did some troubleshooting and see that the following line is the problem but I am not sure how to solve:
cmdCommit.Parameters.AddWithValue(#SourceTable, dtSource);
When I comment the line above, everything works. When I replace the reference to the DataTable (dtSource) in the line above with a string datatype, it works.
Here is the entire web method, I am using this code within a try/catch block:
DataTable dtSource = ObjectToData(sourceTable);
dtSource.TableName = TableTypeObject;
using (SqlConnection cnn = new SqlConnection(_cnnSqlCapss))
{
SqlCommand cmdCommitChange = new SqlCommand("usp_Stored_Procedure", cnn);
cmdCommitChange.CommandType = CommandType.StoredProcedure;
cmdCommitChange.Parameters.AddWithValue("#Parm1", Value1);
cmdCommitChange.Parameters.AddWithValue("#Parm2", Value2);
cmdCommitChange.Parameters.AddWithValue("#Parm3", dtSource);
var returnParameter = cmdCommitChange .Parameters.Add("#ReturnVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
cnn.Open();
cmdCommitChange .ExecuteNonQuery();
var result = returnParameter.Value;
return (int)result;
}
The confusing part is that when I run the web application from the localhost and reference the web service on the server, it works. I don't understand why it fails when I run the web application from the server.
When I comment the line that reference the DataTable everything works.
I have tried the following and still no success:
SqlParameter tvpParam cmdCommit.Parameters.AddWithValue "#SourceTable", dtSource);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.SourceTableType";
Also, The web method is not throwing an exception.
Assumed you're already doing these:
Defining table type in User-Defined Table Types in your database (often known as TVP, see reference section below);
Adding parameter to pass DataTable to stored procedure (e.g. #SourceTable).
Then, you can use SqlDbType.Structured to pass DataTable contents as stored procedure parameter like this:
cmdCommitChange.Parameters.Add("#SourceTable", SqlDbType.Structured).Value = dtSource;
Alternative with AddWithValue:
cmdCommitChange.Parameters.AddWithValue("#SourceTable", dtSource).SqlDbType = SqlDbType.Structured;
Example usage in SqlConnection block:
using (SqlConnection cnn = new SqlConnection(_cnnSqlCapss))
{
SqlCommand cmdCommitChange = new SqlCommand("usp_Stored_Procedure", cnn);
cmdCommitChange.CommandType = CommandType.StoredProcedure;
cmdCommitChange.Parameters.AddWithValue("#Parm1", Value1);
cmdCommitChange.Parameters.AddWithValue("#Parm2", Value2);
cmdCommitChange.Parameters.AddWithValue("#Parm3", Value3);
// add this line
cmdCommitChange.Parameters.Add("#SourceTable", SqlDbType.Structured).Value = dtSource;
cmdCommitChange.Parameters.Add("#ReturnVal", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cnn.Open();
cmdCommitChange.ExecuteNonQuery();
var result = (int)returnParameter.Value;
return result;
}
Reference:
Table-Valued Parameters (MS Docs)
I found the problem. I am passing a text value that is too large for a column on my datatable.
The web service was indeed throwing an exception but there was some code in my application's routine which was preventing me from seeing it.

AX 2012 ODBC Connection Without Active Directory user

I am having problem trying to connect to an external database with Microsoft Dynamics AX.
I have configured the dsn, and i can connect with sql server authentication (not active directory, because is in another server), and when i test, it just works.
But when i try to use the dsn in x++ i am sending the correct user and password to the loginProperty, but always return error, it try to do with the active directory user.
This is my code:
LoginProperty loginProperty;
OdbcConnection odbcConnection;
Statement statement;
ResultSet resultSet;
str sql, criteria;
SqlStatementExecutePermission perm;
TLExternalUser tlExternaUser;
TLExternalUserPwd tlExternalUserPwd;
str strConnectionString;
str dsn = "myDsnName";
str dsnUser = "sqlUser";
str dsnUSerPwd = "sqlPWD";
strConnectionString = strfmt("UID=%1;PWD=%2",dsnUser,dsnUSerPwd);
loginProperty = new LoginProperty();
loginProperty.setDSN(dsn);
loginProperty.setDatabase("MyDatabase");
loginProperty.setOther(strConnectionString);
odbcConnection = new OdbcConnection(loginProperty);
if (odbcConnection)
{
info("success");
}
else
{
throw error("Failed to log on to the database through ODBC.");
}
But i am getting this error:
[Microsoft][SQL Server Native Client 10.0][SQL Server]Login failed for user 'DOMAIN\ACTIVEDIRECTORYUSER'.
I was looging to pass directly to my loginProperty the username and password, but such methods does not exist.
How can i make it works?
Try changing it to this and removing loginProperty.setDSN(...):
strConnectionString = strfmt("DSN=%1;UID=%2;PWD=%3",dsn, dsnUser,dsnUSerPwd);
loginProperty = new LoginProperty();
loginProperty.setDatabase("MyDatabase");
loginProperty.setOther(strConnectionString);
Edit If your password has special characters in it, you will need to either escape them with a backslash \ or place an # symbol before the quotes to indicate a string literal, like this str myPass = #'MyP#ssw0rd';.
See here https://msdn.microsoft.com/en-us/library/aa889472.aspx
I can not make it works with dsn, so i use server, in this way:
LoginProperty loginProperty;
OdbcConnection odbcConnection;
Statement statement;
ResultSet resultSet;
str sql ;
SqlStatementExecutePermission perm;
TLExternalUser tlExternaUser;
TLExternalUserPwd tlExternalUserPwd;
str strConnectionString;
str dbServer = 'myipServer';
str serverDbUser = 'myUser';
str serverDbUserPwd = 'MyPassword';
strConnectionString = strfmt("UID=%1;PWD=%2",serverDbUser,serverDbUserPwd);
loginProperty = new LoginProperty();
loginProperty.setServer(dbServer);
loginProperty.setDatabase("MyDatabase");
loginProperty.setOther(strConnectionString);
odbcConnection = new OdbcConnection(loginProperty);
I do not understand why with dsn does not work

How to set database with AdomdConnection

When I execute this code:
AdomdConnection con = new AdomdConnection("Data Source=MyServer;User ID=MyDomain\\MyUserName;Password=MyPassword");
con.Open();
con.ChangeDatabase("Analysis Services Project1");
I get this exception:
Either the user, MyDomain\MyUserName$, does not have access to the
Analysis Services Project1 database, or the database does not exist.
The database name comes from looking at the server using Microsoft SQL Server Management Studio. If I bring up the properties on the server and go to the security section, my account is listed as a Server administrator. While in management studio, I can see data sources, cubes and execute mdx queries fine.
Why can't do I get this exception in code?
whihc line causes the error?
I imagine you have to infor the catalog on your connection string. Try addind
Catalog=Analysis Services Project1
to your con string.
Also, Analysis Services Project1 seems to be the projects name? Are you sure this is the database name as well?
First
added the reference for Microsoft.AnalysisServices.AdomdClient.dll
strCon = "Data Source=DBserverServerName;Integrated Security=SSPI;Initial Catalog=DBName;";
AdomdConnection con = new AdomdConnection("connectionstring"); // connect DB con.Open(); AdomdCommand cmd = new AdomdCommand("MDX query", con); //query
AdomdDataReader reader = cmd.ExecuteReader(); //Execute query
while (reader.Read()) // read
{
Data dt = new Data(); // custom class
dt.Gender = reader[0].ToString();
dt.Eid = reader[1].ToString();
dt.salary = reader[2].ToString();
data.Add(dt);
}

ASP.NET application opening WAY too many SQL connections

I have an issue on a codebit with an ASP.NET Webforms 4 application.
I am using SQL server 2008 R2, IIS 7, the website is running on Windows Server 2008 R2 in separate Application pool (integrated mode, .NET4, with support for 32bit assemblies).
The following code is posing problems:
Dim sqlCmd = New SqlClient.SqlCommand
With sqlCmd
Using sqlConnectionToUse As SqlClient.SqlConnection = GetActiveConnexion(pstrConnectString), _
vAdaptor As New SqlClient.SqlDataAdapter
.Connection = sqlConnectionToUse
.CommandText = pstrSQL 'function parameter
vAdaptor.SelectCommand = sqlCmd
'query1: SELECT somecolumn FROM table WHERE somecolumn '' ==> opens a new connection in SQL Server
'query2: SELECT someothercolumn FROM anothertable WHERE someothercolumn 23 ==> uses my WebSite process active connection
vAdaptor.Fill(vDataSet)
End Using
End With
UPDATE: the GetActiveConnexion() method simply does the following code in my case:
Return New SqlClient.SqlConnection("my connection string obtained from the web.config file")
When I run the query2, everything goes smoothly, the ASP.NET application uses the openned connection of the application pool and I get my results in the dataset.
However, whenever I run the query1, a NEW connection is openned in SQL server (I can see it show up in the SSMS's Activity Monitor) and this one remains openned. The problem is that If I run this query1 100 times, I reach the connection pool's limit and very bad things happens. I still gets the results in the dataset, can use them etc...
The new connection is created on the call of vAdaptator.Fill().
Any idea on what's wrong ?
Thanks a lot for your time.
(PS: sorry for the bad english).
Here is the code in C# for those who prefer:
object sqlCmd = new SqlClient.SqlCommand();
using (SqlClient.SqlConnection sqlConnectionToUse = GetActiveConnexion(pstrConnectString)) {
using (SqlClient.SqlDataAdapter vAdaptor = new SqlClient.SqlDataAdapter()) {
sqlCmd.Connection = sqlConnectionToUse;
sqlCmd.CommandText = pstrSQL; //function parameter
vAdaptor.SelectCommand = sqlCmd;
//query1: SELECT F10_ID FROM FIN_MONTANT_TT_F10 WHERE F10_ID_TT_F19 = '' ==> opens a new connection in SQL Server
//query2: SELECT A48_ID FROM ADH_EPARTICIPANT_ADMIN_A48 WHERE A48_ID=23 ==> uses my WebSite process active connection
vAdaptor.Fill(vDataSet);
}
}
Your SqlCommand instance should be wrapped in a using block as it's Disposable. It's probably the source of your problems.
using (SqlClient.SqlConnection sqlConnectionToUse = GetActiveConnexion(pstrConnectString))
{
using (SqlCommand sqlCmd = sqlConnectionToUse.CreateCommand())
{
using (SqlClient.SqlDataAdapter vAdaptor = new SqlClient.SqlDataAdapter())
{
...
}
}
}
Or VB
Using sqlConnectionToUse As SqlClient.SqlConnection = GetActiveConnexion(pstrConnectString)
Using sqlCmd As SqlCommand = sqlConnectionToUse.CreateCommand()
Using vAdaptor As New SqlClient.SqlDataAdapter()
...
End Using
End Using
End Using

using a connection string in web.config for crystal report

I`m having problems between two servers, wich use differente odbc dsn.
My apps work great but crystal reports uses the original odbc connection, how can I fix this?
I'm thinking of using the same connection string in the web.config, but I don't know how.
found this but is too confusing for me
thanks,
You can't use a connection string in the same way you can with an ado.net connection. However, you can certainly use values from the web.config to specify the connection info. Create an instance of the ConnectionInfo class and set the ServerName, DatabaseName, UserID, and Password properties. Then attach it to each of the tables in the report:
ConnectionInfo reportConnectionInfo = new ConnectionInfo();
reportConnectionInfo.ServerName = ConfigurationManager.AppSetting["ServerName"];
reportConnectionInfo.DatabaseName = ...;
reportConnectionInfo.UserID = ...;
reportConnectionInfo.Password = ...;
foreach (Table table in reportDocument.Database.Tables) {
table.LogOnInfo.ConnectionInfo = reportConnectionInfo;
}
If you try to use this suggestion, beware of my sloppy typing...
You can use the connection string.
You have to create an instance of the database provider ConnectionStringBuilder passing in the Connection String pulled from a config file. Here is an example in VB.
Dim connString As String = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString
Dim connStringBuilder As SqlConnectionStringBuilder = New SqlConnectionStringBuilder(connString)
Dim myConnectionInfo As ConnectionInfo = New ConnectionInfo()
myConnectionInfo.DatabaseName = connectionStringBuilder.InitialCatalog
myConnectionInfo.UserID = connectionStringBuilder.UserID
myConnectionInfo.Password = connectionStringBuilder.Password
myConnectionInfo.ServerName = connectionStringBuilder.DataSource

Resources