an error in ASP .NET4 + Linq - sql

I'm working on a project that using ASP .NET 4 C# (with Linq) and SQL server. All run well open page on my own computer IIS and connect to local sql database. and it is ok if connection to server database with IIS from my computer. Error happen if open published page (of cause it run from server IIS and will connect to server database).
Error from server's event log is
Log Name: Application
Source: ASP.NET 4.0.30319.0
Date: 4/17/2015 1:33:11 PM
Event ID: 1309
Task Category: Web Event
Level: Warning
Keywords: Classic
User: N/A
Computer: SZHDB1.ds.jdsu.net
Description:
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 4/17/2015 1:33:11 PM
Event time (UTC): 4/17/2015 5:33:11 AM
Event ID: 89f5a478bff241d3aaa4798ce86ad707
Event sequence: 22
Event occurrence: 1
Event detail code: 0
Application information:
Application domain: /LM/W3SVC/1/ROOT/IMS-2-130737223782305527
Trust level: Full
Application Virtual Path: /IMS
Application Path: D:\WebSite\IMS\
Machine name: SZHDB1
Process information:
Process ID: 3944
Process name: w3wp.exe
Account name: IIS APPPOOL\ASP.NET v4.0
Exception information:
Exception type: UpdateException
Exception message: An error occurred while updating the entries. See the inner exception for details.
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at Log.set_storeLog(String value) in C:\Users\che57576\Documents\Visual Studio 2010\Projects\InstrManage\InstrManage\App\Common.cs:line 26
at InstrManage.Admin.Group.GridView_group_SelectedIndexChanged(Object sender, EventArgs e) in C:\Users\che57576\Documents\Visual Studio 2010\Projects\InstrManage\InstrManage\Admin\Group.aspx.cs:line 164
at System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
String or binary data would be truncated.
The statement has been terminated.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary2 identifierValues, List1 generatedValues)
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
and the related code are here:
'Common.cs':
public class Log
{
string conn, username;
public string storeLog
{
set
{
using (AdminEntities myEntrities = new AdminEntities(conn))
{
IMSlog log = new IMSlog();
log.user_name = username;
log.date_time = DateTimeOffset.Now;
log.what = value;
myEntrities.IMSlogs.AddObject(log);
myEntrities.SaveChanges(); //this is line 26
}
}
}
public Log(string linqConn,string userName)
{
conn = linqConn;
username = userName;
}
}
'Group.aspx.cs':
protected void Page_Load(object sender, EventArgs e)
{
log = new Log(sqlconnstr, Session["UserName"].ToString());
}
and in the same page, in the event:
protected void GridView_group_SelectedIndexChanged(object sender, EventArgs e)
{
bool result;
result = Int32.TryParse(GridView_group.SelectedRow.Cells[0].Text.ToString(), out index);
currentStatus = (GridView_group.SelectedRow.FindControl("CheckBox1") as CheckBox).Checked;
using (TransactionScope scope = new TransactionScope())
{
using (AdminEntities myEntrities = new AdminEntities(sqlconnstr))
{
admin_group c = (from r in myEntrities.admin_group
where r.group_id == index
select r).First();
c.group_enable = !currentStatus;
myEntrities.SaveChanges();
log.storeLog = "Set group ID " + index.ToString() + " to " + Convert.ToString(!currentStatus); // this is line 164
}
scope.Complete(); // To commit.
}
queryGroup();
}
when the above event be trigger, the error will happen.
I've search from lots of time, not sure why my laptop is ok but server cannot.
my laptop is win7 and sql express.
server is asp .net 4 and SQL server 2008.

The problem seems to be that you are trying to save a value too long for the length available in the database.
To find the problem, try to look at the length of the username you are trying to save and compare it to what's available in the database.
By setting a breakpoint on row #26 in Common.cs, you should be able to see the content of the variable username.
Once you find the problem, you can increase the size in your database. Also, it's recommended to validate the length of your username directly in your Web Application so the user can't enter a username too long for your database, an error message should be sent to the user asking him to use a shorter username.

