ASP.NET logic / connection pooling and error handing - asp.net

I just uploaded my first ASP.NET (as part of my learning of vb.net) and got into awful mess with the connection pooling (funny things happen when there are more than 1 user of your web site) all sorted now by better use of the try catch statements (well the idea was to learn) BUT I was wondering if this is the best / final method, now if the try fails, then a LOT of the detail on the page isn't placed/updated, so if you are doing some database work and the try fails, do you reload the page ... redirect to self and hope it work the next time ... or just inform the user there was a error and they should try again ?
Thanks

You should defintely use 'using' statements for all objects that implement IDisposable (such as connections and readers). A 'using' statement gets translated into a try-finally block under the covers, and ensures that Dispose() is called even if an error occurs.
Here is a code snippet example:
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "LoadFromRepository";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ID", fileID);
conn.Open();
using (SqlDataReader rdr =
cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (rdr.Read())
{
// do something with read data
}
}
}
}

If an unexpected error occurs, redirect the user to an error page as it probably will happen the next time around too.
Have you looked into "Using" statements for DB connections and readers?

I would never automatically redirect and hope that it will work the next time (you might get in a infinite loop).
Inform the user and optionally a link to try it again.
You even might want to analyze your exception to see if another try will help. Some exceptions are really bugs, and another try will not help.

Related

Exit for loop inside using keyword [duplicate]

I've the following code
using(MemoryStream ms = new MemoryStream())
{
//code
return 0;
}
The dispose() method is called at the end of using statement braces } right? Since I return before the end of the using statement, will the MemoryStream object be disposed properly? What happens here?
Yes, Dispose will be called. It's called as soon as the execution leaves the scope of the using block, regardless of what means it took to leave the block, be it the end of execution of the block, a return statement, or an exception.
As #Noldorin correctly points out, using a using block in code gets compiled into try/finally, with Dispose being called in the finally block. For example the following code:
using(MemoryStream ms = new MemoryStream())
{
//code
return 0;
}
effectively becomes:
MemoryStream ms = new MemoryStream();
try
{
// code
return 0;
}
finally
{
ms.Dispose();
}
So, because finally is guaranteed to execute after the try block has finished execution, regardless of its execution path, Dispose is guaranteed to be called, no matter what.
For more information, see this MSDN article.
Addendum:
Just a little caveat to add: because Dispose is guaranteed to be called, it's almost always a good idea to ensure that Dispose never throws an exception when you implement IDisposable. Unfortunately, there are some classes in the core library that do throw in certain circumstances when Dispose is called -- I'm looking at you, WCF Service Reference / Client Proxy! -- and when that happens it can be very difficult to track down the original exception if Dispose was called during an exception stack unwind, since the original exception gets swallowed in favor of the new exception generated by the Dispose call. It can be maddeningly frustrating. Or is that frustratingly maddening? One of the two. Maybe both.
using statements behave exactly like try ... finally blocks, so will always execute on any code exit paths. However, I believe they are subject to the very few and rare situations in which finally blocks are not called. One example that I can remember is if the foreground thread exits while background threads are active: all threads apart from the GC are paused, meaning finally blocks are not run.
Obvious edit: they behave the same apart from the logic that lets them handle IDisposable objects, d'oh.
Bonus content: they can be stacked (where types differ):
using (SqlConnection conn = new SqlConnection("string"))
using (SqlCommand comm = new SqlCommand("", conn))
{
}
And also comma-delimited (where types are the same):
using (SqlCommand comm = new SqlCommand("", conn),
comm2 = new SqlCommand("", conn))
{
}
Your MemoryStream object will be disposed properly, no need to worry about that.
With the using statement, the object will be disposed of regardless of the completion path.
Further reading...
http://aspadvice.com/blogs/name/archive/2008/05/22/Return-Within-a-C_2300_-Using-Statement.aspx
http://csharpfeeds.com/post/8451/Return_Within_a_Csharp_Using_Statement.aspx
Take a look at your code in reflector after you compile it. You'll find that the compiler refactors the code to ensure that dispose is called on the stream.

While retriving data for mutiple AJAX call with 2 different methods using DataReader

