I have one issue at my work. It about SQL Server stuck one table during has many many transaction request from branches. My solution everyday is cannot do anything without restart SQL Server service.
Below is error log:
E60D17110910021661V1.9.8.3 - 2017-11-09 10:16 : Error: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.\ Details: at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
at System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync()
at System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket()
at System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer()
at System.Data.SqlClient.TdsParserStateObject.TryReadByte(Byte& value)
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)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
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.ExecuteReader()
at TCAM_SOLUTION.Forms.General.CustomerNew.RepositoryBase.ExecuteReader(SqlCommand cmd)
at TCAM_SOLUTION.Forms.Service.SaleOrdering.ServiceInvoices.ServiceInvoiceRepository.GetExistedRepairOrderDetails(List`1 repairOrderDetailIds)
at TCAM_SOLUTION.Forms.Service.SaleOrdering.ServiceInvoices.ServiceInvoiceService.HasItemsSaved(ServiceInvoice invoice)
at TCAM_SOLUTION.Forms.Service.SaleOrdering.ServiceInvoices.FormServiceInvoice.IsNotValidated()
at TCAM_SOLUTION.Forms.Service.SaleOrdering.ServiceInvoices.FormServiceInvoice.btnSave_Click(Object sender, EventArgs e)
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Many thanks in advance.
Suy
Related
I'm new in react-native, I try to make a fetch request using GET for a login page. I talk to a WebService. The response is correct when I hardcode login and password but if I use my own variable like: this.state.login I have this following error :
System.Data.SqlClient.SqlException: Erreur de conversion du type de données nvarchar en bigint.
à System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
à System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
à System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
à System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
à System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
à System.Data.SqlClient.SqlDataReader.get_MetaData()
à System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
à System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
à System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
à System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
à System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
à System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
à System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
à System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
à System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
à System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
à dataClub.DSMembreTableAdapters.TAMembreBureau.GetDataForLogin(String LICI_NUMERO, String LICI_MDP, Nullable1 LOGINADMIN) dans C:\Users\vfelder\Documents\Visual Studio 2015\Projects\ClubOnline\dataClub\DSMembre.Designer.cs:ligne 3869
à ClubOnline.WebServices.AppliMobile.connexion(String p_login, String p_mdp) dans C:\Users\vfelder\Documents\Visual Studio 2015\Projects\ClubOnline\ClubOnline\WebServices\AppliMobile.asmx.cs:ligne 46
This is my constructor and fetch request:
constructor(){
super();
this.state = {
login: '',
password: ''
}
}
userLogin(){
fetch('myWebService?p_login=this.state.login&p_mdp=this.state.password',
{
method: 'GET',
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
},
})
.then(res => console.log(res));
}
And this is my TextInput and Button related to my state:
<TextInput
onChangeText={(text)=>this.setState({login: text})}
placeholder={'Identifiant'}
ref={"login"}
returnKeyType={'next'}
style={styles.input}
value={this.state.login}
/>
<TextInput
editable={true}
onChangeText={(text)=>this.setState({password: text})}
placeholder={"Mot de passe"}
ref={'password'}
secureTextEntry={true}
style={styles.input}
value={this.state.password}
/>
<Button
onPress={this.userLogin.bind(this)}
style={styles.buttonContainer}
title={"Connexion"}>
</Button>
I try to make a post request or directly use XMLHttpRequest but it allawys the same, if I use my own variable, this error is generate. I really don't know what I missed. I hope have been as specific as possible.
You are using this.state.login and this.state.password as string , not the value by putting them in single quotes '
fetch('your_url?p_login=this.state.login&p_mdp=this.state.password',
Change this line with one of below:
Use proper single quotes
fetch('your_url?p_login='+this.state.login+'&p_mdp='+this.state.password,
OR : Use New ES6 syntax ${var} :
fetch(`your_url?p_login=${this.state.login}&p_mdp=${this.state.password}`,
Note : I've replaced your url with your_url, so you can easily check the
changes you need to make
In production I had an episodic timeout exception during commit an Nhibernate transaction. But the records that I expect updated are correct!
In stage environment nothing to report.
Here below the application logs of my batch program.
ERROR 2015-06-25 01:32:01,165 SRV-IIS03 Commit failed
System.Data.SqlClient.SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
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(Transacti onRequest transactionRequest, String transactionName, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransaction(TransactionReq uest transactionRequest, String name, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalTransaction.Commit()
at System.Data.SqlClient.SqlTransaction.Commit()
at NHibernate.Transaction.AdoTransaction.Commit()
ERROR 2015-06-25 01:32:01,431 SRV-IIS03 Errore imprevisto nel metodo Run:NHibernate.TransactionException: Commit failed with SQL exception ---> System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
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.SqlInternalTransaction.Commit()
at System.Data.SqlClient.SqlTransaction.Commit()
at NHibernate.Transaction.AdoTransaction.Commit()
--- End of inner exception stack trace ---
at NHibernate.Transaction.AdoTransaction.Commit()
at [omit].Run(String[] args) in [omit].cs:line 153
ERROR 2015-06-25 01:32:01,493 SRV-IIS03 Errore imprevisto nel batch [omit]: NHibernate.TransactionException: Transaction not successfully started
at NHibernate.Transaction.AdoTransaction.CheckBegun()
at NHibernate.Transaction.AdoTransaction.Rollback()
at [omit].RollbackTransazione() in [omit].cs:line 212
at [omit].Run(String[] args) in [omit].cs:line 159
at [omit].Main(String[] args) in [omit].cs:line 29
And here below the structure of my batch
private static ITransaction tx;
public virtual BatchResponseStatus Run(string[] args)
{
var response = BatchResponseStatus.Success;
try
{
//Do some stuff
SetTransaction();
//Collect elements to be processed
foreach (var item in aListOfItem)
{
// Stuff
// Call methods that creates, reads or updates records
// with Fluent Nhibernate or Sql Server Stored procedure
// Write some files
// Zip files
// Update DTO
}
tx.Commit();
}
catch (Exception ex)
{
RollbackTransaction();
XXRepository.NhSession.Clear();
response = BatchResponseStatus.Error;
}
finally
{
DisposeTransaction();
}
return response;
}
private void SetTransaction()
{
tx = XXRepository.NhSession.BeginTransaction(IsolationLevel.ReadUncommitted);
if (tx == null)
throw new Exception("Impossible create a Transaction");
}
private static void RollbackTransaction()
{
if (tx != null)
{
tx.Rollback();
}
}
I use this technologies:
Sql Server stored procedure
Nhibernate 3.4 (Fluent Nhibernate)
.Net Framework 4.5
Anybody can help me?
Thanks.
The timeout occurs on the connection. This means, that the connection times out, but commit continues in Sql Server. As you can see in the log, Rollback fails because the connection is already committed. IMHO, the connection timeout is not properly handled by the SqlClient implementation.
There is a forum thread where this is discussed.
Query is sum up the top 500 account balances grouped by currencies, used in comparison query from a new SQL 2012 server and existing server to validate no changes in the new 2012 server.
Set timeout property to |set option|command|900| and to no avail.
Below is extract of the error:
System.Data.SqlClient.SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
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.SetMetaData(_SqlMetaDataSet metaData, Boolean moreInfo)
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.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet)
at dbfit.DatabaseTest.GetDataTable(Symbols symbols, String query, IDbEnvironment environment, Int32 rsNo)
at dbfit.fixture.StoreQuery.DoTable(Parse table)
at fitSharp.Fit.Operators.InterpretFlow.DoTable(Tree`1 table, Interpreter activeFixture, Boolean inFlow)
I've attempted to reduce the number of rows to check to 300 from 500 and that seems to work, however a large dataset would be ideal to highlight any discrepancies.
I'm also looking into changing the query to something else to either break it up to a smaller resultset or create an alternative
The query is below, if anyone has a better solution to optimise the query:
select
TOP 1000 fab.DateKey,be.BK_ActOId,be.PtId,be.PDesc,
be.OId,be.ODesc,be.SubOId,be.SubODesc,
rc.Currency,SUM(CASE WHEN rc.Currency = '_NA' THEN FAB.Balance ELSE 0 END) as bal_OrigCcy
,SUM(CASE WHEN rc.Currency = 'AUD' THEN FAB.Balance ELSE 0 END) as bal_AUD
,SUM(CASE WHEN rc.Currency = 'GBP' THEN FAB.Balance ELSE 0 END) as bal_GBP
,SUM(CASE WHEN rc.Currency = 'SGD' THEN FAB.Balance ELSE 0 END) as bal_SGD
,SUM(CASE WHEN rc.Currency = 'USD' THEN FAB.Balance ELSE 0 END) as bal_USD
from olap.v_FactAccB fab
inner join OLAP.v_DimCur dc on dc.CurrencyKey = fab.BalanceCurrencyKey
inner join olap.v_DimReportingCur rc on rc.CurrencyKey = fab.ReportingCurrencyKey
inner join OLAP.v_DimBusinessEntity be on be.BusinessEntityKey = fab.BusinessEntityKey
and rc.Currency in ('_NA', 'AUD', 'GBP', 'SGD','USD')
and fab.DateKey = 20130912
and fab.PlatformKey = 1
group by fab.DateKey, be.BK_ActOId, be.PId, be.PDesc
,be.OId, be.ODesc, be.SubOId, be.SubODesc, rc.Currency
order by fab.DateKey, be.BK_ActOId, be.PId, be.PDesc, be.OId, be.ODesc, be.SubOId, be.SubODesc, rc.Curr
Does anyone have alternatives other than the one above
I would rewrite your query to use a PIVOT instead of the repeated SUM(CASE... )
eg:
select * from yourtable
pivot (SUM(balance) for currency in (_NA,AUD,GBP,SGD,USD)) p
I have a stored procedure that does quite a bit of joins. The query though runs pretty fast, around 3 seconds. I just cant figure out the below error poping up every once in a while. I event cache the document that uses this query for a minute so it doesnt get ran over and over. I am using Entity Framework 5, and my stored procedure is using a CTE to do the paging. Any clues or insight?
System.Data.SqlClient.SqlException (0x80131904): 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.SqlInternalConnection.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)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
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.Common.DbCommand.ExecuteReader()
at System.Data.Objects.ObjectContext.ExecuteStoreQueryInternal[TElement](String commandText, String entitySetName, MergeOption mergeOption, Object[] parameters)
at System.Data.Objects.ObjectContext.ExecuteStoreQuery[TElement](String commandText, Object[] parameters)
at System.Data.Entity.Internal.InternalContext.ExecuteSqlQuery[TElement](String sql, Object[] parameters)
at System.Data.Entity.Internal.InternalContext.ExecuteSqlQueryAsIEnumerable[TElement](String sql, Object[] parameters)
at System.Data.Entity.Internal.InternalContext.ExecuteSqlQuery(Type elementType, String sql, Object[] parameters)
at System.Data.Entity.Internal.InternalSqlNonSetQuery.GetEnumerator()
at System.Data.Entity.Internal.InternalSqlQuery`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Tournaments.Data.Repositories.Games.GamesRepository.GetGamesPaged(IGamesCriteria criteria)
Entity Framework Method
public PagedResult<GameComplex> GetGamesPaged(IGamesCriteria criteria)
{
var results = DataContext.Database.SqlQuery<GameComplex>("EXEC [Schema].[Database] #Page, #PageSize, #SortOrder, #SortDirection, #EventId, #DivisionId, #DivisionTeamId, #Date, #SearchToken, #MemberId",
new SqlParameter("Page", criteria.Page),
new SqlParameter("PageSize", criteria.PageSize),
new SqlParameter("SortOrder", GetDataValue(criteria.SortOrder)),
new SqlParameter("SortDirection", GetDataValue(criteria.SortDirection)),
new SqlParameter("EventId", GetDataValue(criteria.EventId)),
new SqlParameter("DivisionTeamId", GetDataValue(criteria.DivisionTeamId)),
new SqlParameter("DivisionId", GetDataValue(criteria.DivisionId)),
new SqlParameter("Date", GetDataValue(criteria.Date)),
new SqlParameter("SearchToken", GetDataValue(criteria.SearchToken)),
new SqlParameter("MemberId", GetDataValue(criteria.MemberId))).ToList();
return new PagedResult<GameComplex>
{
Page = criteria.Page,
PageSize = criteria.PageSize,
Total = results.Any(q => q != null) ? results.FirstOrDefault().Total : 0,
Results = results
};
}
SQL Server Stored Procedure Parameter Signature
ALTER PROCEDURE [Schema].[Database]
#Page INT = 1,
#PageSize INT = 10,
#SortOrder NVARCHAR(100) = 'Id',
#SortDirection VARCHAR(4) = 'ASC',
#EventId INT = NULL,
#DivisionId INT = NULL,
#DivisionTeamId INT = NULL,
#Date DATETIME = NULL,
#SearchToken NVARCHAR(100) = NULL,
#MemberId INT = NULL
AS
You may need to adjust the COMMAND timeout.
See:
Set Command Timeout in entity framework 4.3
or
How to set CommandTimeout for DbContext?
EDIT
Command Timeout:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtimeout.aspx
Connection Timeout:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx
EDIT:
Another possible issue is "parameter sniffing".
http://blogs.msdn.com/b/queryoptteam/archive/2006/03/31/565991.aspx
So try one of the parameter sniffing workarounds:
ALTER PROCEDURE [Schema].[Database]
#Page INT = 1,
#PageSize INT = 10,
#SortOrder NVARCHAR(100) = 'Id',
#SortDirection VARCHAR(4) = 'ASC',
#EventId INT = NULL,
#DivisionId INT = NULL,
#DivisionTeamId INT = NULL,
#Date DATETIME = NULL,
#SearchToken NVARCHAR(100) = NULL,
#MemberId INT = NULL
AS
Declare #PageCopyOf int
Select #PageCopyOf = #Page
Declare #PageSizeCopyOf int
Select #PageSizeCopyOf = #PageSize
Declare #SortOrderCopyOf NVARCHAR(100)
Select #SortOrderCopyOf = #SortOrder
Declare #SortDirectionCopyOf VARCHAR(4)
Select #SortDirectionCopyOf = #SortDirection
Declare #EventIdCopyOf int
Select #EventIdCopyOf = #EventId
Declare #DivisionIdCopyOf int
Select #DivisionIdCopyOf = #DivisionId
Declare #DivisionTeamIdCopyOf int
Select #DivisionTeamIdCopyOf = #DivisionTeamId
Declare #DateCopyOf DATETIME
Select #DateCopyOf = #Date
Declare #SearchTokenCopyOf NVARCHAR(100)
Select #SearchTokenCopyOf = #SearchToken
Declare #MemberIdCopyOf int
Select #MemberIdCopyOf = #MemberId
And then everything below this uses/consumes the #XXXXXCopyOf variable and NOT the original variable (name).
It's worth a try.
Just a guess, but the query runs fast (3 seconds) only when it is cached. Otherwise, it takes a lot longer and exceeds your server timeout setting. Since System.Data.SqlClient is raising the exception, it is likely that the default timeout is only 15 seconds.
MSDN: "The default value is 15 seconds"
Alternatively, try the CommandTimeout property of the SQLCommand object, which defaults to 30 seconds.
CommandTimeout
We're using EntityFramework in a project that just went live. According to our logs, several users are suffering from "Invalid operation. The connection is closed", it happends about 50 times per day.
Exception looks like:
An error occurred while executing the command definition. See the inner exception for details. at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
at System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at xxxx.SelectResultToPeople(IEnumerable`1 result)
at xxxx.GetResult()
at DynamicModule.ns.Wrapped_IPeopleGetter_a853d13914444ca6ab0e016e035520c5.<People_DelegateImplementation>__0(IMethodInvocation inputs, GetNextInterceptionBehaviorDelegate getNext)
Invalid operation. The connection is closed. at System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync()
at System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket()
at System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer()
at System.Data.SqlClient.TdsParserStateObject.TryReadByte(Byte& value)
at System.Data.SqlClient.TdsParserStateObject.TryPeekByte(Byte& value)
at System.Data.SqlClient.SqlDataReader.TrySetMetaData(_SqlMetaDataSet metaData, Boolean moreInfo)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryCloseInternal(Boolean closeReader)
at System.Data.SqlClient.SqlDataReader.Close()
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, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
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.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
This exception is thrown on very specific pages, so it's not randomly distributed across the application. One of these pages makes a simple query to the database through Entity framework using a table function. The table function is named "GetPeopleNames" and our ObjectContext class is the one named "SiteEntities".
public class PeopleGetter : IPeopleGetter
{
public List<object> GetResult()
{
using (var siteEntities = new SiteEntities())
{
IQueryable<someResultEntity> result =
siteEntities.GetPeopleNames()
.SortBy("Name", "asc")
.Skip(20*query.CurrentPagingPosition)
.Take(20);
List<People> people = SelectResultToPeople(result)
return people;
}
}
private List<People> SelectResultToPeople(IQueryable<someResultEntity> result)
{
return result
.ToList()
.Select(x => new People { })
.ToList();
}
}
I can't see why it should have something to do with our fault, but i'd better mention that PeopleGetter class is resolved and created by Unity IoC container. The PeopleGetter is registered with a 'PerRquest' LifeTimeManager like this:
public class PerCallContextLifeTimeManager : HierarchicalLifetimeManager
{
private readonly string _key = string.Format("PerCallContextOrRequestLifeTimeManager_{0}", Guid.NewGuid());
public override object GetValue()
{
if (HttpContext.Current != null)
return GetFromHttpContext();
else
return base.GetValue();
}
private object GetFromHttpContext()
{
return HttpContext.Current.Items[_key];
}
public override void SetValue(object newValue)
{
if (HttpContext.Current != null)
SetInHttpContext(newValue);
else
base.SetValue(newValue);
}
private void SetInHttpContext(object newValue)
{
HttpContext.Current.Items.Add(_key, newValue);
}
public override void RemoveValue()
{
}
}
Any ideas why we're getting closed connections?
Thanks for you help!