Exception message, filling a datatable with SqlDataAdapter - c#

I run a simple query to SQL and can't seem to get it working correctly.
DataTable loDTDOffre = new DataTable();
SqlCommand loSQLCommand = new SqlCommand("dbo.SP_StoredProc", loConnectionBD.ConnectionSql);
loSQLCommand.CommandType = CommandType.StoredProcedure;
loSQLCommand.Parameters.Add("#liNoUnit", SqlDbType.Int);
loSQLCommand.Parameters["#liNoUnit"].Value = noUniteProduction;
SqlDataAdapter loSqlDataAdapter = new SqlDataAdapter(loSQLCommand);
loSqlDataAdapter.SelectCommand = loSQLCommand;
loSqlDataAdapter.Fill(loDTDOffre);
My database connection is open, the stored proc executed in SQL Management Studio works fine. All I get as error message in VS2010 is :
Warning: Fatal error 50000 occurred at May 30 2013 11:17AM. Note the error and time, and contact your system administrator.
Process ID 59 has raised user error 50000, severity 20. SQL Server is terminating this process.
Is there any way to get a clearer message of what is wrong, the code seems right. The error message is so general, I can't figure out what I do wrong.
My stored procedure returns a simple select, one row.
Thanks

Turns out it runs on an approle, this came out :
The SELECT permission was denied on the object 'thisTable', database 'thisDatabase', schema 'dbo'.
Fixed, thank you.

Related

How do I run a SQL Server job programatically in C#? [duplicate]

This question already has answers here:
How to invoke the job in SQL Server agent from windows application
(6 answers)
Closed 6 years ago.
Inside SQL Server Management Studio there are more than just databases listed in the Object Explorer. Under SQL Server Agent, we have "Jobs". One of these jobs that we have updates the client to match the cache. This is important because of how our cache system works. If we make a change to the database, it is not reflected if we run this job.
So, in the C# code, there are times when I make a change to a database table that I need to run this job afterwards. It is easy to do in SQL Server Management Studio. I just right click on the job and click on "Start Job at Step..." but how would I do the same thing in C#?
The problem I have been having is not answered in what might be a duplicate post. The command line is "execute msdb.dbo.sp_start_job #job_name='Update Client Matching Cache'" and, while I have permissions to run this command from the SQL line (thus showing I have permissions), I cannot run it from the code. Passing the job name, "update client matching cache" to this procedure fails to run:
public static void RunStoredProcedure(string strSQLJob)
{
SqlCommand ExecJob = new SqlCommand();
ExecJob.CommandType = CommandType.StoredProcedure;
ExecJob.CommandText = "msdb.dbo.sp_start_job";
ExecJob.Parameters.AddWithValue("#job_name", strSQLJob);
using (SqlConnection sc = DatabaseManager.SqlConnection())
{
sc.Open();
using (ExecJob)
{
ExecJob.Connection = sc;
ExecJob.ExecuteNonQuery();
}
}
}
The error is: An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: The EXECUTE permission was denied on the object 'sp_start_job', database 'msdb', schema 'dbo'.
I also get the same error if I open Visual Studio in admin mode.
You need to use Microsoft.SqlServer.Management.Smo.Agent namespace..In this namespace you have job class which has INVOKEmethod.Here is some sample code from MSDN..
Server srv = new Server("(local)");
Job jb = new Job(srv.JobServer, "Test Job");
jb.Create();
JobStep jbstp = new JobStep(jb, "Test Job Step");
jbstp.OnSuccessAction = StepCompletionAction.QuitWithSuccess;
jbstp.OnFailAction = StepCompletionAction.QuitWithFailure;
jbstp.Create();
jb.ApplyToTargetServer(srv);
jb.IsEnabled = true;
jb.Invoke();
You can create a new job and a new "Task" table.
The new job would be checking the status of the "Task" table every 5 minutes or so. If there is a new row in that table with a status, for example: "pending", then, this job will start the target job, and will change the status to "in progress".
Finally, the last job can include a step to change the status again to "success" or "failure" when it's finished.
Using the answer in a similar question almost works apart from a privilege error being thrown How to invoke the job in SQL Server agent from windows application

Error on Inserting to Ms Access Database (Unspecified Error \r\n Object invalid or no longer set)

I want to insert about 2000 records every time a button is clicked.
It works fine until record 511, and throw this exception:
Unspecified Error \r\n Object invalid or no longer set
I've debugged it several times with different records or different order and always get the same error on 511th record.
What's happening?
CODE:
(I read the ID of the last record, before i insert another one)
string CmdText = "SELECT TOP 1 Id FROM MyTable ORDER BY Id DESC";
OleDbCommand com = new OleDbCommand(CmdText,tran.Connection,tran);
com.CommandType = CommandType.Text;
OleDbDataReader reader = com.ExecuteReader(); //exception started here
It sounds like somehow the Jet engine is
not working properly or is corrupted.
When opening and closing connections or recordsets using the Microsoft ODBC Driver for Access or the Microsoft OLE DB Provider for Jet, the following error may be reported:
Object invalid or no longer set.
To resolve this problem, install the latest Microsoft Jet 4.0 service pack 6. For additional information FIX: "Object invalid or no longer set" Error with Microsoft Jet
I've figured it out guys.
I have to close OleDBDataReader every time i want to insert new record.
Now it works fine. Thanks.
The best way to resolve this problem is to delete that table in which its giving error in inserting / updating. and then re-create the table, but be sure, to backup the table data first.