While retriving data for mutiple AJAX call with 2 different methods using DataReader.
method 1:
using (SqlDataReader reader = clientDb.ExecuteSPReader("SP1",
CommandBehavior.CloseConnection,
parameters))
{
if (reader.HasRows)
{
while (reader.Read())
{
}
reader.Close();
}
}
method 2:
using (SqlDataReader reader = clientDb.ExecuteSPReader("SP2",
CommandBehavior.CloseConnection,
parameters))
{
if (reader.HasRows)
{
while (reader.Read())
{
}
reader.Close();
}
}
both the method is execute on a single db. Should it suggested that I would not close the reader, as It will be closed by GC? and I am executing reader with "using" statement.
In my case, issue is as both the method is using same database. One method
reader.close()
closes the other method connection and it jumps to exception. So, wanted to know what is the best way to implement such a AJAX request methods.
I have also read in following url that one should not close or dispose the managed objects.
https://msdn.microsoft.com/en-us/library/8xx3tyca%28v=vs.110%29.aspx
First, by using the using statement, when the execution leaves the scope, SqlDataReader will be disposed. It is the same as calling reader.Dispose() manually.
Since the reader don't have a dependency on external or un-managed code, like your SqlConnection, you don't have to dispose it but you should always close it. The disposal will be managed by the GC.
Further on you should really wrap your SqlConnection in a using statement, since it's using a connection pool to the database. And it is not very good for performance if you leave a lot of open connections to the database, when they are not in use.
I assume these database calls are made in two different calls to the server, and not in sequence just after each other in the same method.

how to handle exceptions in vb.net?

I am creating a program in which a user can search and add their desired order. The problem that I'm facing now is that when I throw the exception, the program does not read the exception so that the user will know if the id that is entered is on the database or not. I will provide the code snippet of the program that I'm working on.
Problems
Your code will not throw an error if the item_code does not exist in your database. It will simply not enter the while loop.
This is not the proper use of an exception. It is not an error if the record is not found. The proper way of checking if the item_code exists is a check if the datareader has results.
You must properly defend yourself again SQL injection. By concatenating the sql query you are opening yourself up to a whole host of problems. For example, if a user maliciously enters the following text, it will delete the entire Products table: ';DROP TABLE Products;-
You are not disposing of the OleDbConnection or the OleDbCommand objects correctly. If an exception occurs, your code will not run the Dispose() method. This can cause you to quickly run out of resources.
Solutions
You should check if the dataRead has any rows. If it does not, then you can alert the user via javascript. Like so:
If dataRead.HasRows Then
//READ DATA
Else
//ALERT USER
End If
Solution #1 address Problem #2 as well
Use a parameterized query. The .NET framework will prevent these kinds of attacks (SQL Injection).
selectProductQuery = "SELECT * FROM Products WHERE item_code = #item_code"
...
newCmd.Parameters.AddWithValue("item_code", txtItemCode.Text);
Wrap all objects that implement Dispose() in a using block. This will guarantee everything is properly disposed of, whether an error is thrown or not.
Using newCon As New OleDbConnection(....)
Using newCmd As New OleDb.OleDbCommand(...)
...
End Using
End Using
To be perfectly honest, there is quite a bit "wrong" with your code, but this should get you headed in the right direction.
The line:
Response.Write(<script>alert('The ...')</script>)
Needs to be (note the quotes):
Response.Write("<script type='text/javascript'>alert('The ...')</script>")
Same for the other one at the top, but I dont think that will fix your overall problem.
Instead, use javascript like this:
if(!alert('Whoops!')){window.location.reload();}
to pop up an alert box and then reload the page after they click on the button.

Alternatives for SqlCommand.BeginExecuteNonQuery or SQL jobs? (for calling a stored procedure asynchronously from asp.net web page)

