Running SP using exec in ado.net [duplicate] - asp.net

Is there any benefit to explicitly using the StoredProcedure CommandType as opposed to just using a Text Command? In other words, is
cmd = new SqlCommand("EXEC StoredProc(#p1, #p2)");
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#p1", 1);
cmd.Parameters.Add("#p2", 2);
any worse than
cmd = new SqlCommand("StoredProc");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", 1);
cmd.Parameters.Add("#p2", 2);
EDIT: Fixed bad copy paste job (again). Also, the whole point of the question is for a data access class. I'd much rather be able to pass the stored proc name and parameters in one line as opposed to extra lines for each parameter.

One difference is how message pumping happens.
Where I used to work we had a number of batch processes that ran over night. Many of them simply involved running a stored procedure. We used to schedule these using sql server jobs, but moved away from it to instead call the procedures from a .Net program. This allowed us to keep all our scheduled tasks in one place, even the ones that had nothing to do with Sql Server.
It also allowed us to build better logging functionality into the .Net program that calls the procedures, so that the logging from all of the overnight processes was consistent. The stored procedures would use the sql print and raiserror functions, and the .Net program will receive and log those. What we learned was that CommandType.StoredProcedure would always buffer these messages into batches of about 50. The .Net code wouldn't see any log events until the procedure finished or flushed the buffer, no matter what options you set on the connection or what you did in your sql. CommandType.Text fixed this for us.
As a side issue, I'd use explicit types with your query parameters. Letting .Net try to infer your parameter types can cause issues in some situations.

It's cleaner.
You're calling a stored procedure, why not just use the CommandType.StoredProcedure?

Related

Execute OdbcConnection within a TransactionScope but avoid automatic enlistment

