Provider session provider error 19

We are getting the following error during our performance test run. A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical co...

We are getting the following error during our performance test run.
A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 — Physical connection is not usable)
We are using Azure SQL database and using System.Data.SqlClient from System.Data (.NET 4.8)

Exception message:
SQL Server error(s): FatalError.
Error Details : -1 — A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 — Physical connection is not usable)
Severity : 20
State : 0
Server : asr-perf-sql-tx3psh.database.windows.net
Procedure : marker.WorkItem_Details_Get_General, line 0
Provider : .Net SqlClient Data Provider

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.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, 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, TaskCompletionSource1 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.SqlClient.SqlCommand.ExecuteReader()
at Assessor3.Gateway.Framework.Data.DataAccessBase.ExecuteReader(SqlConnection conn, CommandType type, String cmdText, SqlParameter[] parameters)

System.Data.SqlClient
.NET target: Framework 4.8

  • Remove From My Forums
  • Question

  • I have asked similar question on IIS and SQL Server Forums, but I am yet to get a solution.  I have realized this is highly related to Entity Framework.  Let me explain.

    The following code generates the error about once every two days:

    using (Models.FooEntities context = new Models.FooEntities())
    {
        context.CommandTimeout = 300;
        Models.tblFoo foo = new Models.tblFoo();
        foo.DateTime = DateTime.Now;
        ...
        try
        {
            context.SaveChanges();
        }
        catch (EntityDataSourceValidationException edsve)
        {
            ...
        }
        catch (Exception ex)
        {
            //"A transport-level error has occurred when receiving results from the server"  is caught here
        }
    }

    Once this happens, the only way to remedy it is rebooting the hosting machine — a Windows 7 box. None of the following would help:

    1. Recycling app pools.
    2. Restarting the web application.
    3. Restarting IIS.
    4. Restarting SQL server.

    Here may be the most important fact: only web applications using Entity Framework generate this error.
     When it happens, other applications that do not use Entity Framework work fine with the same SQL database.

    Is there a way to reset Entity Framework without rebooting the machine?


    Hong

Answers

  • Hi Fred, it has been working fine since I added the following to the connection string 2 days ago:

    Connection Lifetime=3;Max Pool Size=3

    I think I will be able to declare this is a remedy for the problem by the end of tomorrow if the problem will not occur.  I will report back.


    Hong

    • Marked as answer by

      Thursday, October 31, 2013 9:38 AM

We have a program written in C# using Visual Studio 2012 and .NET 4.0 / .NET 4.5. It rapidly executes many queries in Microsoft SQL Server 2008 R2 and then exits. Executed query count varies from several hundred to many thousand.

Today, when executed particular task with very many queries, I noticed an error in the log file:
A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)
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.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.ReadBuffer()
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.ExecuteReader()
at MyTestApp.Program.QueryOneLineOneValue(String cmdText)
at MyTestApp.Program.Worker(String[] args)
at MyTestApp.Program.Main(String[] args)

At first, the error message lead me to think that something is wrong with the network. “Physical connection is not usable”… anyway it didn’t say anything useful… and SQL Server log file didn’t have anything useful either.

A quick Google search revealed that many people have the same problem:

  1. Minimizing Connection Pool errors in SQL Azure — it has code example with an serious bug, and it leads to Reliability Update 1 for the .NET Framework 4 which may help judging from the description – “Issue 14 – A transport-level error has occurred when sending the request to the server.” I didn’t tried it, mostly because it talks about Azure services.
  2. Discussion in the Microsoft SQL Server Database Engine forum which leads to MSDN article about SQL Server Connection Pooling which again does not help much, because I have only one connection in my application.
  3. And a couple not very useful pages from the Stack Overflow: One suggests to call ClearAllPools and another one is about Azure again.

Again, I had to find solution by myself. I looked at the code and didn’t see anything unusual. I did another run under the VS debugger, and after a while the same exception was thrown. Looking under debug log file, I noticed that program stopped in the same place that in the production server. And by the same place I mean, the same amount of SQL commands were executed.

I quickly put a counter on right before SQL command execution and found that .NET throws exception always on 32767 command. 32767 is very familiar constant for programmers, and it is obvious that some resource leakage is happening. A quick glance at the code again revealed that a call to Close or Using statement is missing.

SqlConnection conn;

   
private static void QueryOneLineOneValue(String cmdText)
{
      string q = "SELECT ... FROM cmdText...";
      SqlCommand command =
         new SqlCommand(q, conn);

   
      SqlDataReader reader = command.ExecuteReader();

   
      while (reader.Read())
      {
         //do something with the data...
      }

   
      reader.Close(); //this line was missing
}

When I am trying to Load page of my clients web application, which has shared connection string, I am getting the below error

