I have some code that uses ODP.Net
using (OracleConnection connection = new OracleConnection(connectionString))
{
connection.Open();
boxCommand = new OracleCommand(sql, connection);
OracleDataAdapter boxAdapter = new OracleDataAdapter(boxCommand);
DataTable boxTable = new DataTable();
boxAdapter.Fill(boxTable);
}
I then get an error below on a production server. The test server is fine.
I don't understand as its complaining about a connection not being open but if there was a problem it should occur at the point my Open is called not on the Fill. Also I thought Fill was supposed to open the connection anyway.
Can anyone suggest what might be going on?
UPDATE: From the comments I tried adding this but same problem:
using (OracleConnection connection = new OracleConnection(connectionString))
{
connection.Open();
while(connection.State != ConnectionState.Open)
{
connection.Close();
connection.Open();
}
boxCommand = new OracleCommand(sql, connection);
OracleDataAdapter boxAdapter = new OracleDataAdapter(boxCommand);
DataTable boxTable = new DataTable();
boxAdapter.Fill(boxTable);
}
UPDATE 2 : I have added logging and the Validate Connection = true to the connection string and I know the connection state is open, the box command was done, the adapter created and the table created, it definitely errors on the Fill
Can you try installing the latest version of ODP.Net and see if you still have the problem? You should be able to run latest ODP.Net even against older Oracle DBs (10g in your case).
EDIT:
Since you're restricted to a specific ODP.net version, here are some other things to try:
Make sure the proper Oracle folders are at the beginning of your system path. For example, I have the Oracle folders at the beginning of my path, like this (I have ODP.net installed in c:\oracle\ora11g and I also have Oracle 10g Express Edition installed, but note that the ODP.net folders are first:
c:\oracle\ora11g\product\11.1.0\client_1;c:\oracle\ora11g\product\11.1.0\client_1\bin;C:\oracle\ora10g\bin;
I've seen situations where Oracle does weird things and won't work properly if the path isn't correct.
Try reinstalling the specific ODP.net version you are using. This should clean things up and hopefully resolve your issue.
Related
I am writing a Windows Forms application that needs to query 2 fields from a MAS-90 database. For this we use the MAS 90 32-bit ODBC Driver by ProvideX called SOTAMAS90. Here is the code I use to retrieve a DataTable from the MAS-90 database.
public static DataTable getDatatable(string qry)
{
DataTable dt = new DataTable();
using (OdbcConnection conn = new OdbcConnection(GetSQLConnection()))
{
try
{
OdbcCommand cmd = new OdbcCommand(qry, conn);
cmd.CommandType = CommandType.Text;
conn.Open();
OdbcDataAdapter adpt = new OdbcDataAdapter(cmd);
adpt.Fill(dt);
cmd.Dispose();
conn.Close();
conn.Dispose();
}
catch (OdbcException e) { conn.Close(); }
catch (AccessViolationException ae) { conn.Close(); }
catch (UnauthorizedAccessException ue) { conn.Close(); }
}
return dt;
}
On line adpt.Fill(dt) I get the following exception:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
This was working just fine yesterday. Today Visual Studio is telling me that this is an Unhandled AccessViolationException even though you can clearly see the try/catches. I had to add <legacyCorruptedStateExceptionsPolicy enabled="true"/> to my config file just for the exception to be caught in the try/catch.
The other strange thing is I am able to connect to the database and run the same exact query (which is just selecting 2 fields from a table) using the ODBC Query Tool by Jaime De Los Hoyos M. (Available here)
Any help at resolving this issue is greatly appreciated. Please let me know if you need additional information.
I also wanted to add that I have tried:
Targeting x86 in my app as the Driver is 32-bit
Giving permissions to the directory where the database is stored
Restarting PC
Changing query to add parameters with cmd.Parameters.AddWithValue("#PARAM", "Value")
I was able to resolve my issue. The database was stored on a server to which my PC had a mapped drive to. For whatever reason, the mapping broke for the MAS 90 32-bit ODBC Driver. This was strange because I was still able to access the network drive's files via File Explorer and I was also able to query the table via the ODBC query tool I mentioned (which uses the same ODBC driver). I discovered this when I wanted to change the Database Directory field (seen below) and it kept telling me the path was invalid or inaccessible (even though it was accessing it for the ODBC query tool).
Anyway, I remapped the network drive, then deleted and recreated the SOTAMAS90 DSN and it worked again.
I have an asp.net C# application (.net 4.0) connected to SQL Server 2012 using ADO.Net and am encountering an error which says:
[InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.]
I very well know what a DataReader is but, my problem is getting this error in below conditions:
I have not at all used any DataReader in my application, I have only
used DataAdapters everywhere. The code works fine while running in
local environment and there is no errors.
Application works fine even after deployment in IIS7 when used by a
single user.
The error only occurs when multiple users starts using the website hosted in IIS7.
Kindly help, I am also doubting for any problems with my hosting in IIS7
After a lot of trial and error, finally I found out that it's a problem with SqlConnections. What I used to do was open a connection at the instantiation of my DAL layer object. So, whenever two methods from the same DAL object called together, it used to throw the error.
I solved it by opening and closing a connection in every call to the database. Now it all works fine. This also allows max number of users to use the application at a time. Below is my code sample from DAL:-
DataTable dt = new DataTable();
try
{
using (SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString()))
{
if (sqlcon.State == ConnectionState.Closed)
sqlcon.Open();
SqlCommand sqlCommand = new SqlCommand
{
Connection = sqlcon,
CommandType = CommandType.StoredProcedure,
CommandText = "MyStoredProc"
};
sqlCommand.Parameters.AddWithValue("#Parameter1", Parameter1);
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlCommand))
{
adapter.Fill(dt);
}
}
return dt;
}
catch (Exception exp)
{
LogHelper.LogError(string.Concat("Exception Details: ", ExceptionFormatter.WriteExceptionDetail(exp)));
throw exp;
}
finally
{
dt.Dispose();
}
Please post a better way of doing it if you know any, thank you.
I am trying to insert an integer value into a SQL Server database as below when I run the program there are no any errors, but the table doesn't get updated with values. I have searched on the internet and I am doing the same can anyone help to find what I am doing wrong.
Note: I already defined "connectionString" as a string on the form class
private void btnUpdate_Click(object sender, EventArgs e)
{
int totalincome=600;
int totaldeductions = 10;
connectionString = ConfigurationManager.ConnectionStrings["BudgetApp.Properties.Settings.MainDataBaseConnectionString"].ConnectionString;
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand("INSERT INTO Totals(TotalIncome, TotalDeductions) VALUES (#TotalIncome, #TotalDeductions)", con);
cmd.Parameters.AddWithValue("#TotalIncome", totalincome);
cmd.Parameters.AddWithValue("#TotalDeductions", totaldeductions);
cmd.ExecuteNonQuery();
MessageBox.Show("Done !!");
}
The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MainDataBase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MainDataBase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
Code Seems correct,Perhaps you are checking the wrong DB?. I would add a Try/catch for exceptions. And remember to close connection after executing query. Regards
check your database column datatype,use try catch.
and try to replace cmd.Parameters.AddWithValue("#TotalIncome", totalincome); to cmd.Parameters.Add("#Number", SqlDbType.Int).Value = totalincome;
try
{
int totalincome=600;
int totaldeductions = 10;
connectionString = ConfigurationManager.ConnectionStrings["BudgetApp.Properties.Settings.MainDataBaseConnectionString"].ConnectionString;
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand(#"INSERT INTO Totals(TotalIncome, TotalDeductions) VALUES (#TotalIncome, #TotalDeductions)", con);
cmd.Parameters.Add("#Number", SqlDbType.Int).Value = totalincome;
cmd.Parameters.Add("#Number", SqlDbType.Int).Value = totaldeductions;
//cmd.Parameters.AddWithValue("#TotalIncome", totalincome);
//cmd.Parameters.AddWithValue("#TotalDeductions", totaldeductions);
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
I have a stored procedure that I need to run in C# and set the result set returning from the SP in a HTML table. Please note that the SP is working well in SSMS and returning results.
The c# code I am using is (it is in an ASP 4.5 project):
SQLDatabase sqldb = new SQLDatabase();
using (SqlConnection sqlcn = new SqlConnection(sqldb.GetConnectionString().ToString()))
{
if (sqlcn.State == ConnectionState.Closed)
{
sqlcn.Open();
}
SqlCommand cmd = new SqlCommand("[MyStoredProcedure]", sqlcn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FromDate", Convert.ToDateTime(txtFrom.Value.ToString()));
cmd.Parameters.AddWithValue("#ToDate", Convert.ToDateTime(txtTo.Value.ToString()));
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
a.Fill(ds);
dtExtra = ds.Tables[0];
}
}
This code above is returning 0 rows, even though the SP is working in SSMS. While debugging, the connectionstring and the parameters are coming all true, no issue. The connectionstring is:
<add name="DefaultDB" connectionString="Data Source=TestEnv;Initial Catalog=TestTable;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
I don't understand what may cause this. I found the topic below, but I am using Integrated Security=SSPI in my connection string already, so it did not help me. Any advice would be appreciated.
ASP.NET stored proc call bringing back no rows, but does in Management Studio!
EDIT: SOLVED! Thanks #NineBerry. It turned into a between/and usage problem in SP. Changing txtTo.Value as: DateTime.Today.AddDays(1).ToString("yyyy-MM-dd"); in the code fixed the issue (It was DateTime.Today.ToString("yyyy-MM-dd") before, I should have included it in the code part, didn't think it is related to that, sorry). Better solution would be updating the SP using >= and <= instead of between/and keywords tho.
I would modify your code to simply be:
using(var dbConnection = new SqlConnection("..."))
using(var command = new SqlCommand(query, dbConnection))
{
dbConnection.Open();
...
}
Handling the connection pooling in the using block is always a good idea per Microsoft guideline:
To ensure that connections are always closed, open the connection
inside of a using block, as shown in the following code fragment.
Doing so ensures that the connection is automatically closed when the
code exits the block.
You are checking if the connection is closed, what if the connection is idle? By using the using syntax you implement dispose. So it will correctly close your connection, so you should not need to check if the connection is closed unless you are using a singleton for the connection.
After reading your question, you may have more than just the one issue I pointed out. I would recommend a service account with access the specific data you are seeking, that the application can access rather than integrated security.
I have a bit of .NET code that retrieves the results from an Oracle Stored Procedure, using the ADO.NET Library, and populates the results into a DataTable like so:
using System.Data.OracleClient;
public DataTable getData()
{
OracleConnection conn = new OracleConnection("Data Source=DATASOURCE;Persist Security Info=True;User ID=userID;Password=userPass;Unicode=True;Min Pool Size=1;Max Pool Size=20;Connection Lifetime=300");
DataTable dt = new DataTable();
conn.Open();
try
{
OracleCommand oraCmd = new OracleCommand();
oraCmd.Connection = conn;
oraCmd.CommandText = "stored_procedure.function_name";
oraCmd.CommandType = CommandType.StoredProcedure;
oraCmd.Parameters.Add("cursor", OracleType.Cursor).Direction = ParameterDirection.Output;
OracleDataAdapter oraAdapter = new OracleDataAdapter(oraCmd);
oraAdapter.Fill(dt);
}
finally
{
conn.Close();
return dt;
}
}
This code has been working without any issues on several projects I have implemented the code on. However I am running into an issue on a new project, where the Oracle DB machine is actually much slower to respond, and seems to become unresponsive when too many clients begin to access the hardware. What I would like to do is implement some sort of timeout on the oraAdapter.Fill command - as it appears that when the database becomes unresponsive, the .NET application will hang on the 'Fill' method for as long as 10 minutes or more, never reaching the 'finally' codeblock and closing the DB connection.
I am in an environment where I am restricted to using the MSDN Library for connecting to the Oracle Database, so I'm hoping I can do it using the ADO.NET Control.
The CommandTimeout property does not work using the System.Data.OracleClient .NET 3.5 Provider. It appears that this functionality is not supported without the use of an external library.
It seems you need the CommandTimeout property, not ConnectionTimeout.