SQL Server Id column seems to be reset in a C# app - c#

All of a sudden the the web application for the database my nonprofit uses stopped functioning as it should. Basically I can't save any new entry. I can edit entries, but whenever I make new entry I get the error.
The app my organization uses is custom C# app. I was digging through the logs and I isolated the problem to a table which tracks user sessions.
NHibernate.Exceptions.GenericADOException: could not execute batch command.[SQL: SQL not available] ---> System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK__tUserSes__3214EC07F91B0D0B'. Cannot insert duplicate key in object 'SiteUser.tUserSession'. The duplicate key value is (7062).
That table has more than 300000 entries and the Id is clearly wrong, it's not the Id it should be. The more back I go in the logs the lower the Id number. It's like at some the Id counter was rested.
Whenever I try to add a new entry I get "System error occurred during request processing. Please contact the system administrator." which in logs looks like Cannot insert duplicate key in object 'SiteUser.tUserSession'. The duplicate key value is (7062).
I tracked down the logs to the point where the error appeared for the first time. It was actually at the beginning of the log file for the day 20180507.log
2018-05-07 00:24:29,990 WARN NHibernate.Util.ADOExceptionReporter - 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.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.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.SqlInternalTransaction.Commit()
at System.Data.SqlClient.SqlTransaction.Commit()
at NHibernate.Transaction.AdoNetTransactionFactory.ExecuteWorkInIsolation(ISessionImplementor session, IIsolatedWork work, Boolean transacted)
ClientConnectionId:c6788280-f7cc-4c3a-9bf2-514f4df84fc9
Error Number:-2,State:0,Class:11
2018-05-07 00:24:30,006 ERROR NHibernate.Util.ADOExceptionReporter - Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
2018-05-07 00:24:30,006 WARN NHibernate.Util.ADOExceptionReporter - System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out
2018-05-07 00:24:30,006 ERROR NHibernate.Util.ADOExceptionReporter - The wait operation timed out
2018-05-07 00:24:30,006 ERROR NHibernate.Base.Transaction.With - Transaction failed.
NHibernate.Exceptions.GenericADOException: error performing isolated work[SQL: SQL not available] ---> System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception: The wait operation timed out
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 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.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.SqlInternalTransaction.Commit()
at System.Data.SqlClient.SqlTransaction.Commit()
at NHibernate.Transaction.AdoNetTransactionFactory.ExecuteWorkInIsolation(ISessionImplementor session, IIsolatedWork work, Boolean transacted)
--- End of inner exception stack trace ---
at NHibernate.Transaction.AdoNetTransactionFactory.ExecuteWorkInIsolation(ISessionImplementor session, IIsolatedWork work, Boolean transacted)
at NHibernate.Transaction.AdoNetWithDistributedTransactionFactory.ExecuteWorkInIsolation(ISessionImplementor session, IIsolatedWork work, Boolean transacted)
at NHibernate.Engine.TransactionHelper.DoWorkInNewTransaction(ISessionImplementor session)
at NHibernate.Id.MultipleHiLoPerTableGenerator.Generate(ISessionImplementor session, Object obj)
at NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.FireSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.SaveOrUpdate(Object obj)
at Quiddita.Business.Statistics.Services.StatisticsBusinessService.<>c__DisplayClass1.<CreateNewUserSession>b__0() in d:\Projects\CAT – Site Database\Source\Quiddita.Business.Statistics\Services\StatisticsBusinessService.cs:line 71
at NHibernate.Base.Transaction.With.Transaction(IsolationLevel level, Action transactional) in d:\Projects\CAT – Site Database\Source\NHibernate.Base\Transaction\With.Transaction.cs:line 39
2018-05-07 00:24:30,037 ERROR Quiddita.Aspects.Statistics.MethodBoundaryAspects.NewSessionAspectAttribute - NewSessionAspectAttribute.OnSuccess failed to execute.
NHibernate.Exceptions.GenericADOException: error performing isolated work[SQL: SQL not available] ---> System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception: The wait operation timed out
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 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.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.SqlInternalTransaction.Commit()
at System.Data.SqlClient.SqlTransaction.Commit()
at NHibernate.Transaction.AdoNetTransactionFactory.ExecuteWorkInIsolation(ISessionImplementor session, IIsolatedWork work, Boolean transacted)
--- End of inner exception stack trace ---
at NHibernate.Transaction.AdoNetTransactionFactory.ExecuteWorkInIsolation(ISessionImplementor session, IIsolatedWork work, Boolean transacted)
at NHibernate.Transaction.AdoNetWithDistributedTransactionFactory.ExecuteWorkInIsolation(ISessionImplementor session, IIsolatedWork work, Boolean transacted)
at NHibernate.Engine.TransactionHelper.DoWorkInNewTransaction(ISessionImplementor session)
at NHibernate.Id.MultipleHiLoPerTableGenerator.Generate(ISessionImplementor session, Object obj)
at NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.FireSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.SaveOrUpdate(Object obj)
at Quiddita.Business.Statistics.Services.StatisticsBusinessService.<>c__DisplayClass1.b__0() in d:\Projects\CAT – Site Database\Source\Quiddita.Business.Statistics\Services\StatisticsBusinessService.cs:line 71
at NHibernate.Base.Transaction.With.Transaction(IsolationLevel level, Action transactional) in d:\Projects\CAT – Site Database\Source\NHibernate.Base\Transaction\With.Transaction.cs:line 54
at Quiddita.Business.Statistics.Services.StatisticsBusinessService.CreateNewUserSession(Nullable1 userId, String IPAddress) in d:\Projects\CAT – Site Database\Source\Quiddita.Business.Statistics\Services\StatisticsBusinessService.cs:line 74
at Quiddita.Aspects.Statistics.MethodBoundaryAspects.NewSessionAspectAttribute.OnSuccess(MethodExecutionArgs args) in d:\Projects\CAT – Site Database\Source\Quiddita.Aspects.Statistics\MethodBoundaryAspects\NewSessionAspectAttribute.cs:line 68
2018-05-07 00:24:31,056 WARN NHibernate.Util.ADOExceptionReporter - System.Data.SqlClient.SqlException (0x80131904): Violation of PRIMARY KEY constraint 'PK__tUserSes__3214EC07F91B0D0B'. Cannot insert duplicate key in object 'SiteUser.tUserSession'. The duplicate key value is (1).
The statement has been terminated.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 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)
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, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.SqlClient.SqlCommandSet.ExecuteNonQuery()
at NHibernate.AdoNet.SqlClientBatchingBatcher.DoExecuteBatch(IDbCommand ps)
ClientConnectionId:a7af4119-1d67-4f69-ae91-fc556c97768f
Error Number:2627,State:1,Class:14
2018-05-07 00:24:31,068 ERROR NHibernate.Util.ADOExceptionReporter - Violation of PRIMARY KEY constraint 'PK__tUserSes__3214EC07F91B0D0B'. Cannot insert duplicate key in object 'SiteUser.tUserSession'. The duplicate key value is (1).
The statement has been terminated.
2018-05-07 00:24:31,068 ERROR NHibernate.Event.Default.AbstractFlushingEventListener - Could not synchronize database state with session
NHibernate.Exceptions.GenericADOException: could not execute batch command.[SQL: SQL not available] ---> System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK__tUserSes__3214EC07F91B0D0B'. Cannot insert duplicate key in object 'SiteUser.tUserSession'. The duplicate key value is (1).
The statement has been terminated.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 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)
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, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.SqlClient.SqlCommandSet.ExecuteNonQuery()
at NHibernate.AdoNet.SqlClientBatchingBatcher.DoExecuteBatch(IDbCommand ps)
--- End of inner exception stack trace ---
at NHibernate.AdoNet.SqlClientBatchingBatcher.DoExecuteBatch(IDbCommand ps)
at NHibernate.AdoNet.AbstractBatcher.ExecuteBatchWithTiming(IDbCommand ps)
at NHibernate.AdoNet.AbstractBatcher.ExecuteBatch()
at NHibernate.Engine.ActionQueue.ExecuteActions()
at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session)
2018-05-07 00:24:31,068 ERROR NHibernate.Base.Transaction.With - Transaction failed.
An this is part of the StatisticsBusinessService.cs:line 74
/// <summary>
/// Creates new <c>UserSession</c> and saves the object to database.
/// </summary>
/// <param name="userId">The database id of the<see cref="User"/> associated with the Session. If <c>null</c> then the anonymous user is in question.</param>
/// <param name="IPAddress">The IPAddress of the client machine the page was accessed from.</param>
/// <returns>The newly created <c>UserSession</c> object.</returns>
public UserSession CreateNewUserSession(long? userId, string IPAddress)
{
UserSession userSession = null;
With.Transaction(() =>
{
userSession = InitializeUserSession();
if (userId.HasValue)
userSession.User = _securityService.LoadUser(userId.Value, null);
userSession.IPAddress = IPAddress;
UnitOfWork.CurrentSession.SaveOrUpdate(userSession);
});
return userSession;
}
I discovered that in the hours prior to the problem appearing we were getting a bunch of brute force password guesses. Each of those was logged in a session table. The logins kept coming but we implemented a firewall to allow only a set of IP to login. So I think we haven't been breached.
Prior to the problem the Windows server wasn't accessed in weeks. The files haven't been changed, and the database hasn't been changed. The windows hasn't been updated. Basically nothing on the system changed, but the id counter was somehow reset. I checked the database, the id columns weren't set to identity (false), so I guess the auto-increment has been implemented in the app, rather than at the database level.
I have 0 experience with C#, SQL Server and the entire Windows ecosystem. I am at a complete loss of what is going on.
We use Windows Server 2012r2, SQL Server 2014 Express, IIS 8
Any clue will be much appreciated.