A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.SqlClient.SqlException: A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)

/transport-level-error-has-occurred-when-receiving-results-from-the-server-provider-Session-Provider-error.png

What’s the issue?

Asked by:- bhanu

0

: 7132
At:- 1/30/2018 11:57:10 AM

SQL
sql-server
transport-level error


3 Answers

It looks like when fetching the results from server(share connection), database connection get’s closed before it returns results to your web application, this can occur due to when you pickup the shared connection string and try to execute it’s not able to reach the database or connection to sql server got interrrupted, if you are using Visual Studio, restart it or your local IIS and try again. If facing this issue on live website, simply resetting your application pool for your web site should recycle the connection pool should work.

If the above solution doesn’t work, try restarting your SQL server(if using it locally) or if you are not using IIS end all of the debugger processes: WebDev.WebServer40.EXE which may solve your issue.

If you are still facing issue after trying all the above steps, please read moer about it here
https://blogs.msdn.microsoft.com/spike/2009/04/16/a-transport-level-error-has-occurred-when-sending-the-request-to-the-server-provider-tcp-provider-error-0-an-existing-connection-was-forcibly-closed-by-the-remote-host/

2

At:- 1/31/2018 10:44:19 AM

Yes, I see my connection was interrupted from server, thanks for your answer
0

By : bhanu — at :- 2/7/2018 4:54:43 PM

profileImage
Answered by:- pika

Try to restart your Visual Studio and SQL server, and check, I had similar issue once, restarting Visual Studio solved it.

1

At:- 2/12/2018 6:53:35 AM

profileImage
Answered by:- pika

Would like to mention transport-level error occurs when you are receiving data from SQL Server and the connection is disconnected.

If it happens in production, resetting your application pool for your web site should recycle the connection pool.

It can also be due to the Timeout expired error, which is usually thrown when a sql query takes too long to run.

So you can check

  • Restart IIS
  • Restart machine
  • Optimize SQL queries.

For better output.

0

At:- 2/21/2022 2:57:23 PM

«Ошибка: 19 — физическое соединение невозможно использовать» с доступом OWIN в базе данных Azure

Я перепробовал все другие сообщения об ужасной «ошибке 19» и обнаружил, что те немногие, у которых есть ответы, не подходят или не помогают, отсюда и этот новый пост. Это очень серьезная потенциальная проблема для всех пользователей Azure + EF.

Первое появление:

Я использую последнюю версию всего в проекте VS2013 EF6.1 Razor (пакеты перечислены в конце). База данных размещена в SQL Azure.

После запуска моего веб-приложения несколько раз (в среде разработки) я получаю следующую ошибку: A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 — Physical connection is not usable)

Линия, на которой он умирает, всегда такая:

Я понимаю, что ошибка связана с пулом соединений (и исчерпанием соединений), но я нигде не могу обнаружить утечку.

Когда я получаю доступ к членству в OWIN и другим функциям базы данных в приложении, у меня есть DatabaseContoller , от которого наследуются все остальные контроллеры. Это создает все соответствующие компоненты и избавляется от них.

DatabaseController.cs

Пакеты установлены

Предполагая, что это утечка соединения, как я могу отследить источник утечки?

Если вам нужна дополнительная информация, просто спросите.

Обновление: 22 мая 2014 г. Предлагается вторая награда

У меня все еще та же проблема, с некоторыми небольшими изменениями проекта, внесенными с момента последней публикации, поэтому я опубликую последние подробности ниже.

Я добавил Connection Lifetime=3;Max Pool Size=3; в свои строки подключения на основе этот пост.

Обновление: 23 мая 2014 г. ошибка все еще возникает

На следующий день после отладки несколько десятков раз эта ошибка вернулась.

Обновление: 11 июня 2014 г.

После двух наград и бесчисленных расследований Google (на этот вопрос нет реального ответа), я должен предположить, что это недостаток Entity Framework 6, который я каким-то образом вызываю.

Дополнительная информация:

У меня была такая же ошибка в проекте WinForm, подключитесь к Azure. В этом случае я случайно не очищал список объектов после добавления каждых 20 новых элементов.

Каждый раз, когда код запускался, он добавлял еще 20 записей и обновлял поле DateModified для всех из них. К тому времени, когда он достиг 1700 обновляемых записей, он внезапно выдал ужасную «ошибку 19 — Физическое соединение не используется». После этого мне нужно было перезапустить мой отладочный IIS, чтобы он вообще заработал.

Очевидно, что код подвергся огромному количеству обновлений, и, возможно, что-то в этом поможет кому-то придумать что-нибудь .

2 ответа

Ошибка 19 не является ошибкой связи! (или не просто ошибка связи)