Aim: Calling a very slow stored procedure (with parameters) asynchronously from code behind of an asp.net web page via single function call, and then forgetting about it.
Notes: I tried using SqlCommand.BeginExecuteNonQuery without calling SqlCommand.EndExecuteNonQuery (see the code below), but the stored procedure didn't run. (I used a tiny stored procedure to update single field on a table for testing but the field was not updated. It gets update when I use SqlCommand.ExecuteNonQuery).
I am not interested in and don't know when the stored procedure will end. (So I can't wait for it to finish to call SqlCommand.EndExecuteNonQuery.)
Situation:
After some research, I found out that sql jobs can be used for this purpose. And for the sp parameters; I can store them in a table and then sp can read them. However I don't know if this is the right approach to my problem (I am new to SQL world). I hope you can comment on usage of an sql job for this purpose, or suggest alternatives. Thanks.
Code:
using (SqlConnection connection = new SqlConnection(
#"Data Source=XXX\MSSQL2008R2;Initial Catalog=YYY;Integrated Security=True"
+ ";Asynchronous Processing=true"))
{
connection.Open();
SqlCommand cmd = new SqlCommand("spTestProcedure", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#pText", DateTime.Now.ToString()));
cmd.BeginExecuteNonQuery(); //Doesn't work.
//cmd.ExecuteNonQuery(); // This works.
}
I think you should simply execute your sp in a separate thread.
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
Use ThreadPool for example to make a sync call on a separate thread.
It will looks something like this...
Extract method:
private void ExecuteCommandSync()
{
using (SqlConnection connection = new SqlConnection(
#"Data Source=XXX\MSSQL2008R2;Initial Catalog=YYY;Integrated Security=True"
+ ";Asynchronous Processing=true"))
{
connection.Open();
SqlCommand cmd = new SqlCommand("spTestProcedure", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#pText", DateTime.Now.ToString()));
cmd.ExecuteNonQuery();
}
}
Change your code:
ThreadPool.QueueUserWorkItem((x) => { ExecuteCommandSync(); });
It will make a synchronous call on some thread from ThreadPool, once it is done - it will close connection and you are done.
It is not the BEST solution performance-wise, because you will have a thread sleeping while it waits for the Stored Proc, but it is good enough and will do what you want.
I was looking for a way of doing this from the code behind of asp.net, but realized there is no easy way of doing it (I didn't want to think about connection or time out problems). I ended up doing it via a web service.
From asp.net code behind, I call my webs service's function synchronously.
Within the web service's function, I call the stored procedure asynchronously using SqlCommand.BeginexecuteNonQuery(AsyncCallback, Object).
The callback is handled within the web service (for error handling).
Hence my web page keeps working the way I want: Fire the request once, then forget about it.

ASP.NET :What advantage if i use using when creating an object

in ASP.NET, I have seen people coding like this
using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
// Do the datatbase transactions
}
How does it differ from this one
SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString)
// Do the datatbase transactions
Is there any performance/speed improvements in using one over the other ?
The using statement allows the
programmer to specify when objects
that use resources should release
them. The object provided to the using
statement must implement the
IDisposable interface. This interface
provides the Dispose method, which
should release the object's resources.
A using statement can be exited either
when the end of the using statement is
reached or if an exception is thrown
and control leaves the statement block
before the end of the statement.
A good article can be found here
Understanding the 'using' statement in C#
It's just a shortcut. :)
using (var foo = new Foo())
foo.bar();
equals to:
Foo foo = new Foo();
try
{
foo.bar();
}
finally
{
if (foo != null)
((IDisposable)foo).Dispose();
}
using keyword ensures that object will be disposed (it must implement IDisposable).
It's useful when working with external resources (database connection, file streams etc.) - they will be released despite of errors that may occur.
Using: Defines a scope, outside of which an object or objects will be disposed.
So its just syntax instead of creating the object then disposing it.
More details on MSDN
objects created in the using construct have lifetime within the construct (the braces {}). And if you notice only those members which implement the IDisposable interface can only be created. It simply means that right after the using construct code the the compiler will automatically call the dispose method on the object you've created. It helps in garbage collection.
As in the case of SqlConnection objects we must call dispose otherwise the ado.net connection pool (which manages connections to database) will assign a new connection to another incoming request instead of reusing an old connection pool. Connection pooling is simply an inherent way to minimize the resources & time taken to acquire a connection to a database.
Refer:
Connection Pooling
IDisposable
using statement is a shortcut for
try
{
/* do the work here with obj */
}
finally
{
if (obj != null)
obj.Dispose();
}
In general, you should use the using syntax for any object that implements IDisposable - for example, SqlConnection.
The using statement ensures that the object is disposed correctly at the end of the block in (almost) all circumstances, even if exceptions occur.
There aren't any direct speed/performance differences either way, but if you don't dispose of your IDisposable objects (usually by using using) then you might encounter problems down the line because vital resources haven't been tidied up.
Using using is good practice and almost always the right way to do things. Not using using is usually a bad idea, unless you're absolutely certain of what you're doing and why.
the using statement would automatically call the finally, i.e once the using block is finished, it will dispose off the object.
using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
// Do the datatbase transactions
}
is equivalent to:
SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString)
// Do the datatbase transactions
myConnection.Close();
myConnection.Dispose()

Resources