What a stack trace!
If I've understood correctly your autonumber seed just got reset.
Make a backup and try this:
SELECT MAX(tUserSession) FROM SiteUser
You'll got a number, let say 123456
then reseed your autonumber with the same value:
DBCC CHECKIDENT (SiteUser, RESEED, 123456)

Related

MVC Application Getting Execution Timeout Expired

I am getting an error that the Execution Timeout Expired. I have reviewed the Server Profiler and I dont see any timeout events or long duration time. The Application calls the db to display a grip so I dont think it is related to a connection.
This is what I am seeing in the trace
RPC:Starting exec sp_executesql
SP:StmtStarting
RPC:Strating exec sp_reset_connection
There is no end time so I am not sure if this is the problem.
Why am I seeing the sp_resetConnection?
<ExceptionMessage>
Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
</ExceptionMessage>
<ExceptionType>System.Data.SqlClient.SqlException</ExceptionType>
<StackTrace>
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, Boolean shouldCacheForAlwaysEncrypted) 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.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) <SendAsync>d__1.MoveNext()
</StackTrace>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>The wait operation timed out</ExceptionMessage>
<ExceptionType>System.ComponentModel.Win32Exception</ExceptionType>
<StackTrace/>
</InnerException>
This was related to the entity framework timeout command not a SQL timeout like the Exception Type reported

