Asp.Net MVC double submit/request breaks SQL connection - asp.net

I am running into a strange problem I don't fully understand. The main symptom is that when I double click a link (that points to a controller action) in my MVC application, my database server connection gets blown, and I get the error :
Execution of the command requires an open and available connection. The connection's current state is broken.
If I step through starting at a breakpoint at the top of the controller action, it will step down a couple lines and then jump back up to the breakpoint. Somehow the first request isn't executing fully before the second one gets there, and somehow my database connection breaks when it gets to any query. Every time this happens, I have to restart the application server.
It was happening intermittently at first, but the double clicking of links seems to reproduce it everytime. Does this happen to anyone else? What am I missing here?
Thanks,
rusty
Update :
A.) I incorrectly tagged this as Linq-to-sql when we are actually using Linq-to-entities.
B.) The connection object is defined as a member variable of the controller :
namespace C2S.Controllers
{
public class ArtifactController : Controller
{
private c2sEntities _entities = new c2sEntities();
...
I noticed in some of the asp.net tutorials they declare the variable in the same spot but have a separate constructor for the controller where the db object is initialized. Does this make any difference?
C.) The problem is not only with the double-clicking as described above. The connection breaks at other seemingly random times; I cannot seem to reproduce the error consistently (even double-clicking does not always break it). Restarting the web site usually fixes it, although sometimes I have to restart the host machine. After its back up, repeating the same sequence of actions usually does not reproduce the same error!
Maybe there's something I don't understand about setting up my linq-to-entities classes or the nature of the database connection. Does anyone have any thoughts? I really don't even know how to investigate this one!
Thanks again
Rusty

It's a bit difficult to say from your description of the problem, but a first guess would be:
Is your connection object static (i.e. controller or application level) or defined locally within the action? Double clicking a link would fire the event twice and that sounds like what you are describing here. So the first call creates the connection, then the 2nd call comes in and tramps all over the 1st call to the method, breaking the connection it thinks it has.
Edit: Does the problem only occur on double clicks. Does it work as expected if you only single click on the link? An example of the code in question would help.

I am guessing that you're not properly closing your database connection. You should consider making use of the using statement.
using(SqlConnection conn = new SqlConnection("connstring")) {
using (SqlCommand cmd = new SqlCommand("SQLSTATEMENT", conn)) {
// more code here......
}
}
This will ensure that your connection is closed even if there's an error in your code somewhere.
Read all about it here: http://davidhayden.com/blog/dave/archive/2005/01/13/773.aspx

Related

How do you get code to execute at the end of a procedure?

I'm working on a new piece of code at work to assist the rest of the programmers in making app server calls. Previously we just had a .i file and relied on the developer to make sure you made all the right calls and cleaned up the app server connection at the end of the program. Obviously some people have forgotten to do that in the past and it's caused problems for us.
I've been building a basic appserver.cls file, but I can't figure out how to get it to disconnect at the end of the program.
I've tried the following things so far.
ON CLOSE OF THIS-PROCEDURE
DO:
clAppServer:cleanupAppServer().
END.
This doesn't seem to fire at the end of the webspeed call.
DESTRUCTOR appserver():
cleanupAppServer().
END DESTRUCTOR.
This works when it does garbage collection, but Progress doesn't seem to do garbage collection at the end of a webspeed call and the objects are still in memory (which is an entirely different issue that I need to deal with).
ON CLOSE OF SESSION:LAST-PROCEDURE
DO:
clAppServer:cleanupAppServer().
END.
This doesn't even compile obviously.
I've tried a whole bunch of other things that are variants on these three to no avail.
Is there any way to do what I'm asking? Bonus points if it can be inside the appserver.cls file.
If I understand the question, you want to disconnect from another AppServer once the work is done. Would try something along the lines of the below work?
Create a AppServer-handle-wrapper class. This class is responsible for the A/S connection; it has a public "Handle" (or similarly-named) property that you can use to run stuff on the AppServer.
In this class' destructor you can add code that does your clean-up : disconnect and delete server handle .
Code that wants to run something on the AppServer does something like ...
def var asConn as AppServerConnection.
asConn = new AppServerConnection().
run foo.p on asConn:Handle (param1, out param2).
// cause GC
asConn = ?.
// manually destroy
delete object asConn.
The destructor will then do the right thing.
Note that if you have this code in an internal procedure or method, then the variable would go out of scope at the end of it, and the GC would kick in.
There's an example of this approach at https://github.com/consultingwerk/ADE-Sourcecode/blob/566ac0a6e085d6305a8f364f13a1d805d3597d2a/src/netlib/OpenEdge/Net/ServerConnection/ClientSocket.cls
Bear in mind that in the ClientSocket is that the handle is private - you may want to make it public for a general AppServer connection.

Can a thread in ASP.NET work keep continue after Response.End?

I want to make a tcp connection to a device and keep continously retrieve data from device. I want to start this with a simple request and keep it working background even Page response completed. Is this possible in asp.net?
Can a thread in ASP.NET work keep continue after Response.End?
Yes, you can if you do not care or do not need the result.
For example, in the following code, you call AddLogAsync and insert a log, but you not care whether insert successful or not.
public Task AddLogAsync(Log log)
{
return Task.Run(() => AddLog(log));
}
private void AddLog(TraceLog traceLog)
{
// Do something here.
}
I want to make a tcp connection to a device and keep continously
retrieve data from device. I want to start this with a simple request
and keep it working. Is this possible in asp.net?
I'm not really understanding above question. After Response.End, you cannot return anything, although you can continue work on something in different thread.

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.

in Flex 3.2 Having troubles converting remote object result to specific object on client side in modules

in Flex 3.2 Having troubles converting remote object result to specific object on client side in modules.
For example I have VIPSAdmin module.
it has function
private function doResult(event:ResultEvent):void {
var data_:Array = ArrayUtil.toArray(event.result);
var result:ResultDTO = data_[0] as ResultDTO;
if(!result.isError()) {
trace(result.result);
vipsAdminDTO = result.result as VIPSAdmin;
compId= vipsAdminDTO.compId; // second time dying here
}
}
Function invoked when I get data from remote objet.
First time all great,when I unload this modeule and load it again:
data_[0] as ResultDTO;
Performs fine, but
vipsAdminDTO = result.result as VIPSAdmin;
vipsAdminDTO always null!
Even when
trace(result.result);
produces [object VIPSAdmin]
What a heck I missing here!? Looks like it just cannot do
result.result as VIPSAdmin;
even when trace and debug says it is instance of VIPSAdmin
I've figured out what is the problem, problem is that when I first instantiate something in module then in main app, somehow classes are not alined even that they are identical !
So solution is to make a fake instance in application class first, then if you use that same class to make an instance in module it will work!
I do it very simple in my main application class I just added:
VIPSAdmin;
This seems to create some sort of ghost instance, which I belie will be pickup by GC later, but will build tables of instances properly! Which solved my problem.
Not sure if this is appropriate solution ! but it sure works.

ASP.NET Cannot evaluate expression because a thread is stopped at a point where garbage collection is impossible

I have a weird problem, I get an object from my DB, like this:
var user = BLL.Managers.Users.UserTmpManager.GetUser((int)customerID);
when I debug that code, and expand the user object, for each property I see the error as I mentioned at this topic's title. What causes it ?
unfortunately, it is still not being resolved, as I thought at the beginning..
I got this too, when I hit a NullReferenceException from a 3rd party control.
In this one case, I found that if I set a breakpoint before I hit the exception, I could then single step through the rest of the code without seeing the problem.
No idea why, but this worked for me - in this case at least.

Resources