"table or view does not exist", but only sometimes

A SQL select statement gets run when a user presses a button on my website, and I do this:
connection = new OleDbConnection();
connection.ConnectionString = [connection string];
connection.Open();
cmd = profile.Execute(mySQLStatement);
da = new OleDbDataAdapter(cmd);
table = new DataTable();
da.Fill(table);
90% of the time, this works just fine. But every once in a while, I get the OleDbException table or view does not exist on the line da.Fill(table). There doesn't seem to be a pattern of when this works and when it doesn't, though it's more likely to not work when the site isn't used for a minute or two... Like the session might be expiring. But the rest of the website (that does not require this database) works.
Any ideas of what might be happening or how to fix it?
I have not found a solution. As a temporary fix, whenever this happens, I just re-start the page.
Sometimes the content of mySqlStatement is not exactly correct, maybe?
Trap the exception dump mySqlStatement to a logfile (with date and time this happened), and then throw.

Database.ExecuteNonQuery does not return

I have a very odd issue. When I execute a specific database stored procedure from C# using SqlCommand.ExecuteNonQuery, my stored procedure is never executed.
Furthermore, SQL Profiler does not register the command at all. I do not receive a command timeout, and no exeception is thrown.
The weirdest thing is that this code has worked fine over 1,200,000 times, but for this one particular file I am inserting into the database, it just hangs forever.
When I kill the application, I receive this error in the event log of the database server: "A fatal error occurued while reading the input stream from the network. The session will be terminated (input error: 64, output error: 0). Which makes me think that the database server is receiving the command, though SQL Profiler says otherwise.
I know that the appropiate permissions are set, and that the connection string is right as this piece of code and stored procedure works fine with other files.
Below is the code that calls the stored procedure, it may be important to note that the file I am trying to insert is 33.5MB, but I have added more than 10,000 files larger than 500MB, so I do not think the size is the issue:
using (SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["TheDatabase"].ConnectionString))
using (SqlCommand command = sqlconn.CreateCommand())
{
command.CommandText = "Add_File";
command.CommandType = CommandType.StoredProcedure;
command.CommandTimeout = 30 //should timeout in 30 seconds, but doesn't...
command.Parameters.AddWithValue("#ID", ID).SqlDbType = SqlDbType.BigInt;
command.Parameters.AddWithValue("#BinaryData", byteArr).SqlDbType = SqlDbType.VarBinary;
command.Parameters.AddWithValue("#FileName", fileName).SqlDbType = SqlDbType.VarChar;
sqlconn.Open();
command.ExecuteNonQuery();
}
There is no firewall between the server making the call and the database server, and the windows firewalls have been disabled to troubleshoot this issue.
I've seen this once before when uploading XML via a stored proc from one workstation only
We changed the network cable (which routed differently in our big building) and it worked.
Bizarre as this sounds, can you somehow re-mount the server or change cables or bypass a switch etc.

Always get exception when trying to Fill data to DataTable

The code below is just a test to connect to an Oracle database and fill data to a DataTable. After executing the statement da.Fill(dt);, I always get the exception
"Exception of type 'System.OutOfMemoryException' was thrown."
Has anyone met this kind of error? My project is running on VS 2005, and my Oracle database version is 11g. My computer is using Windows Vista. If I copy this code to run on Windows XP, it works fine.
Thank you.
using System.Data;
using Oracle.DataAccess.Client;
...
string cnString = "data source=net_service_name; user id=username; password=xxx;";
OracleDataAdapter da = new OracleDataAdapter("select 1 from dual", cnString);
try
{
DataTable dt = new DataTable();
da.Fill(dt); // Got error here
Console.Write(dt.Rows.Count.ToString());
}
catch (Exception e)
{
Console.Write(e.Message); // Exception of type 'System.OutOfMemoryException' was thrown.
}
Update
I have no idea what happens to my computer. I just reinstall Oracle 11g, and then my code works normally.
How big is your dual table? This query:
select 1 from dual
Will return a single-column table with as many rows as the dual table, with 1 in every row. If the table has millions of rows then it wouldn't surprise me if it threw an out of memory exception.
Edit Of course, this doesn't explain why it would work on XP but not on Vista, unless it's something implementation-specific (querying a different instance of the database on the two different workstations, for example).
Edit 2:
Ok, so presumably there is only one row in dual since your comment indicates that the query only returns a single row.
A couple of things to investigate:
The Oracle ADO.NET connection requires the Oracle client software, right? Is the Oracle software on your Vista box the same version as on the XP box? Perhaps there's a discrepancy there.
Instead of showing e.Message, try showing e.ToString() to get a full stack trace - it might give you more insight as to where the error is being thrown from.

Categories

Resources