Handling Timeouts In A Website SQLCommand Object And C#?
May 14, 2010
I'm using visual studio 2008 and sql server 2005 and everything is working just fine under normal use. However if a user is on a page for a while several minutes with no activity then clicks a button on occassion the site throws the following exception ...
Procedure or Function "sp_name" parameter '@SomeParameterName', which was not supplied
I'm also encountering this error in Visual Studio while debugging the application, in otherwords run the site from visual studio then make some change to the html in VS save the changes and refresh the page.
The error is not consistent nor is the time the page has to stay idle in order for it to occur....
The current sql command object timeout is 30 secs and the website timeout is 30 minutes.
This might have been asked before but I did a quick search and found nothing.
Problem: I want to get the name of the object that has a value of nothing and the type of the object when the "Object reference not set to an instance of an object error" occurs. The type obviously can be Object or specific. I want this information so that I can log a better error message in the error handling module. The only real useful information currently that comes back from the Exception object on a try catch is the line number at which the error occurred which in most cases is adequate except when you have functions calling functions, all in one line.
I've been stuck with this for days, and posted elsewhere online without success. If anyone can provide me with an answer to this problem I will arrange for beer to be sent to your chosen address....I have a DataTable containing multiple rows of data that I want to insert into a SQL 2005 table. The code works perfectly when the DataTable contains values that meet the SQL table schema design (e.g. all rows have a username, password, firstname & surname). However, when a value is missing or incorrectly entered (e.g. no firstname value), this causes a SqlException. I need to handle this in ASP.NET to provide a more user-friendly error message than what SQL gives, then rollback the whole transaction to cancel the transaction.The code attached is an imitation of how my data layer works. The error occurs on the RollBack() method. The error is: 'Object reference not set to an instance of an object'Can anyone explain why this happens? The SqlCommand object seems okay when I debug (it exists), but the Transaction object is lost as soon as the SqlException occurs. Although the transaction never commits when a SqlException is thrown, its a pretty ugly exit.My code design might be poor, in which I would welcome advice, but most important I need to figure out how to trap SqlExceptions without this error occuring, and Rollback as needed.The SqlException Numbers thrown are 2601 or 2627, both of which carry a severity level of 14, which is not high enough for the SqlCommand object to close the connection according to MSDN.The code looks lengthy but should be simple to follow...
how do you treat situations where there is the need of storing collections of object belonging to an object not persisted on db (not yet). For example , suppose we have a web application for submitting orders. The user click on 'Create new order" , then insert order's data , choose items from a catalog and add them to the order. Finally he "submit" the order. I can see two different way to persiste data :
a) create on db an empty order instance when user click on "create new order" , so that the orderitems collection could be directly associated (saved) with that instance in the db.
b) keep all data in memory and finally save order and orderitem.
The b option imply storing (in session?) the orderitems collection till submit. Are there, probably, other solutions. Which are best practices in these situation?
i am currently working on an asp.net mvc 2 web app using LinqToSQL. I would like to handle a scenario where a user comes form a country and for this i have set the users - countries db relationship and in my user model i have a CountryId property.
I would like to display the country name on my users display view, so i tried fetching the country name like this: User.Country.Name, but an exception occurs that i cannot access a disposed object. I understand that this is caused by the way i handle my users repository and service.
This the repository users code:
[Code]....
This is the service users code (the repository is not class level property, but a local one that gets dipsosed immediately after calling it):
[Code]....
So, how could i handle such a scenario, where i would like the Country model to be also fetched in order to use it later? Should i convert the repository model a class level proprty in order not to get disposed?
For a public website what is the best approch to handle the exception and showing to the system administrator and not to the user and what is the best practise followed in most of the ASP.NET sites.
I have a file upload to SQL Server 2005 DB that keeps timeing out at different times. I know about the web.config <httpRuntime maxRequestLength="2097151" executionTimeout="180"/> Where else are there times out settings?
I have a web service that sends up to 5000 emails to our customers.
It is called asynchronously from a web application and then chuggs away sending the emails. Generally it works okay. Yesterday, it kept stopping - sometimes after sending a small number (33 first time) and then it might send another couple of hundred - then 50 or so etc. This went on all day as I kept manually calling the web service.
The data (subject, body, fromaddress, replytoaddress etc) is all kept in the database - as are the recipients.
Here's the code that gets the data from the database.
// Create Instance of Connection and Command Object SqlConnection myConnection = new SqlConnection(ConnectionString); SqlCommand myCommand = new SqlCommand("CPEmailsToSend_List", myConnection);
// Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; myCommand.CommandTimeout = 1000;
[Code]....
So I have a dataset containing 3 sets of data - the subject, body etc., a list of attachments and a list of recipients. I then use the .net smtpClient like this:
Code: //about to start sending emails - update the MessageSendStatus to inprogress myCommand.CommandText = "CPEmailSendStatus_Update"; myCommand.Parameters.Clear(); myCommand.Parameters.Add("@CPEmailID", SqlDbType.Int).Value = CPEmailID; myCommand.Parameters.Add("@SendStatus", SqlDbType.TinyInt).Value = 1;
[Code] ....
When the web service stopped (it kept stopping yesterday) - no errors were raised. I have a function on the page that checks the email address is valid before I try to send the email as I know the smtpClient does not like invalid email addresses. Normally, invalid email addresses are trapped and the loop continues and sends the next one etc. But, yesterday, it just stopped sending. No error messages - nothing.
So, I began to wonder if the Command object is timing out. With a lot of email addresses to send to (up to 5000) and half a dozen attachments - the web service can take a long time (hours) to send all the emails. So, is the fact that I am reusing the command object over and over again for different stored procedures the issue? (I do this a lot and have never had a problem before - I read somewhere that the CommandTimeout only counts the time network access is used).
I've been sending test emails all morning (but I can only send small batches as I have a limited number of email addresses I can send test emails to) and they have all worked okay ... but, yesterday, trying to send about 5000 emails took about 30 attempts.
I have a webpage with a form that collects user data. I need to take that data (multiple items) and pass it to a completely different website. What would be the best way to do this keeping security in mind? Can I create a class, instantiate an object to hold the data and pass that object to the other website? Is that even possible? Is there a different/better way to do this?
Just getting back into .NET so I'm a little rusty.
I have a webservice, that when called, calls many other web services based on the information that was sent. I have always left the timeout as the default, or a better way to describe it, I have never changed anything. How (and where) do I change the timeouts for each service individually. Since I have quite a few now, I want the original transaction to never take more than 30 seconds. That said. I want to go in and change the timeouts for the services I have to ping in that 30 seconds to be 5 to 10 seconds based on which one.
There are various ways to handle session timeouts, like "meta refreshes" javascript on load functions etc.
I would like something neat like: 5 minutes before timeout, warn the user...
I am also contemplating keeping the session open for as long as the browser is open(still need to figure out how to do it though... probably some iframe with refreshing).
How do you handle session timeouts, and what direction do you think i should go in?
I expected this would set 30 minutes as timeout for inactive sessions, but they seem to be timing out much sooner.
Is there some other way to specify time for session timeout ?
I know I am using an unsupported AccessMembershipProvider which I was forced to do because my host service does not support SQL Server Database (so I am using an Access Database).
However, this AccessDB provider seems to work fine in all other respects. I'm suspecting that the early timeout is because of some other obscure setting.
I are building a web application which will be deployed to Windows Azure. I want user to set session timeout value which will be stored in Database. Currently I am aware of Web.Config method to set session timeout. i.e.
I've converted an ASP.Net website over to an Azure version and I've got it up and running. However the vast majority of the time I experience timeouts when I'm trying to debug the application.This seems to happen on any page at any time. I start debugging from VS2010 and sometimes the home page will come up sometimes it hangs. When it does come up if I select an item from a drop down list sometimes it works somtimes it times out. I have breakpoints set and they don't even fire I just eventually get the time out.
If I hit refresh that sometimes seems to fix it but it eventually starts happening again. This is making the completion of the conversion VERY difficult and I'm starting to creep up to a deadline.Does anyone have any idea what might be happening? If there is a better location I can post this question to would someone be kind enough to point me in the right direction?Thanks in advance for any help and in addition my email is mgorgone@pictureu.com as our Windows Live account email is diff.
Is this enough that should prevent that page from timing out as it does what it needs to? I have no control over the process and how long it runs but we've found that 5 minutes is more than enough time, yet we're still getting intermittent errors of:
System.Web.HttpException: Request timed out.
We've tried upping the value to 600 with really no difference and in any testing we've done we can never get the actual process to run for that long. Is there elsewhere that we need to be setting timeout values that won't affect the entire application and only the specific page we need the longer timeout value on?
Can I still use Session_OnEnd to trap a session timeout? Is there a better way to trap a session timeout? I want to take the user to a page that tells them the session timed out, and give them an opportunity to re-enter the application in a new session if they wish. How can I accomplish this? Is there still a global.asax file in the .NET 4.0 world?
I have code in an ASP.NET form that needs to, depending on user entry create messages in the database. We are speaking of potentially thousands of db entries. How do I protect against deadlocks, I mean apart from using Transactions and setting IsolationLevel to Serializable, as well as using WITH(NOLOCK) statement on my select statements since I don't mind a dirty read.
Event code: 3005 Event message: An unhandled exception has occurred. Event time: 10/13/2010 10:12:14 PM Event time (UTC): 10/14/2010 3:12:14 AM Event ID: a565c58a7f844692859aa21303447c7c Event sequence: 206 Event occurrence: 1 Event detail code: 0 Application information: Application domain: /LM/W3SVC/610100832/Root-12-129314933998593750 Trust level: Full Application Virtual Path: / Application Path: D:Websitesadmin.beta.sharedTime.com Machine name: SHAREDTIME Process information: Process ID: 3440 Process name: w3wp.exe Account name: NT AUTHORITYNETWORK SERVICE Exception information: Exception type: SqlException Exception message: Transaction (Process ID 56) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction. Request information: Request URL: http://beta.admin.sharedTime.com/admin_text_mass_send.aspx Request path: /admin_text_mass_send.aspx User host address: 69.211.10.138 User: Is authenticated: False Authentication Type: Thread account name: NT AUTHORITYNETWORK SERVICE Thread information: Thread ID: 10 Thread account name: NT AUTHORITYNETWORK SERVICE Is impersonating: False Stack trace: at mtNamespace.mt.createmessage_queue(String phone_number, String text_message, DateTime send_on, String system_name, Double user_no, Double send_priority, String message_type, Boolean returnqueue) in http://server/App_Code/mt.vb:line 1509 at ASP.admin_text_mass_send_aspx.save_user_values(Object sender, EventArgs e) in http://server/admin_text_mass_send.aspx:line 103 at System.Web.UI.WebControls.Button.OnClick(EventArgs e) at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) Custom event details:
I have an asp.net page that will be doing some processing that may take a very long time to complete. I cannot just set the page timeout value since this is going to be in a hosted environment and the timeout values that I set in my web.config are overridden by the server host. What I'm doing is taking a file from a FileUpload control and doing some web requests to a 3rd party service for each line in the file, all of which may take a very long time to process a large file. I'm talking on the order of, say, 30 minutes, and there's just no way to optimize this any further to cut down on the processing time. Is it possible to even do such a lengthy page request in asp.net? Can someone give me a pointer in the right direction here to make this happen? Is my only hope to create an async page? It seems that doing an async page is the way to go if I have a potential for a lot of lengthy requests, but really this massive of a request is going to happen VERY rarely so this is not an issue of running out of thread pool since most of the time this particular request will be completed relatively quickly, but on occasion it may receive a very large file it will need to process and will take a very long time. So what is the best way to handle that case?I'd also like to update the client with the processing status as the processing is going on. I'm familiar with doing client ajax calls via jQuery to a page webmethod so if there is some clean way to update the client as this long processing
I have a gridview, where I have made autocode using the wizard. However I need a dynamic SQLcommand from server side. I have tried this code, but it doesn't work, it works if I use this code from HTML (setting the sqlcommand in the SQLDataSource. I have deleted the sqlcommand from the HTML and instead I have implemented the code in the page_load event:
Code:
Dim str As String = SqlDataSource1.SelectCommand = "SELECT DISTINCT Beregning.bId, Informationer.Dato,Beregning.bType, Informationer.pNavn, Informationer.pNr, Informationer.Beskr, Beregning.uId FROM Beregning CROSS JOIN Informationer WHERE (Beregning.UserId = @UserId) AND Beregning.uId = Informationer.uId AND (Beregning.bType=@berType2) ORDER BY Beregning.bId DESC" SqlDataSource1.SelectCommand = str But this code works, when I apply the SQLCommand in HTML:
I have another class that creates the connection (see refined class half way down page) and I believe it connects or at lest I do not hit any of the exceptions in run time.
I would now like to insert data into my database but nothing is updated.
I am trying to follow this example but it is for reading.
I did run "querystring" on the show SQL Pane and it does execute correctly. It inserts data properly as a new row.
a) SqlCommand.ExecuteNonQuery is used for update, insert and delete operations.
Besides the fact that by using ExecuteNonQuery instead of ExecuteReader we automatically know there won't be any query results returned, are there some other benefits/reasons why ExecuteNonQuery should be used?
b) Similarly, if we want a database operation to return a single value, we should use ExecuteScalar instead of ExecuteNonquery ,where with the latter result would be returned via SqlParameter. Is there any particular reason why we should prefer ExecuteScalar over ExecuteNonQuery?
Dim conn As SqlConnection = New SqlConnection("server='h'; user id='w'; password='w'; database='w'; pooling='false'") conn.Open() Dim query As New SqlCommand("DECLARE @investor varchar(10), @sql varchar(1000) Select @investor = 69836 select @sql = 'SELECT * FROM OPENQUERY(db,''SELECT * FROM table WHERE investor = ''''' + @investor + ''''''')' EXEC(@sql)", conn) dgBookings.DataSource = query.ExecuteReader dgBookings.DataBind()
I need to add in an If statement basically saying if the SQLCommand query returns no rows then show a specific label Can this be done?