I'm trying to use the InterSystems Caché ODBC driver to do a simple SELECT, but get the following error:
OdbcException: ERROR [HYC00] [Cache ODBC][State : HYC00][Native Code Driver not capable
I am assuming, based on conversations with colleagues and the otherwise simplicity of the requirement and environment, that this is because the OdbcConnection is automatically enlisting in the ambient TransactionScope, which isn't supported.
The result of this SQL is fundamental to the coninuation of the TransactionScope, which occurs over a SqlConnection, so I need to have this nested nature within the security afforded by a TransactionScope.
Is there a way I can have the ODBC code, which is fundamental to the TransactionScope execute within the context of the code, but outside the TransactionScope`?
It's been a week or so with no responses so one has to assume it isn't possible. (This itself represents knowledge and a place in the StackOverflow corpus).
I've worked around it by disabling transactions for this particular workload.

oracle ExecuteNonQuery freezes on ASP.Net

I am trying to run a non query using a Oracle connection in ASP C# with CLR 4.5. Here is my code:
string connectionString = ConfigurationManager.ConnectionStrings["OracleConnectionString1"].ConnectionString;
OracleConnection conn = new OracleConnection(connectionString);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "update SALES_ADVENTUREWORKS2012.SALESORDERDETAIL set UNITPRICEDISCOUNT=0 where ROWGUID='4A399178-C0A0-447E-9973-6AB903B4AECD'";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = QUERY_TIMEOUT;
int row_affected = cmd.ExecuteNonQuery();
HttpContext.Current.Response.Write("Rows affected:" + row_affected + "<br/>");
conn.Close();
when I run the query in oracle development tool, it works fine.
when I use the asp code above, it freezes when performing the query. It freezes forever even though I used a 5 second timeout.
I've tried using the managed and unmanaged oracle libraries; both behave the same.
Note that using the fill or scalar query work perfectly fine so there is nothing wrong with my connection string. Also the fact that oracle development can perform this update query proves that this is not a permission problem.
Any ideas?
Most likely your query is waiting to get access to the record. You probably have modified that row in "oracle development tool" and have not committed or rolled back that transaction.
Just commit/rollback in your tool or close open session.
You can check for open transactions in v$transaction view.
More on automatic locks in Oracle:
http://docs.oracle.com/cd/E11882_01/server.112/e41084/ap_locks001.htm
Are you certain you are using the 4.5 library? The 3.5 documentation states that the CommandTimeout property has no effect.
The 4.5 documentation suggests it should work, but the Remarks section doesn't mention the change, which warrants suspicion.
Otherwise, the code you posted doesn't seem to show where you actually set the value of QUERY_TIMEOUT to 5 seconds. If QUERY_TIMEOUT has a value of zero, then any other provider (SQLCommand, for example) would wait indefinitely. As vav suggested, locks from other sources could cause an indefinite wait.

How to access SQL Server from my WCF web service?

VS Express 2012, SQL Server Express 2012, Win 8.1
Hello,
I have a (very) simple WCF hosted as a web service on IIS. I also have a SQL Server instance (with 1 table) installed on the same machine.
I need a step-by-step guide on how to connect to SQL from the WCF (VB) and retrieve a single record from the table (ie: "SELECT LAST NAME FROM MYTABLE WHERE PK = 1;"). That's it. I don't need a 1,200 page manual -- which is all Google keeps throwing at me.
Anyone know of a quick, clean resource?
Thanks,
Jason
The main classes that are involved are SqlConnection and SqlCommand. The documentation of the classes contains some samples on how to use them. To get you started, here is a small sample:
Dim connStr = "Data Source=SQLServerName\InstanceName;Initial Catalog=DatabaseName;Integrated Security=SSPI"
Using conn As New SqlConnection(connStr)
conn.Open()
Using cmd = conn.CreateCommand()
cmd.CommandText = "SELECT LAST_NAME FROM MYTABLE WHERE PK = #pk"
cmd.Parameters.AddWithValue("#pk", 1)
Dim result = cmd.ExecuteScalar()
If Typeof result Is DbNull Then
' Handle null value
Else
' Otherwise
End If
End Using
End Using
This sample assumes that you want to retrieve a single cell as in your statement. If you want to retrieve tabular data, have a look a the SqlDataReader or SqlDataAdapter class.
Please note that - especially in server applications - it is important to dispose of the created instances properly.
There is no difference on using ADO.NET in a WCF service or in a normal application from the point of view of the classes required.
The first thing needed is a connection string that allows your SqlConnection object to find the host and the database that you want to use. Here examples on connection strings
Then you usually need a SqlCommand that encapsulates the SQL text and parameters needed to retrieve the data (Here you setup your SELECT statement and conditions)
Finally you need a SqlDataReader that get the result of the command execution and allows you to loop over the results.
Here a sample that could get you started.
Keep in mind that this is just a minimal todo-list and there are numerous other ways to work with data. Basic objects like SqlDataAdapter, Dataset, DataTable present different ways to load data from a database and use that data. Then on top of these there are technologies like Linq To Sql and Object Relational Mapper tools that abstract the data access and offer high level functionality on top of data.
That's probably the reason you get so much informations on data access technologies

SqlServer Timeout in ASP.NET

I have a SP which takes 20 seconds in SqlServer environment but sometimes in my ASP.NET page when I run the SP I get SqlServer timeout excaption.
I event set CommandTimeout and ConnectionTimeout to 60 but I still get the exception.
I would appreciate to help me.
Some other operation might be locking the table. set the timeout to a higher value and check.
while running the proc execute sp_lock and sp_who2 system procedure for any locking
You can try
cmd.CommandTimeout = 0;
if you are executing a query taking long time.
1) tried something like??
SqlCommand cmd = new SqlCommand("MyReport", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 3660; //// or set it zero (0)
2) and this???
3) Assuming your db server and point of execution are different, is your internet/intranet connectivity fine?
4) check for vpn connection (if used)
Execute the query from the SSMS and save the execution plan. Then run the application and have the SQL Profiler to capture the trace and then save the execution plan from profiler as mentioned in this link.
Compare the two execution plan to find out the actual difference in execution.
Check for parameter sniffing. If you still have the issue make sure the DB statistics are updated, sometimes this might be the issue after that drop and create the procedure.
I think the problem is the sending parameters from your application to store procedure.
try it again but this time use SQL Server Profiler to trace your query execution .
you can use TextData column value in SQL Server Profiler and run real executed query again to find the real problem.

How to write unit case for remote database connection in asp web application

I am new to unit testing for web applications
I have a function which creates a connection to a remote mysql database and perform some operations on it .
I want to have a test case which tests the connection is closed or not after the operations on database.
for example
fun1()
{
ODBCConnection con = new ODBCConnection(connString);
con.open();
}
in the above function, the connection is not closed?
how do i check this? can any one help?
In .Net, it's generally best to open your connections immediately before you use them. So rather than building (and testing) a function that connects to the database, you build and test a function that returns the correct connectionstring. You also have a reference database for your testing environment, and so you build your data access methods and create their own connection and test them against your reference database, that the right results come back.
Okay, based on your comment I can help you. Since you will be opening and closing the connection in the same function (as you should), you can do this:
public void fun1()
{
using (ODBCConnection con = new ODBCConnection(connString))
{
con.open();
//use the connection here
}
//connection is closed here because of the using block, even if an exception is thrown
}
There is no need to check if the connection closes in the code above. It will be closed in a timely manner by the using block, and that's guaranteed as much as anything can be in software. Just make sure you use that pattern everywhere you use connections.
In unit testing, the "units" to be tested are methods/functions. You test that the function performs as you expect it to, and nothing more. If you want to test specifically if a connection is closed, than the way to do it is to write a function to close the connection, and test that.

Resources