Просто убедитесь, что в вашем запросе LINQ to SQL есть все необходимые вызовы .Include(x=>x.ForeignTable) !

Обновлено в августе 2015 г. (возможное решение, по крайней мере для некоторых сценариев):

У нас только что был 100% повторный случай этой проблемы, который мы смогли решить с помощью тестирования методом проб и ошибок, так что это вполне может быть решением или, по крайней мере, дать подсказки о том, что искать.

Сценарий:

  • Ошибка возникала только в сборках выпуска, работающих под IIS. Этого не происходило при отладке или в IIS Express.
  • Мы также включили профилирование SQL, чтобы увидеть, когда и где на самом деле был поражен сервер.
  • Рассматриваемый запрос извлекал совпадающие записи, а затем создавал модели представления в итерации результатов foreach (т. Е. Ленивая оценка). Модель представления зависела от значения в связанной таблице запрашиваемого объекта.

Тестирование:

Первая попытка : удалите все сложные фильтры по запросу.

  • Результат: по-прежнему не удалось с ошибкой 19

Вторая попытка: добавьте ToList() в запрос, чтобы заставить запрос выполняться до завершения немедленно.

  • Результат: успешно . (очевидно, что здесь что-то происходит)

Третья попытка: удалите ToList() и добавьте .Include(x=>x.ForeignTable) в запрос, чтобы принудительно включить соответствующие данные.

  • Результат:успех !

Моя новая теория:

Если вы случайно пропустите Include сторонней таблицы, EF случайно не сможет получить связанные данные при ленивом вычислении. Это может привести к печально известной ошибке 19.

Поскольку в Identify Framework существуют отношения внешнего ключа, вы можете предположить, что также отсутствует .Include() или эквивалент в запросе где-то в OWIN. Это может быть причиной случайной проблемы при использовании OWIN или других запросов.

Примечания:

  • Ключевым моментом, который следует убрать, является то, что ошибка 19 не является ошибкой связи. Запросы попадают на SQL-сервер. На стороне клиента возникает проблема, связанная с невозможностью получить связанные данные.

Пауза для аплодисментов (мы очень рады, что это нашли) :)

Обновлено 28 августа 2015 г .:

Только что сегодня снова произошла ужасная ошибка 19, связанная с подключением к локальной базе данных SQL (обычно это была проблема с Azure для меня). Основываясь на результатах выше, я просто добавил оператор .Include(x=>x.ForeignTable) там, где это необходимо, и проблема исчезла! Кажется, это проблема того, что EF не всегда может лениво загружать информацию о связанных таблицах.

Вы пробовали SqlAzureExecutionStrategy? Похоже, что соединение прервано, но с этой стратегией EF следует автоматически повторить попытку повторного подключения.

Источник

“error: 19 — Physical connection is not usable” with OWIN access in Azure database

I have tried all the other postings on the dreaded «error 19» and found that the few with answers do not apply or do not help, hence this new post. This is a very serious potential problem for all Azure+EF users.

First occurrence:

I am using the latest version of everything in a VS2013 EF6.1 Razor project (packages listed at the end). The database is hosted on SQL Azure.

After running my webapp a few time (in a dev environment) I get this error: A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 — Physical connection is not usable)

The line it dies on is always this:

I gather the error relates to connection pooling (and running out of connections), but I cannot spot a leak anywhere.

As I access OWIN membership and other database features throughout the app I have a DatabaseContoller from which all other controllers inherit. This creates all the relevant components and disposes of them.

DatabaseController.cs

Packages installed

Assuming it is a connection leak, how can I track down the source of the leak?

If you need any more information, just ask.

Update: 22 May 2014 Second Bounty offered

I still have the same problem, with some slight project changes made since last posting, so will post latest details below shortly.

I have added Connection Lifetime=3;Max Pool Size=3; to my connection strings, based on this post.

Update: 23 May 2014 Error still occurs

The next day, after debugging a few dozen times, this error returned.

Update: 11 June 2014

After 2 bounties and countless Google investigations (no real answer to this), I have to assume it is a flaw in Entity Framework 6, that I am somehow causing to appear.

More Information:

I just had the same error in a WinForm project, connect to Azure. In this instance I was accidentally not clearing an entity list after each 20 new items were added.

Every time the code ran it added 20 more records and updated the DateModified field on all of them. By the time it hit 1700 records being updated it suddenly gave the dreaded «error 19 — Physical connection is not usable». After that I needed to restart my debug IIS for it to work at all.

Obviously the code had run a massive number of updates, and maybe something about this will help someone think of something.

Источник

A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 — Physical connection is not usable) — Azure SQL Database #19657

Hi all,
We migrated on-prem SQL databases to Azure SQL Databases and after migration, during monitoring the services we see exceptions stating «A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 — Physical connection is not usable).». We are getting this error intermittently. The consumer service itself is in on-prem whilst the database is in Azure.

