The website we're hosting in Azure is regularly throwing exceptions when there are several users using the system at once (15-25 users) and retrieving, and posting data from and to the database. The exception has to do with the connection to the database.
We're using Azure SQL and Linq to SQL. I've checked the monitor of the database, and there's no report about failed connection and the amount of connections are well under what it should be able to handle.
I'm using a IoC container for making new instance of the datacontext and it's only one instance of the datacontext being initiated and are being used for querying all the tables.
I've digged into the eventlog and found the exceptions that are being thrown:
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 02.04.2013 11:48:45
Event time (UTC): 02.04.2013 11:48:45
Event ID: 09157c3457904c99b2b57abb44bef857
Event sequence: 5911
Event occurrence: 74
Event detail code: 0
Application information:
Application domain: /LM/W3SVC/1273337584/ROOT-1-130093075659455176
Trust level: Full
Application Virtual Path: /
Application Path: E:\sitesroot\0\
Machine name: RD00155D36AB20
Process information:
Process ID: 2420
Process name: w3wp.exe
Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
Exception type: SqlException
Exception message: The service is currently busy. Retry the request after 10 seconds. Incident ID: {26F49B32-6DD8-4149-89FA-780AF4BD74D3}. Code: 32771
A severe error occurred on the current command. The results, if any, should be discarded.
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.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)
at System.Data.Linq.DataQuery1.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source, Expression`1 predicate)
at Holte.UK.Service.People.PersonServiceCRUD.GetCompanyIdByUserProfile(Object userID)
at Holte.UK.MvcApplication.Application_PostAcquireRequestState(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Request information:
Request URL: http://www.x.x/
Request path: /
User host address: x.x.x.x
User:
Is authenticated: False
Authentication Type:
Thread account name: NT AUTHORITY\NETWORK SERVICE
Thread information:
Thread ID: 20
Thread account name: NT AUTHORITY\NETWORK SERVICE
Is impersonating: False
Stack trace: 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.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)
at System.Data.Linq.DataQuery1.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source, Expression`1 predicate)
at Holte.UK.Service.People.PersonServiceCRUD.GetCompanyIdByUserProfile(Object userID)
at Holte.UK.MvcApplication.Application_PostAcquireRequestState(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Custom event details:
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 02.04.2013 11:46:56
Event time (UTC): 02.04.2013 11:46:56
Event ID: a8dc5c34109e4a7d9f1c74bb697d86b8
Event sequence: 5905
Event occurrence: 72
Event detail code: 0
Application information:
Application domain: /LM/W3SVC/1273337584/ROOT-1-130093075659455176
Trust level: Full
Application Virtual Path: /
Application Path: E:\sitesroot\0\
Machine name: RD00155D36AB20
Process information:
Process ID: 2420
Process name: w3wp.exe
Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
Exception type: SqlException
Exception message: A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
at System.Data.SqlClient.TdsParserStateObject.ReadSni(DbAsyncResult asyncResult, TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParserStateObject.ReadNetworkPacket()
at System.Data.SqlClient.TdsParserStateObject.ReadByte()
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.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)
at System.Data.Linq.DataQuery1.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source, Expression`1 predicate)
at Holte.UK.Service.People.PersonServiceCRUD.GetCompanyIdByUserProfile(Object userID)
at Holte.UK.MvcApplication.Application_PostAcquireRequestState(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Request information:
Request URL: http://www.x.x/
Request path: /
User host address: x.x.x.x
User:
Is authenticated: False
Authentication Type:
Thread account name: NT AUTHORITY\NETWORK SERVICE
Thread information:
Thread ID: 20
Thread account name: NT AUTHORITY\NETWORK SERVICE
Is impersonating: False
Stack trace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
at System.Data.SqlClient.TdsParserStateObject.ReadSni(DbAsyncResult asyncResult, TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParserStateObject.ReadNetworkPacket()
at System.Data.SqlClient.TdsParserStateObject.ReadByte()
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.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)
at System.Data.Linq.DataQuery1.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source, Expression`1 predicate)
at Holte.UK.Service.People.PersonServiceCRUD.GetCompanyIdByUserProfile(Object userID)
at Holte.UK.MvcApplication.Application_PostAcquireRequestState(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Custom event details:
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 02.04.2013 11:20:11
Event time (UTC): 02.04.2013 11:20:11
Event ID: cbf42c3adf63405293a803cb75577076
Event sequence: 5652
Event occurrence: 71
Event detail code: 0
Application information:
Application domain: /LM/W3SVC/1273337584/ROOT-1-130093075659455176
Trust level: Full
Application Virtual Path: /
Application Path: E:\sitesroot\0\
Machine name: RD00155D36AB20
Process information:
Process ID: 2420
Process name: w3wp.exe
Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
Exception type: SqlException
Exception message: Database 'xxx' on server 'xxx' is not currently available. Please retry the connection later. If the problem persists, contact customer support, and provide them the session tracing ID of '30b6d33f-4976-44b8-a586-8bfe2bc66182'.
Login failed for user 'xxx'.
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user)
at System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe()
at System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode()
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.DataQuery1.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source, Expression`1 predicate)
at Holte.UK.Service.People.PersonServiceCRUD.GetCompanyIdByUserProfile(Object userID)
at Holte.UK.MvcApplication.Application_PostAcquireRequestState(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Request information:
Request URL: http://mail.x.x/FindInspector/Companies/128?InspectorCompaniesViewModel-page=5&InspectorCompaniesViewModel-sort=Telephone-asc
Request path: /FindInspector/Companies/128
User host address: 66.249.76.91
User:
Is authenticated: False
Authentication Type:
Thread account name: NT AUTHORITY\NETWORK SERVICE
Thread information:
Thread ID: 21
Thread account name: NT AUTHORITY\NETWORK SERVICE
Is impersonating: False
Stack trace: at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
at System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user)
at System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe()
at System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode()
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.DataQuery1.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable1 source, Expression`1 predicate)
at Holte.UK.Service.People.PersonServiceCRUD.GetCompanyIdByUserProfile(Object userID)
at Holte.UK.MvcApplication.Application_PostAcquireRequestState(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Custom event details:
These are very common transient conditions in SQL Azure. I guess you have not implemented any retry logic in your code.
Take a look, read through and implement Transient Fault Handling in your application.
Best practices for handling transient conditions in SQL Azure client applications
Using the Transient Fault Handling Application Block with SQL Azure
From my understanding, this issue can be quite random if you get it or not. There are around 600 Azure SQL installations/instances running on one SQL server. The Azure installations are sharing all the resources, mdf and ldf file (this is why you have to contact support to restore your db) on that server. Therefore, if you are unlucky and end up on a server where someone uses heavy DB operations then this will affect the performance of your Azure SQL.
If you are unlucky and get the transient error a lot can another solution be to create a new Azure SQL and move your DB over there. Hopefully this will place your new Azure SQL on a different server and with less heavy DB operations from others also using the server.
Related
I am using EntityFramework to connect to a MySql server.
I have a method which inserts many objects in the database. For this, i am generating an SQL script, which i execute it using dbContext.Database.ExecuteSqlCommand(script) method.
This workflow works ok when the EntityFramework was connected to MS SQL Server.
Now, after i moved it to MySql, it throws error when executing the script.
Incorrect syntax near '`'.
Important
The script had been generated to match MySql syntax. If i run that script in MySQL Workbench, the query is executed successfully.
I think that EntityFramework is trying to parse the script i am sending, but in the MS SQL language.
Here is the exception 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.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, 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.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
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.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass59.<ExecuteStoreCommand>b__58()
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__DisplayClass59.<ExecuteStoreCommand>b__57()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreCommand(TransactionalBehavior transactionalBehavior, String commandText, Object[] parameters)
at System.Data.Entity.Internal.InternalContext.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
at System.Data.Entity.Database.ExecuteSqlCommand(TransactionalBehavior transactionalBehavior, String sql, Object[] parameters)
at System.Data.Entity.Database.ExecuteSqlCommand(String sql, Object[] parameters)
at AppFormApp.Domain.EntityFramework.AppFormAppDatabaseService.<InsertAllObjectsAsync>d__1.MoveNext() in F:\GitRoot\AppFormApp\AppFormApp\AppFormApp.Domain\EntityFramework\AppFormAppDatabaseService.cs:line 120
UPDATE
This is the MySQL query generated
INSERT INTO `appformapp`.`appformdata`(`Id`, `ApplicationIdentifier`, `ApplicationName`, `LastSavedDate`, `LastActivity`)
VALUES (N'59bbf577-d601-4857-aabf-84b69b2d7b75', N'APP-TMH3EI', N'Test ABV', N'2016-10-17 05:56:16', N'2016-10-17 05:56:16');
The Entity Framework is already working with MySql. The error is only triggered when using dbContext.Database.ExecuteSqlCommand(script)
I am trying to upgrade an EF db schema. After the schema upgrade, the tables, indexes and keys all look correct, but when I run the application I find that all inserts fail (updates work fine) including on tables I didn't change. For example, I have a table generated by this script:
CREATE TABLE [dbo].[BlogPosts] (
[Id] int IDENTITY(1,1) NOT NULL,
[Date] datetime NOT NULL,
[Title] nvarchar(max) NOT NULL,
[Post] nvarchar(max) NOT NULL,
[Category] nvarchar(max) NOT NULL);
ALTER TABLE [dbo].[BlogPosts]
ADD CONSTRAINT [PK_BlogPosts]
PRIMARY KEY CLUSTERED ([Id] ASC);
But when I try to add a new blog post, I see the following error:
Cannot insert the value NULL into column 'Id', table 'ptytest.dbo.BlogPosts';
column does not allow nulls. INSERT fails.
Intellitrace shows the following insert:
ADO.NET:Execute Reader "insert [dbo].[BlogPosts]([Date], [Title], [Post], [Category])
values (#0, #1, #2, #3)
select [Id]
from [dbo].[BlogPosts]
where ##ROWCOUNT > 0 and [Id] = scope_identity()"
A clean DB with the new schema works fine with similar SQL. Somehow this is not treating the identity key properly in the upgraded schema. Have any idea what is going on?
Here is the stack trace from the original db.SaveChanges()
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +1753986
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5296058
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1682
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +59
System.Data.SqlClient.SqlDataReader.get_MetaData() +90
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +365
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) +1379
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +175
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +134
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10
System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues) +217
System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) +262
[UpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) +444
System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache) +146
System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options) +571
System.Data.Entity.Internal.InternalContext.SaveChanges() +323
[DbUpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Entity.Internal.InternalContext.SaveChanges() +369
System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +53
System.Data.Entity.DbContext.SaveChanges() +52
I just faced the same issue. I was importing the database from azure and it was not importing the key fields as keys(Identity). That's why i was having the issue. What i have done and worked is to use 'Export Data-tier Application' to export de database to a bacpac file and then use 'Import Data-tier Application' to create your development database. Hope it helps.
I am having the strangest problem: Everything was working fine while I was coding a new site I'm working on one night when suddenly the site could not longer connect to SQL Server. I can connect happily using SQL Server Management Studio, but the site throws the following exception.
Firewalls on this machine are completely disabled.
One issue thought is that I have SQL Server running under a local user I created. Some times when I restart the SQL Server Service to see if that resolves the problem, the service complains that the Login failed. I then re-enter the same credentials that got the service running in the first place, and then it starts up after AGAIN stating that the account has been granted login as a service rights. I have however tried using NETWORK SERVICES and LOCAL SYSTEM, both of which prompts the same exception from my site.
From time to time, however, it does work though. I'm running this on a domain connected notebook, so I'm wondering if this has something to do with it not being able to talk to the domain while I'm at home. The service account I created is however a local account.
I'm running this on IIS Express on Windows 8 Enterprise though (Just in case it's some known issue with Win8).
adding Pooling=no to the connection string also has no effect. [Ref]
Here is my connection string: Data Source=.;Initial Catalog=NotesBoard;Integrated Security=SSPI;
I've also used my Machine name instead on "." with the same outcome. Even tried FQDN.
System.Web.HttpException was unhandled by user code
HResult=-2147467259 Message=Unable to connect to SQL Server
database. Source=System.Web ErrorCode=-2147467259 WebEventCode=0
StackTrace:
at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String
fullFileName, String dataDir, String connectionString)
at System.Web.DataAccess.SqlConnectionHelper.EnsureDBFile(String
connectionString)
at System.Web.DataAccess.SqlConnectionHelper.GetConnection(String
connectionString, Boolean revertImpersonation)
at System.Web.Security.SqlRoleProvider.GetRolesForUser(String username)
at WebMatrix.WebData.SimpleRoleProvider.GetRolesForUser(String username)
at System.Web.Security.RolePrincipal.IsInRole(String role)
at ASP._Page_Views_Shared__Layout_cshtml.Execute() in d:\dtaylor\Documents\Visual Studio
2012\Projects\NotesBoard\NotesBoard\Views\Shared_Layout.cshtml:line
28
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext
pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.WebPages.WebPageBase.<>c__DisplayClass7.b__6(TextWriter
writer)
at System.Web.WebPages.HelperResult.WriteTo(TextWriter writer)
at System.Web.WebPages.WebPageBase.Write(HelperResult result)
at System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action1 body)
at System.Web.WebPages.WebPageBase.PopContext()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext
pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext
controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext preContext, Func1 continuation)
InnerException: System.Web.HttpException
HResult=-2147467259
Message=Unable to connect to SQL Server database.
Source=System.Web
ErrorCode=-2147467259
WebEventCode=0
StackTrace:
at System.Web.Management.SqlServices.GetSqlConnection(String server,
String user, String password, Boolean trusted, String
connectionString)
at System.Web.Management.SqlServices.SetupApplicationServices(String
server, String user, String password, Boolean trusted, String
connectionString, String database, String dbFileName, SqlFeatures
features, Boolean install)
at System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString)
at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String
fullFileName, String dataDir, String connectionString)
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was
not found or was not accessible. Verify that the instance name is
correct and that SQL Server is configured to allow remote connections.
(provider: SQL Network Interfaces, error: 26 - Error Locating
Server/Instance Specified)
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=20
LineNumber=0
Number=-1
Server=""
State=0
StackTrace:
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.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean
ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean
trustServerCert, Boolean integratedSecurity, Boolean withFailover)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
serverInfo, String newPassword, SecureString newSecurePassword,
Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean
withFailover)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo
serverInfo, String newPassword, SecureString newSecurePassword,
Boolean redirectedUserInstance, SqlConnectionString connectionOptions,
SqlCredential credential, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer
timeout, SqlConnectionString connectionOptions, SqlCredential
credential, String newPassword, SecureString newSecurePassword,
Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity
identity, SqlConnectionString connectionOptions, SqlCredential
credential, Object providerInfo, String newPassword, SecureString
newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString
userConnectionOptions)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions
options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo,
DbConnectionPool pool, DbConnection owningConnection,
DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection
owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions
userOptions)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
owningConnection, TaskCompletionSource1 retry, DbConnectionOptions
userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection
outerConnection, DbConnectionFactory connectionFactory,
TaskCompletionSource1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1
retry)
at System.Data.SqlClient.SqlConnection.Open()
at System.Web.Management.SqlServices.GetSqlConnection(String server,
String user, String password, Boolean trusted, String
connectionString)
InnerException:
Update:
This error is more clearly defined in a new post here
The server was not found or was not accessible. Verify that the
instance name is correct and that SQL Server is configured to allow
remote connections.
Looks like a network problem between the web server and the SQL server. Could be anything: firewall, DNS, ... Could also be intermittent problems with your SQL server.
Talk to your system administrator for more details. There's nothing wrong with your code.
I am doing a regular update table scan
Using connect1 As New MySqlConnection(ConnectLocalhost.serverString)
connect1.Open()
Dim cmd = New MySqlCommand("set net_write_timeout=99999; set net_read_timeout=99999", connect1) ' // Setting tiimeout on mysqlServer
cmd.ExecuteNonQuery()
Dim BusinessReader = selectSomeQuery("Select * from tablebusiness limit 800,10000000", connect1)
Do While BusinessReader.Read 'random exception here
Sometimes I got this error
MySql.Data.MySqlClient.MySqlException was unhandled
ErrorCode=-2147467259
Message=Fatal error encountered during data read.
Number=0
Source=MySql.Data
StackTrace:
at MySql.Data.MySqlClient.MySqlDataReader.Read()
at dreamhost.Business.InsertLocalhost() in \\work\c\business\fromwork\currentprojects\program\library\vb.net\badger.vb:line 1849
at dreamhost.Business.surFoursquare() in \\work\c\business\fromwork\currentprojects\program\library\vb.net\badger.vb:line 1939
at dreamhost.traverseweb._Lambda$__92() in \\work\c\business\fromwork\currentprojects\program\library\vb.net\traverseweb.vb:line 77
at dreamhost.buttonClicking.startAndStopClickingButton(Object sender, Action SomeSub) in \\work\c\business\fromwork\currentprojects\program\library\vb.net\buttonclicking.vb:line 45
at dreamhost.traverseweb.foursquare_Click(Object sender, EventArgs e) in \\work\c\business\fromwork\currentprojects\program\library\vb.net\traverseweb.vb:line 77
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.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at dreamhost.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: MySql.Data.MySqlClient.MySqlException
ErrorCode=-2147467259
Message=Reading from the stream has failed.
Number=0
Source=MySql.Data
StackTrace:
at MySql.Data.MySqlClient.MySqlStream.LoadPacket()
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
at MySql.Data.MySqlClient.NativeDriver.FetchDataRow(Int32 statementId, Int32 columns)
at MySql.Data.MySqlClient.Driver.FetchDataRow(Int32 statementId, Int32 columns)
at MySql.Data.MySqlClient.ResultSet.GetNextRow()
at MySql.Data.MySqlClient.ResultSet.NextRow(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlDataReader.Read()
InnerException: System.IO.IOException
Message=Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Source=MySql.Data
StackTrace:
at MyNetworkStream.HandleOrRethrowException(Exception e)
at MyNetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at MySql.Data.MySqlClient.TimedStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.BufferedStream.Read(Byte[] array, Int32 offset, Int32 count)
at MySql.Data.MySqlClient.MySqlStream.ReadFully(Stream stream, Byte[] buffer, Int32 offset, Int32 count)
at MySql.Data.MySqlClient.MySqlStream.LoadPacket()
InnerException: System.Net.Sockets.SocketException
ErrorCode=10054
Message=An existing connection was forcibly closed by the remote host
NativeErrorCode=10054
Source=System
StackTrace:
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
InnerException:
All I want is for the program to just "continue" when this thing happen. But that seems to be impossible. So I guess I need a way to make sure this bug doesn't happen. It happens randomly eery 800 entries or so.
Looks to me the connection is forcibly closed by remote host. In that case, I simply want to go where things left on and restart again.
There may be a lot of reasons why the connection drops (server load, network problem, etc). That your program is crashing suggests that your database code is not protected by a try statement. If you do something like this :
try
Using connect1 As New MySqlConnection(ConnectLocalhost.serverString)
connect1.Open()
Dim cmd = New MySqlCommand("set net_write_timeout=99999; _
set net_read_timeout=99999", connect1)
cmd.ExecuteNonQuery()
Dim BusinessReader = selectSomeQuery("Select *...", connect1)
Do While BusinessReader.Read
'random exception here'
'...more code'
Loop
End Using
Catch ex As Exception
' code breaks here on exception - recover from this point '
End Try
I won't go into a protracted dissertation on exception handling but there are a lot of resources out there if you have a look. How you deal with it will depend on your specific situation - whether to log the exception, record what the last successful operation was, whether to try to resume from where you were or whether to try to do the whole thing over again, notify the user, etc.
MSDN - Try/Catch/Finally
Doing a SQL CLR. Everything worked great in development, everything whent great in testing, then we went live, and everything broke. So it seems to have something to do with EXTERNAL_ACCESS security. I have confirmed that our database is marked as trustworthy, the database owner is a sysadmin, and the assembly is marked as EXTERNAL_ACCESS permissions. That leaves me a bit stumpted as to what could cause this error. Any other ideas on what could cause this error?
(I hid a few things that arnt critical to the error)
Error querying repository for dirty items: 'prc_XXXXXXXXXXXXXXXXXXXXX'
System.Data.SqlClient.SqlException: An error occurred in the Microsoft .NET Framework while trying to load assembly id 65536. The server may be running out of resources, or the assembly may not be trusted with PERMISSION_SET = EXTERNAL_ACCESS or UNSAFE. Run the query again, or check documentation to see how to solve the assembly trust issues. For more information about this error:
System.IO.FileLoadException: Could not load file or assembly 'myassemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=123451234151234' or one of its dependencies. Exception from HRESULT: 0x80FC3C2C
System.IO.FileLoadException:
at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.Load(String assemblyString)
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
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 ....
For some reason, even though the UI showed that the assembly had external access permissions (and it added to the database with those permissions), internally it must have thought that it didnt have that kind of access for some reason. So as a work around I ran these commands and it fixed the problem (note I tried running just the second command, and it didnt fix it):
ALTER ASSEMBLY [< AssemblyName>]
WITH PERMISSION_SET = UNSAFE
ALTER ASSEMBLY [< AssemblyName>]
WITH PERMISSION_SET = EXTERNAL_ACCESS