how to get or set database error user friendly for user .net core

I am developing .net core web application with angular and typescript, what I need is to track error in user friendly manner.
public JsonResult Post([FromBody] Data product)
{
Response.StatusCode = 200;
try
{
repo.Insert(new TblStudentRegisteration() { RgNo = product.rgno , Name = product.name , FatherName = product.FatherName});
}
catch (Exception e)
{
Response.StatusCode = 400;
return Json(e.ToString());
}
return Json("ok");
}
Where RGNo is primary key, What I need is whenever any error raised by Database, Error it return in user friendly manner?
Like when user give RgNo two times exception throws like
"Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_tbl_StudentRegisteration'. Cannot insert duplicate key in object 'dbo.tbl_StudentRegisteration'.
The statement has been terminated.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 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, SqlDataReader ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple2 parameters)
at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded)
at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func2 operation)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable1 commandBatches, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IReadOnlyList1 entries)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList1 entriesToSave)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at RepositoryData.Repository`1.Insert(T entity) in
Where I understand that this is the problem of duplicate entries, from this given sentence.
Violation of PRIMARY KEY constraint 'PK_tbl_StudentRegisteration'. Cannot insert duplicate key in object 'dbo.tbl_StudentRegisteration'
How User understand this? until and unless we define them in a best way.
is there easiest way to do this?
EDIT
One thing I want to clear that, I know there are many ways to do this like, first check whether this RgNo exist, and then post it to DB, but there are also some others excpetion, use of ex.Message will give short form, etc, but I want something easier which makes my life easier every time.

"Current user *** have no permission.",it showed this while using SqlCacheDependency and HttpRuntime.Cache.How to solve it?

SqlCacheDependencyAdmin.EnableNotifications(connString);
SqlCacheDependencyAdmin.EnableTableForNotifications(connString, tableName);
SqlCacheDependency sqlDenpendency = new SqlCacheDependency(entryName, tableName);
HttpRuntime.Cache.Insert(key,lstData,sqlDenpendency,DateTime.Now.AddMinutes(timeout), Cache.NoSlidingExpiration);
When I used SqlCacheDependency to save some data into HttpRuntime.Cache like this,there was a runtime error as following:
Current user uu163 have no permission .
The transaction ended in the trigger. The batch has been aborted.
[SqlException (0x80131904): Current user uu163 have no permission .
The transaction ended in the trigger. The batch has been aborted.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +2442126
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5736904
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +628
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +3731
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) +940
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +272
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +280
System.Web.Caching.SqlCacheDependencyAdmin.SetupNotifications(Int32 flags, String table, String connectionString) +752
How to solve this error?

Error in SQL Server stored procedure, timeout period elapsed

I am trying to use a stored procedure in which I am sending single parameter which I sent through ADO.NET C# code.
Now the problem is the stored procedure is getting called from my dev environment and when I deploy it to production I am getting exception of timeout elapse and it never reaches to the stored procedure (I have added logs to check if stored procedure is actually hit and at what stage it causes timeout).
Exception: 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, Action1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 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)
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, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at ProjectName.ViewModel.ClassViewModel.<>c__DisplayClasse.b__d()
I have no clue what is happening over production server. Please guide me over this issue.
There are a lot of questions for same error message but I am not able to find similar scenario for issue, like stored procedure not getting executed and still it causes timeout error.
I would have included stored procedure but it is very basic stored procedure.
Please help :)
Thanks,
Nikhil Chavan.
Have you tried to run your stored procedure in SQLServer and check if it runs successfully?
Have you tried setting the SqlCommand.CommandTimeout Property?
Have you checked your connection string if it is pointing to the correct DB and it is reachable?

remote procedure call (RPC) protocol stream is incorrect

I use entityframework 5.0. I have so many test. If I run a test alone it passes, if I run this with the others eachother in the same time, it does not pass. There is no contact between the tests. Everytime one same query was sent. It would not be modified.
**query:**
insert [dbo].[Patient]
([AddressId],
[FirstName],
[LastName],
[MiddleName],
[MuthersName],
[Sex],
[BirthDate],
[TAJNumber],
[Height],
[Weight],
[PhoneMobil],
[PhoneHome],
[Email],
[OtherDisease])
values (13 /* #0 */,
'Peter' /* #1 */,
'Peter' /* #2 */,
'Peter' /* #3 */,
'Maria' /* #4 */,
1 /* #5 */,
'1991-07-04T00:00:00' /* #6 */,
'5464845' /* #7 */,
170 /* #8 */,
66 /* #9 */,
'00456249864' /* #10 */,
'00456249864' /* #11 */,
'alma22#mailmetrash.com' /* #12 */,
null)
select [Id]
from [dbo].[Patient]
where ##ROWCOUNT > 0
and [Id] = scope_identity()
**WARN:**
System.Data.SqlClient.SqlException (0x80131904): The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Parameter 9 ("#6"): The supplied value is not a valid instance of data type datetime2. Check the source data for invalid values. An example of an invalid value is data of numeric type with scale greater than precision.
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(CommandBehavior behavior)
at HibernatingRhinos.Profiler.Appender.ProfiledDataAccess.ProfiledCommand.ExecuteDbDataReader(CommandBehavior behavior)
ClientConnectionId:c184fe10-8d28-4b0b-96bf-395796cd0e29
**exception:**
Test Name: VM_PatientRegistration_Insert
Test FullName: **Insert
Test Source: **line 23
Test Outcome: Failed
Test Duration: 0:00:01,0018114
Result Message:
Test method TandoCare.Desktop.Test.ViewModel.PatientRegistrationViewModelTest.VM_PatientRegistration_Insert threw exception:
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Parameter 9 ("#6"): The supplied value is not a valid instance of data type datetime2. Check the source data for invalid values. An example of an invalid value is data of numeric type with scale greater than precision.
Result StackTrace:
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(CommandBehavior behavior)
at HibernatingRhinos.Profiler.Appender.ProfiledDataAccess.ProfiledCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
--- End of inner exception stack trace ---
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
--- End of inner exception stack trace ---
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at TandoCare.Infrastructure.Data.UnitOfWork.UnitOfWorkBase`1.Save() in ** at TandoCare.Desktop.Test.ViewModel.PatientRegistrationViewModelTest.VM_PatientRegistration_Insert() in *** :line 55
I faced this problem when I tried to insert a new row with a column of float data type. The same exception as yours was thrown when I tried to insert Infinity or NaN values, which are not supported by SQL Server.
if you're using Entity Framework, It's recommended to use the HibernatingRhinos assembly. You can trace generated queries and detect the parameter that caused your problem.
SQL Profiler will not help you if your using TPT (Table-Per-Type).
I was issuing a SQLCommand with a select command and I had the error :
The incoming tabular data stream (TDS) remote procedure call (RPC)
protocol stream is incorrect. The RPC name is invalid.
Because I was calling a SQLCommand with a command type of CommandType.StoredProcedure.
Changing this to CommandType.Text fixed my problem.
System.Data.SqlClient.SqlCommand result = new SqlCommand(GetSQLSelectCommande());
if (FromDate == default(DateTime) || isEqualDay(FromDate, DateTime.Now))
{
FromDate.AddMonths(-1);
}
ToDate = new DateTime(ToDate.Year, ToDate.Month, ToDate.Day, 23, 59, 59);
result.Parameters.Clear();
result.CommandType = CommandType.Text;
result.Parameters.Add("#IdClient", SqlDbType.Int).Value = this.IdClient;
result.Parameters.Add("#dateDebut", SqlDbType.DateTime).Value = this.FromDate;
result.Parameters.Add("#dateFin", SqlDbType.DateTime).Value = this.ToDate;
result.Parameters.Add("#langue", SqlDbType.Int).Value = (Offix.Culture.GetCulture() == Offix.EnumLangue.ofxFrancais ? 5 : 3);
I think the issue is coming from your parameter #6. It seems that the format is invalid.
Have you tried some thing like this to create the date? :
new DateTime(1991,07,04).ToShortDateString()

Categories

Resources