One of the following assignments is too large for your data store
log.user_name = username;
log.date_time = DateTimeOffset.Now;
log.what = value;
You can also check if log.date_time is assigned the correct value

Related

Azure SQL - System.ComponentModel.Win32Exception: The wait operation timed out

I have an MVC Azure Web App, using an Azure SQL Database.
I've just finished developing a new version on my local machine, and released it to my Azure test environment, but it's behaving a bit strangely: some parts of the system work, but one particular part (which hasn't changed for this release) is giving me the following error:
System.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTdsWithTransparentParameterEncryption(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest, Task describeParameterEncryptionTask)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryInternal[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass69`1.<ExecuteStoreQueryReliably>b__68()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass69`1.<ExecuteStoreQueryReliably>b__67()
at System.Data.Entity.Infrastructure.DbExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery[TElement](String commandText, ExecutionOptions executionOptions, Object[] parameters)
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
The part that's failing calls a stored procedure to generate some management information. It works fine in my local environment and on the production site, but fails in the test environment. In the environments that work, it takes a fraction of a second to run.
Other parts of the test system are working fine, and the performance is the same as usual.
It turned out that the problem was the pricing tier of the database.
Until now I've been running the test database at Basic level, to keep costs down. Basic level supports databases up to 2GB.
When I imported the most recent copy of the production database it was less than 2GB, so I was allowed to select Basic, but that didn't leave enough space for the temporary tables used by the stored procedure that was causing the problem.
As soon as I switched to the Standard pricing tier and increased the maximum size of my database to 5GB, the problem went away.

Hangfire - Background job creation failed. See inner exception for details

I create a hangfire jobs as `BackgroundJob.Enqueue(x => x.Recalculate(itemID)); to queue a job. When I try to save consecutively few times I get following error from Hangfire.
Here is the stack trace,
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, CommandDefinition& command, Action`2 paramReader)
at Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition& command)
at Dapper.SqlMapper.Execute(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Nullable`1 commandTimeout, Nullable`1 commandType)
at Hangfire.SqlServer.SqlServerWriteOnlyTransaction.<>c__DisplayClass7_0.<SetJobState>b__0(SqlConnection x)
at Hangfire.SqlServer.SqlServerWriteOnlyTransaction.<Commit>b__4_0(SqlConnection connection)
at Hangfire.SqlServer.SqlServerStorage.<>c__DisplayClass17_0.<UseTransaction>b__0(SqlConnection connection)
at Hangfire.SqlServer.SqlServerStorage.UseConnection[T](Func`2 func)
at Hangfire.SqlServer.SqlServerStorage.UseTransaction[T](Func`2 func, Nullable`1 isolationLevel)
at Hangfire.SqlServer.SqlServerStorage.UseTransaction(Action`1 action)
at Hangfire.Client.CoreBackgroundJobFactory.Create(CreateContext context)
at Hangfire.Client.BackgroundJobFactory.<>c__DisplayClass7_0.<CreateWithFilters>b__0()
at Hangfire.Client.BackgroundJobFactory.InvokeClientFilter(IClientFilter filter, CreatingContext preContext, Func`1 continuation)
at Hangfire.Client.BackgroundJobFactory.Create(CreateContext context)
at Hangfire.BackgroundJobClient.Create(Job job, IState state)
Exception message: Background job creation failed. See inner exception for details.(BackgroundJobClientException)
Inner Ex: Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Has anyone came across this issue? This works fine in locally. But issue happens in Azure Deployment. I am using a v12 database. Appreciate any help. I noticed that all my hangfire job creation takes like 20 seconds on average to queue the background job. When I try to create the job again and again it times out. Time out seems to be 30 seconds.
I tried to increase the connection timeout but what ever the value I put in connection string, it seems it times out after 30 seconds. But increasing the time out won't solve the underlying issue anyways.
I figured out that DTU usage is at 100% most of the time, which was unacceptable as there was nothing much happening in the Test environment that I was testing this. Then I looked in to performance data in Azure database which gave me worst performing queries, which was really handy. Handfire delete jobs query was causing this performance issue. It was an issue with the Hangfire version we were using. Solution was to upgrade the Hangfire to a latest version.

The wait operation timed out Win32Exception (0x80004005): The wait operation timed out azure

Following error comes when retrieving large amount of data from sql azure. I have already implement the Transient Fault Handling but still getting this error
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ComponentModel.Win32Exception: The wait operation timed out
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[Win32Exception (0x80004005): The wait operation timed out]
[SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +1789270
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5340622
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1691
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +275
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) +1421
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +177
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +208
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +163
System.Web.SessionState.SqlSessionStateStore.SqlExecuteNonQueryWithRetry(SqlCommand cmd, Boolean ignoreInsertPKException, String id) +98
[HttpException (0x80004005): Unable to connect to SQL Server session database.]
System.Web.SessionState.SqlSessionStateStore.ThrowSqlConnectionException(SqlConnection conn, Exception e) +235
System.Web.SessionState.SqlSessionStateStore.SqlExecuteNonQueryWithRetry(SqlCommand cmd, Boolean ignoreInsertPKException, String id) +390
System.Web.SessionState.SqlSessionStateStore.SetAndReleaseItemExclusive(HttpContext context, String id, SessionStateStoreData item, Object lockId, Boolean newItem) +589
System.Web.SessionState.SessionStateModule.OnReleaseState(Object source, EventArgs eventArgs) +565
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34009
http://i.stack.imgur.com/8BloW.png
The SqlClient.SqlCommand object has a property CommandTimeout. It's default value is 30 (seconds). You should set it to a higher value.
You can set the timeout value higher or you can turn off the timeout value, as I did in the below code. Note that you may encounter errors if the object that holds the data exceeds 2Gb. You may want to consider redesigning your query to take smaller chunks of data at a time.
// I'm populating an ADO.Net DataTable for this demo but populate whatever object you'd like
DataTable DtFromSQL = new DataTable();
SqlConnection myConnection = new SqlConnection("ConnectionString");
myConnection.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("enter some SQL query here", myConnection);
// A CommandTimeout Value of 0 turns the timout off, otherwise you can set it to some value in seconds
myCommand.CommandTimeout = 0;
myReader = myCommand.ExecuteReader();
DtFromSQL.Load(myReader8);
myConnection.Close();
DtFromSQL;

Concurrent access to a database with Entity Framework == EntityException

I've a MS SQL 2008 database which is accessed through LINQ for data update/retrival.
My linq is accessed by WCF services in a PerCall instantiation mode for an heavy application. This application has several thread which makes calls to the service, and several application are running in the sametime.
I've often some EntityException happening:
System.Data.EntityException was caught
Message=An error occurred while starting a transaction on the provider connection. See the inner exception for details.
Source=System.Data.Entity
StackTrace:
at System.Data.EntityClient.EntityConnection.BeginDbTransaction(IsolationLevel isolationLevel)
at System.Data.EntityClient.EntityConnection.BeginTransaction()
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at Infoteam.GfK.TOMServer.DataServer.DataServer.SaveChanges() in D:\Workspace\XYZWASDF\DataServer\DataServer.cs:line 123
InnerException: System.Data.SqlClient.SqlException
Message=Une nouvelle transaction n'est pas autorisée parce que d'autres threads sont en cours d'exécution dans la session.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=16
LineNumber=1
Number=3988
Procedure=""
Server=ift-srv114
State=1
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.TdsExecuteTransactionManagerRequest(Byte[] buffer, TransactionManagerRequestType request, String transactionName, TransactionManagerIsolationLevel isoLevel, Int32 timeout, SqlInternalTransaction transaction, TdsParserStateObject stateObj, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransactionYukon(TransactionRequest transactionRequest, String transactionName, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransaction(TransactionRequest transactionRequest, String name, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalConnection.BeginSqlTransaction(IsolationLevel iso, String transactionName)
at System.Data.SqlClient.SqlInternalConnection.BeginTransaction(IsolationLevel iso)
at System.Data.SqlClient.SqlConnection.BeginDbTransaction(IsolationLevel isolationLevel)
at System.Data.Common.DbConnection.BeginTransaction(IsolationLevel isolationLevel)
at System.Data.EntityClient.EntityConnection.BeginDbTransaction(IsolationLevel isolationLevel)
InnerException:
(Sorry it's not very readable). (The message of the internal exception mean "A new transaction is not allowed because there are other threads running in the session."
I've check, I'm not in a loop, it's purely random when it makes this exception, and I've no idea about how to avoid this.
any help will be really appreciated :)
Thank you!
EDIT: Here is an example of where I got this exception SOMETIMES
//My DataServer method, which is a singleton
[MethodImpl(MethodImplOptions.Synchronized)]
public void SaveChanges()
{
lock (_lockObject)
{
try
{
_context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
_changeListener.ManageIDAfterInsert();
}
catch (Exception ex)
{
Logger.Instance.Error("[DataServer:SaveChanges] Got an error when trying to save an object", ex);
//HERE I've this error
}
}
}
//One example where I can have exception sometimes, this is called through a WCF service, so I have a method which attach the object and then save it
private OrderStatus AddOrderStatus(OrderStatus orderStatus)
{
DataServer.DataServer.Instance.InsertOrUpdateDetachedObject(orderStatus);
return orderStatus;
}
Without seeing your code, the short answer is that EntityFramework is not thread-safe. You're getting this error in a seemingly random pattern when two+ threads overlap when trying to try access your ObjectContext. I assume you've stuffed your context into a static variable. Either make the context a local variable or write locking around access to the ObjectContext.
If you want a more specific answer posting your code will help.
Edit
Your issue is that two threads are trying to use the context at the same time, or 1 thread is leaving a transaction open then and a second thread comes through trying to use your singleton context. Your code snippet raises more questions for me than I had before.
In your code example is _lockObject a static variable?
Why do you show the lock in SaveChanges but then explain an error is being thrown
from InsertOrUpdateDetachedObject? Can we see the code for InsertOrUpdateDetachedObject?
Does SaveChanges use the same _lockObject as all other methods that access the context directly?
Is your call to _context.SaveChanges the only way you save to the DB or do you have other areas that open transaction contexts on their own?
Your using a singleton so your context is shared across multiple calls. It might be preferable to instantiate a new new context for every WFC call.

Timeout error in VB.NET while running a sql script

I was wondering if someone can help me figure why I am getting this error from a simple stored procedure that I created in SQL Server 2008 R2. I am trying to obtain data and insert it into a temporary table. if it is a timeout issue, how can I increase the timeout length to 420 seconds. to my understanding the timeout is good for only 30 seconds.
this is the error in its entirety:
Server Error in '/WebSite9' Application.
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1951450
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4849003
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2394
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +33
System.Data.SqlClient.SqlDataReader.get_MetaData() +83
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +297
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +954
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +162
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +12
System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +10
System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +130
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +287
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable) +92
System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +1297
System.Web.UI.WebControls.BaseDataList.GetData() +38
System.Web.UI.WebControls.DataList.CreateControlHierarchy(Boolean useDataSource) +153
System.Web.UI.WebControls.BaseDataList.OnDataBinding(EventArgs e) +54
System.Web.UI.WebControls.BaseDataList.DataBind() +55
System.Web.UI.WebControls.BaseDataList.EnsureDataBound() +60
System.Web.UI.WebControls.BaseDataList.CreateChildControls() +69
System.Web.UI.Control.EnsureChildControls() +87
System.Web.UI.Control.PreRenderRecursiveInternal() +44
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842
Version Information: Microsoft .NET Framework Version:2.0.50727.4952; ASP.NET Version:2.0.50727.4955
Dim cmd = connection.CreateCommand()
cmd.CommandTimeout = 420
Use the CommandTimeout property.
Set the timeout in ASP code
VB.NET:
Dim objCmd = conn.CreateCommand()
objCmd.CommandTimeout = 420
or Classic:
set con = createObject("ADODB.Connection")
con.open connectionString
con.commandTimeout = 420
I would review your execution plan on your query as well to determine if you have some table scans going on resulting in a poor performing query.