There is an issue(#7800) created and closed but it didn’t help me to solve the issue.

The stack trace :

Exception Details:
ExceptionDetail.Message:A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 — Physical connection is not usable)
ExceptionDetail.Number:-1
ExceptionDetail.Source:.Net SqlClient Data Provider
ExceptionDetail.Type:System.Data.SqlClient.SqlException
SourceContext:Microsoft.EntityFrameworkCore.Query
ContextType:IdentityServer4.EntityFramework.DbContexts.ConfigurationDbContext

What we applied to solve the issue:
1-Apply custom execution strategy
2-Apply connection resiliency scenarios
3-upgrade NuGet packages
4-change connection policy from «Default» to «Redirect» and open required ports as Microsoft Azure team suggested

Any help will be very appreciated.

Thanks in advance.

The text was updated successfully, but these errors were encountered:

Источник

Cannot get rid of «physical connection is not usable» exception

I am about to shoot myself. Spent few weeks now trying to solve this issue. We have an ASP.NET MVC 4 web app that uses SQL Server 2012 and Entity Framework as ORM and Unity for IoC. Web app is hosted on Amazon EC2. I started getting «Physical connection is not usable» exception. It happens few times a day. I searched many articles and forums and tried all the possible suggestions:

  • Tried removing pooling from connection string «Polling=False»
  • Tried limiting pool size and connection lifetime
  • Tried changing LifetimeManager of Unity to HierarchicalLifetimeManager, PerRequestLifetimeManager. Also made sure entities context is disposed after the end of request
  • Removed all TransactionScope references

When exception happens, the only way to restore application is to restart server, which is very bad.

This is full exception:

A transport-level error has occurred when sending the request to the server. (provider: Session Provider, error: 19 — Physical connection is not usable)

9 Answers 9

I confirm now, by changing connection string on the server to use «.» for data source instead of domain name, exception seem to have disappeared. Very weird as domain name used to work before. Must be some sort of update on SQL Server

I know this is an old post but I’ve recently had a horrible time with this error and there were no solutions on any of the blogs.

Specific details about my problem: ASP.NET web app with target .NET framework 4.5, MVC ver. 5.2.3, Entity ver. 6.0.0.0, MS SQLServer Express 2014. My dev system is running Windows 7 Pro SP1.

Symptoms: The error came on suddenly (I had not worked on the project for almost three weeks, at which time it had functioned fine). When I started the app, after logging the user in, the second query sent to the database by the Entity framework ALLWAYS generated the error «A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 — Physical connection is not usable)«. It did not matter which table was queried. The error was not intermittent and rebooting the server did not help. The error occurred using IIS and IIS express.

SqlConnection.ClearAllPools() prevented the error for ONE query only, and I did not want to add this before every single Entity call in the program. I tried every single solution on all the blogs to no avail, even solutions to other Transport-Level Errors. I rolled back package updates for my references in an attempt to get back to a working state. Nothing!

The Solution: The culprit was Microsoft SQL Server 2014 SP1 Security update (KB3070446)!! I rolled back this update and everything worked like a charm!

I lost two days of dev work dealing with this problem, hopefully this post can help someone else avoid this agony!

Источник

A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 — Physical connection is not usable) — Azure SQL Database #394

Hi all,
We migrated on-prem sql databases to Azure SQL Databases and after migration, during monitoring the services we see exceptions stating «A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 — Physical connection is not usable).». We are getting this error intermittently. The consumer service itself is in on-prem whilst the database is in Azure.

Technical Details:
Dot.net Core Version: .net core 2.2.0
SqlClient Version: 4.5.1
Sqlserver : Azure Sql Server

The stack trace :

Exception Details:
ExceptionDetail.Message:A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 — Physical connection is not usable)
ExceptionDetail.Number:-1
ExceptionDetail.Source:.Net SqlClient Data Provider
ExceptionDetail.Type:System.Data.SqlClient.SqlException
SourceContext:Microsoft.EntityFrameworkCore.Query
ContextType:IdentityServer4.EntityFramework.DbContexts.ConfigurationDbContext

What we applied to solve issue:
1-Apply custom execution strategy
2-Apply connection resiliency scenarious
3-upgrade nuget packages
4-change connection policy from «Default» to «Redirect» and open required ports as Microsoft Azure team suggested

Any help will be very appreciated.
Thanks in advance

The text was updated successfully, but these errors were encountered:

Источник

Понравилась статья? Поделить с друзьями:
  • Psql on error stop
  • Psql exit on error
  • Psql error relation couriers does not exist
  • Psql error fatal password authentication failed for user postgres
  • Psql error could not connect to server fatal role root does not exist