Net sql data provider ошибка

By default login failed error message is nothing but a client user connection has been refused by the server due to mismatch of login credentials. First task you might check is to see whether that user has relevant privileges on that SQL Server instance and relevant database too, thats good. Obviously if the necessary prvileges are not been set then you need to fix that issue by granting relevant privileges for that user login.

Althought if that user has relevant grants on database & server if the Server encounters any credential issues for that login then it will prevent in granting the authentication back to SQL Server, the client will get the following error message:

Msg 18456, Level 14, State 1, Server <ServerName>, Line 1
Login failed for user '<Name>'

Ok now what, by looking at the error message you feel like this is non-descriptive to understand the Level & state. By default the Operating System error will show ‘State’ as 1 regardless of nature of the issues in authenticating the login. So to investigate further you need to look at relevant SQL Server instance error log too for more information on Severity & state of this error. You might look into a corresponding entry in log as:

2007-05-17 00:12:00.34 Logon     Error: 18456, Severity: 14, State: 8.
or

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

As defined above the Severity & State columns on the error are key to find the accurate reflection for the source of the problem. On the above error number 8 for state indicates authentication failure due to password mismatch. Books online refers: By default, user-defined messages of severity lower than 19 are not sent to the Microsoft Windows application log when they occur. User-defined messages of severity lower than 19 therefore do not trigger SQL Server Agent alerts.

Sung Lee, Program Manager in SQL Server Protocols (Dev.team) has outlined further information on Error state description:The common error states and their descriptions are provided in the following table:

ERROR STATE       ERROR DESCRIPTION
------------------------------------------------------------------------------
2 and 5           Invalid userid
6                 Attempt to use a Windows login name with SQL Authentication
7                 Login disabled and password mismatch
8                 Password mismatch
9                 Invalid password
11 and 12         Valid login but server access failure
13                SQL Server service paused
18                Change password required


Well I'm not finished yet, what would you do in case of error:

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

You can see there is no severity or state level defined from that SQL Server instance’s error log. So the next troubleshooting option is to look at the Event Viewer’s security log [edit because screen shot is missing but you get the

idea, look in the event log for interesting events].

===================================

Cannot connect to ACER-PC.

===================================

Login failed for user ‘sa’. (.Net SqlClient Data Provider)

——————————
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=18456&LinkId=20476

——————————
Server Name: ACER-PC
Error Number: 18456
Severity: 14
State: 1
Line Number: 65536

——————————
Program Location:

   at System.Data.SqlClient.SqlInternalConnection.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.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
   at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
   at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
   at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
   at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
   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 Microsoft.SqlServer.Management.UI.ConnectionDlg.Connector.ConnectorThread()

  • Changed type

    Monday, February 12, 2018 5:06 PM
    question

Hi, I just installed SQL Server 2008 full edition on my machine but am not able to connect to the default MSSQLSERVER database.  When I set it up, I specified Windows authentication.  And so that is how I try to connect to it.  And even though I see the MSSQLSERVER service in the Sql Server Configuration Manager, I still can’t connect to it.  I tried modifying the protocols and even enabling FILESTREAM, but none of this helped.  How can I fix this?

===================================

Cannot connect to D610-MMSSQLSERVER.

===================================

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: 25 — Connection string is not valid) (.Net SqlClient Data Provider)

——————————

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=87&LinkId=20476

——————————

Error Number: 87

Severity: 20

State: 0

——————————

Program Location:

at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)

at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)

at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, SqlConnection owningObject)

at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)

at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)

at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)

at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)

at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)

at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)

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 Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.ObjectExplorer.ValidateConnection(UIConnectionInfo ci, IServerType server)

at Microsoft.SqlServer.Management.UI.ConnectionDlg.Connector.ConnectionThreadUser()

ИТ База знаний

Полезно

— Узнать IP — адрес компьютера в интернете

— Онлайн генератор устойчивых паролей

— Онлайн калькулятор подсетей

— Калькулятор инсталляции IP — АТС Asterisk

— Руководство администратора FreePBX на русском языке

— Руководство администратора Cisco UCM/CME на русском языке

— Руководство администратора по Linux/Unix

Навигация

Серверные решения

Телефония

FreePBX и Asterisk

Настройка программных телефонов

Корпоративные сети

Протоколы и стандарты

Популярное и похожее

Пошаговый ввод в домен Windows 10

Погружение в Iptables – теория и настройка

Как сбросить root пароль на MySQL?

Передача файлов по RDP – это просто

Решаем ошибку 18456 в SQL

2 минуты чтения

С нетерпением спешим поделиться с тобой способом решения ошибки 18456 — Login Failed for User (Microsoft SQL Server, Error: 18456). Определим пользователя, который имеет права доступа к SQL и создадим новую учетную запись.

Если вы только столкнулись с проблемой, вам необходимо понять, какой пользователь имеет права на подключение к SQL. Как правило, это юзер, под которым был установлен SQL. Об этом и поговорим.

Получаем доступ

Запустите Server Manager в операционной системе. Переходим в раздел ToolsComputer Management:

Раскрываем список Local Users and Groups, в разделе Computer ManagementSystem Tools и нажимаем на Users.

Смотрим описание к пользователям. Находим описание юзера, которое начинается с Built-in account for administering the computer…. С большой вероятностью, это именно тот аккаунт, с которого мы получим доступ к SQL.

Выходим из под текущего юзера в операционной системе, заходим под пользователем Administrator. Пробуем подключиться – работает.

Даем права нужному пользователю

Подключившись к SQL Management Studio под пользователем Administrator, слева, в меню навигации, раскрываем список под именем сервера, переходим в раздел SecurityLogins. Нажимаем на Logins правой кнопкой мыши и нажимаем New Login…:

Нажимаем на кнопку Search:

В появившемся окне укажите имя пользователя, которому необходимо предоставить права администратора SQL. Нажимаем OK:

В разделе Server Roles выбираем sysadmin и жмем OK:

В разрешениях отмечаем Connect SQL и жмем OK.

Теперь, выходим из под пользователя Administrator в ОС и подключаемся под пользователем, с которым мы изначально пытались подключиться. Готово.

Полезна ли Вам эта статья?

Пожалуйста, расскажите почему?

Нам жаль, что статья не была полезна для вас 🙁 Пожалуйста, если не затруднит, укажите по какой причине? Мы будем очень благодарны за подробный ответ. Спасибо, что помогаете нам стать лучше!

Подпишитесь на нашу еженедельную рассылку, и мы будем присылать самые интересные публикации 🙂 Просто оставьте свои данные в форме ниже.

Источник ошибки net sqlclient data provider

Вопрос

Объект: Виртуальный сервер Windows Server 2008 R2 SE на нем SQL Server 2008 R2 64x

Позавчера встало обновление KB2979597, но со второго раза. Безумно долгая перезагрузка, но терпеливо ждал до 5-ти утра. В итоге получил проблему со входом Management Console

Error: 18401
Login failed for user ‘ ‘. Reason: Server is in script upgrade mode. Only administrator can connect at this time.

Проделал это: https://support.microsoft.com/en-us/kb/2163980 (Исправил: поскольку дело было бессонной ночью, описанное здесь проделал не до конца. Возможно дело в этом).

не помню перезагружался или нет, службу SQL сервер отрестартил. Консоль запустилась, клиентские подключения тоже заработали. Далее система осталась без изменений.

На настоящий момент клиентские подключения работают, к консоли подключиться можно, но при попытке раскрыть перечень баз получаем:

Не удалось получить данные по этому запросу. (Microsoft.SqlServer.Management.Sdk.Sfc)

в Microsoft.SqlServer.Management.Sdk.Sfc.Enumerator.Process(Object connectionInfo, Request request)
в Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItemBuilder.NavigableItemBuilderDataReader.RunQuery()
в Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItemBuilder.NavigableItemBuilderDataReader.Process()
в Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItemBuilder.NavigableItemBuilderDataReader.get_PropertyNames()
в Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItemBuilder.BuildDynamicItemWithQuery(IList`1 nodes, INodeInformation source, INavigableItem sourceItem, String urnQuery, Boolean registerBuilder, Boolean registerBuiltItems)
в Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItemBuilder.BuildDynamicItem(IList`1 nodes, INodeInformation source, INavigableItem sourceItem, IFilterProvider filter)
в Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItemBuilder.Build(IList`1 nodes, INodeInformation source, INavigableItem sourceItem, IFilterProvider filter)
в Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.NavigableItem.RequestChildren(IGetChildrenRequest request)
в Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.ExplorerHierarchyNode.BuildChildren(WaitHandle quitEvent)

При выполнении инструкции или пакета Transact-SQL возникло исключение. (Microsoft.SqlServer.ConnectionInfo)

в Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteReader(String sqlCommand, SqlCommand& command)
в Microsoft.SqlServer.Management.Smo.ExecuteSql.GetDataReader(String query, SqlCommand& command)
в Microsoft.SqlServer.Management.Smo.DataProvider.SetConnectionAndQuery(ExecuteSql execSql, String query)
в Microsoft.SqlServer.Management.Smo.ExecuteSql.GetDataProvider(StringCollection query, Object con, StatementBuilder sb, RetriveMode rm)
в Microsoft.SqlServer.Management.Smo.ExecuteSql.ExecuteWithResults(StringCollection query, Object con, StatementBuilder sb)
в Microsoft.SqlServer.Management.Smo.SqlObjectBase.FillData(ResultType resultType, StringCollection sql, Object connectionInfo, StatementBuilder sb)
в Microsoft.SqlServer.Management.Smo.SqlObjectBase.FillDataWithUseFailure(SqlEnumResult sqlresult, ResultType resultType)
в Microsoft.SqlServer.Management.Smo.SqlObjectBase.BuildResult(EnumResult result)
в Microsoft.SqlServer.Management.Smo.SqlObjectBase.GetData(EnumResult erParent)
в Microsoft.SqlServer.Management.Sdk.Sfc.Environment.GetData()
в Microsoft.SqlServer.Management.Sdk.Sfc.Environment.GetData(Request req, Object ci)
в Microsoft.SqlServer.Management.Sdk.Sfc.Enumerator.GetData(Object connectionInfo, Request request)
в Microsoft.SqlServer.Management.Sdk.Sfc.Enumerator.Process(Object connectionInfo, Request request)

Недопустимое имя объекта «msdb.dbo.syspolicy_configuration». (.Net SqlClient Data Provider)

——————————
Имя сервера: SDB
Номер ошибки: 208
Серьезность: 16
Состояние: 1
Номер строки: 3

в Microsoft.SqlServer.Management.Common.ConnectionManager.ExecuteTSql(ExecuteTSqlAction action, Object execObject, DataSet fillDataSet, Boolean catchException)
в Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteReader(String sqlCommand, SqlCommand& command)

Не открываются не только базы. Гугление пока ни к чему не привело. Поиск по «microsoft sql server ошибка 208» тоже дает несхожие с моей ситуацией результаты.

Источник ошибки net sqlclient data provider

Александр Жевелев
Автор

Сообщений: 2672
Откуда: Новосибирск

с приложением одновременно работают 10-50 пользователей, иногда (и даже не каждый день) от одного или нескольких пользователей прилетает такая ошибка:

Собственно, вопрос в заглавии поста.

PaulWist

1. Причин разрыва соединения может быть масса (для начала посмотри в логах сервера на предмет таймаута, deadlock-a итп).

2. Писать аналог фоксовской SQLIDLDISCONNECT(), те проверять если соединение «умерло», то заново коннектиться (если хранишь логин-пароль, «в тихую», если делаешь правильно и не хранишь логин-пароль, то дать соединиться юзеру интерактивно) и выполнять последоватеность команд заново.

Igor Korolyov

blogs.msdn.com
От те цельная куча возможных причин.

Александр Жевелев
Автор

Сообщений: 2672
Откуда: Новосибирск

Влад Колосов

Сообщений: 22664
Откуда: Ростов-на-Дону

KILL сессиям делают админы или робот, тогда такие сообщения приходят.
Еще слишком умный роутер может сессии прибивать, если нет трафика

Исправлено: Влад Колосов, 12.11.15 14:28

Аспид

Сообщений: 3371
Откуда: Москва

Помнится отлаживал обрыв связи, так шнурок от компа, прямо под руку положил, и рвал.
Добивался, что бы само при восстановлении восстанавливалось )))
зы. И может лучше коннект, на кажный чих, и дисконнект? Должно исчезнуть?

Igor Korolyov

Не факт что лучше — всё ж это затратная процедура. При этом я имею в виду именно «физический» коннект (то что висит в адонетовском пуле даже если прога не пользует в данный момент ни каких Connection). Я надеюсь что автор таки следует «рекомендациям лучших собаководов» и работа с БД организована сравнительно короткими сеансами (подход UnitOfWork) вида
Просто инфраструктура пула не может сама прочухать что подлежащая коннекция протухла и надо бы её выкинуть и сделать новую.

А ежели автор таки пользует подход «при старте проги сделал одну DBConnection, запихал ея в static поле и таперича всегда и везде её пользую», то он таки неправ

Александр Жевелев
Автор

Сообщений: 2672
Откуда: Новосибирск

MSDN
Соединения и платформа Entity Framework

Entity Framework открывает соединения только по требованию, например чтобы выполнить запрос или вызвать метод SaveChanges, и закрывает соединение после завершения операции.
Вызов любого из следующих методов открывает соединение:

-SaveChanges или Refresh в ObjectContext.

-FirstOrDefault или First в ObjectQuery.

-Load в EntityCollection.

-Load в EntityReference.

-Любой метод LINQ или метод построителя запросов ObjectQuery, такой как Where, OrderBy или Select.

2. Похоже найдена и устранена причина ошибки в моем случае — Сервер, на котором крутится SQL server установлен на виртуальной машине, так вот скорость виртуальной сетевой карты виртуальной машины не соответствовала скорости реальной сетевой карты (была в 10 раз выше). После устранении несоответствия ошибок не возникает вообше!
Всем спасибо за внимание и советы!

Ошибка отсутствие установленного MS SQL server Native Client

При разнесении по разным серверам (хостам) Сервер 1С и MS SQL в попытке создать новую базу средствами утилиты администрирования Сервера 1С, нас встречает ошибка: «Ошибка создания информационной базы, Ошибка операции администрирования, Ошибка при получении значения из базы данных: Возможной причиной является отсутствие установленного MS SQL server Native Client. »

Конечно, данная тема также подымается и на курсе: Администратор 1С!

Конечно, получить ошибку «повезло не всем», а только тем, кто работает с 1С версии 8.3.8 и выше.

Благо решить проблему довольно просто, собственно дав Серверу 1С то, что он просит!

Где искать MS SQL server Native Client ?

Скорее всего файл установщик MS SQL server Native Client (он же sqlncli.msi) уже у Вас на диске!

Если Вы не удалили каталог «установщик», когда скачивали и затем ставили свой MS SQL server 2017 (Выпуск Evaluation).

Тогда искать долго не надо!

Идем «по умолчанию путь» на диск С: там ищем каталог «SQL server 2017 Media»

И уже в этом каталоге воспользовавшись обычным поиском sqlncli.msi, успешно находим наш MS SQL server Native Client!

Остается лишь его скопировать и установить там, где работает «Сервер 1С».

Установка очень простая, всего пару кликов по кнопке «Далее»

Ставим «Пакет SDK для SQL Server Native Client»

Также MS SQL server Native Client можно скачать и на официальном сайте Microsoft, например в пакете дополнительных компонентов для Microsoft® SQL Server® 2016:

Если Вы хотите больше узнать о технической стороне 1С, тогда регистрируйтесь на первый бесплатный модуль курса: Администратор 1С >>>

System.Data.SqlClient.SqlException: сбой входа для пользователя

При работе с моим проектом в режиме отладки у меня нет проблем. Однако при запуске его в IIS я получаю эту ошибку:

System.Data.SqlClient.SqlException: сбой входа для пользователя ‘домен имя-ПК $’.

Трассировка стека

Решение номер один, которое я могу найти в Google, — это изменить расширенные настройки идентификации пула приложений, которые не работали.

Я использую IIS 7.5 и подключаюсь к SQLServer 2012, моя строка подключения указана ниже.

Строка подключения

8 ответов

Предполагая, что вы собираетесь использовать проверку подлинности Windows для олицетворения учетной записи службы, необходимо настроить проверку подлинности Windows как в IIS, так и в ASP.NET.

В IIS убедитесь, что модуль проверки подлинности Windows добавлен и включен. Также убедитесь, что пул приложений работает под учетной записью домена, а не локальной учетной записью.

В ASP.NET убедитесь, что для атрибута режима аутентификации установлено значение «Windows»

Просто установите Integrated Security=False , и он будет работать в соответствии с комментарий разница между True и False :

True игнорирует User ID и —- +: = 5 =: + —-, если он предоставлен и использует те из запущенного процесса, Password он будет использовать их, если это предусмотрено, поэтому MS предпочитает это. Они эквивалентны тем, что используют один и тот же механизм безопасности для аутентификации, но это так.

Вы также можете получить эту ошибку, если ваш SQL Server не был настроен на использование проверки подлинности в смешанном режиме — он фактически не говорит вам, что это не включено!

У меня был похожий опыт, и мне потребовалось время, чтобы решить проблему. Хотя в моем случае это были ASP.Net MVC Core и Core рамки. Настройка Trusted_Connection=False; решила мою проблему.

Внутри appsettings.json файл

Я только что натолкнулся на эту ошибку, и ее устранение заняло несколько дней. Мы были зациклены на сообщении об ошибке «красная сельдь», упомянутом в первоначальном вопросе, плюс журнал ошибок Windows Event Viewer показал что-то похожее:

Ничего из этого не было правдой, у пользователя были все необходимые разрешения в SQL Server.

В нашем случае решением было переключить идентификатор пула приложений в IIS на NetworkService .

Здесь Numpty использовал аутентификацию SQL

вместо Windows (правильно)

при добавлении имени входа на SQL Server, что также выдает эту ошибку, если вы используете аутентификацию Windows.

Я столкнулся с такой же ситуацией. Создайте строку подключения следующим образом.

добавить постоянную информацию о безопасности = True; в строке подключения.

title description author ms.author ms.date ms.service ms.subservice ms.topic dev_langs

SqlClient troubleshooting guide

Page that provides resolutions to commonly observed problems.

David-Engel

v-davidengel

03/06/2023

sql

connectivity

conceptual

csharp

vb

SqlClient troubleshooting guide

[!INCLUDEDriver_ADONET_Download]

Exceptions when connecting to SQL Server

There are various reasons why connection can fail to be established. Here are some troubleshooting tips that can be used as a guide to analyze and solve many of the problems.

Unable to load native SNI (Server Network Interface) library

Issues in .NET Framework applications

Stacktrace observed:

TypeInitializationException: The type initializer for 'Microsoft.Data.SqlClient.SNILoadHandle' threw an exception.
DllNotFoundException: Unable to load DLL 'Microsoft.Data.SqlClient.SNI.x64.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
TypeInitializationException: The type initializer for 'Microsoft.Data.SqlClient.SNILoadHandle' threw an exception.
DllNotFoundException: Unable to load DLL 'Microsoft.Data.SqlClient.SNI.x86.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

SNI is the native C++ library that SqlClient depends on for various network operations when running on Windows. In .NET Framework applications that are built with the MSBuild Project SDK, native DLLs aren’t managed with restore commands. So a «.targets» file is included in the «Microsoft.Data.SqlClient.SNI» NuGet package that defines the necessary «Copy» operations.

The included «.targets» file is autoreferenced when a direct dependency is made to the «Microsoft.Data.SqlClient» library. In scenarios where a transitive (indirect) reference is made, this «.targets» file should be manually referenced to ensure «Copy» operations can execute when necessary.

Recommended Solution: Make sure the «.targets» file is referenced in the application’s project file to ensure «Copy» operations are executed. An example of edits to a project file can be found in this related GitHub issue.

These targets cover Microsoft’s well-known and commonly used targets only. If an external tool or application defines custom targets to copy binaries, new targets must be defined by tool maintainers to ensure native SNI DLLs are copied along-side the Microsoft.Data.SqlClient.dll binaries and are available when executing client applications.

Issues in .NET Core applications

Stacktrace observed:

System.TypeInitializationException: The type initializer for 'Microsoft.Data.SqlClient.TdsParser' threw an exception.
---> System.TypeInitializationException: The type initializer for 'Microsoft.Data.SqlClient.SNILoadHandle' threw an exception.
---> System.DllNotFoundException: Unable to load shared library 'Microsoft.Data.SqlClient.SNI.dll' or one of its dependencies.

[!NOTE]
This error may occur on Windows applications only. If it occurs in a Unix environment, you must ensure your application is built to appropriately target a Unix runtime and not for Windows.

SNI is the native C++ library that SqlClient depends on for various network operations when running on Windows. Microsoft.Data.SqlClient doesn’t manage loading/unloading of this library in .NET Core.

Recommended Solution: Ensure «Execute» permissions are granted on the filesystem where native runtime libraries are loaded in the .NET Core process. If that doesn’t solve the issue, you can file an issue in the dotnet/runtime repository for further support.

Native SNI (pdb not found) errors

Stacktrace observed:

An assembly specified in the application dependencies manifest (sql2csv.deps.json) was not found:
  package: 'Microsoft.Data.SqlClient.SNI.runtime', version: '2.0.0'
  path: 'runtimes/win-x64/native/Microsoft.Data.SqlClient.SNI.pdb'

Recommended Solution: Ensure client application references minimum v2.1.0 version of Microsoft.Data.SqlClient package. When using EF Core, add a reference to this package version of Microsoft.Data.SqlClient directly to override dependency.

Hostname resolution errors

Stacktrace observed:

Microsoft.Data.SqlClient.SqlException (0x80131904): 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: TCP Provider, error: 0 - No such host is known.)
Microsoft.Data.SqlClient.SqlException (0x80131904): 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: TCP Provider, error: 35 - An internal exception was caught)
Microsoft.Data.SqlClient.SqlException (0x80131904): 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: TCP Provider, error: 35 - An internal exception was caught)
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (00000005, 0xFFFDFFFF): Name does not resolve

Possible reasons

  • TCP/Named Pipes Protocol isn’t enabled on SQL Server

    Recommended Solution: Enable the TCP/Named Pipes Protocol on the SQL Server instance from the SQL Server Configuration Manager console.

  • Hostname not known

    Recommended Solution: Ensure the hostname resolves to the Server’s IP address from the client where the connection is being initiated.

Login-phase errors

Stacktraces observed:

Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the pre-login handshake.
(provider: SSL Provider, error: 31 - Encryption(ssl/tls) handshake failed)
System.IO.EndOfStreamException: End of stream reached
A connection was successfully established with the server, but then an error occurred during the login process.
(provider: SSL Provider, error: 0 - The target principal name is incorrect.)
Microsoft.Data.SqlClient.SqlException (0x80131904): Connection Timeout Expired. The timeout period elapsed during the post-login phase. The connection could have timed out while waiting for server to complete the login process and respond; Or it could have timed out while attempting to create multiple active connections.
The duration spent while attempting to connect to this server was - [Pre-Login] initialization=837; handshake=394; [Login] initialization=3; authentication=15; [Post-Login] complete=1027;
---> System.ComponentModel.Win32Exception (258): Unknown error 258
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)

Possible reasons and solutions

  • SQL Server doesn’t support TLS 1.2

    This error typically occurs in client environments like docker image containers, Unix clients, or Windows clients where TLS 1.2 is the minimum supported TLS protocol.

    Recommended Solution: Install the latest updates on supported versions of SQL Server1 and ensure the TLS 1.2 protocol is enabled on the server.

    1 View SqlClient driver support lifecycle for the list of supported SQL Server versions with different versions of Microsoft.Data.SqlClient.

    Insecure solution: Configure TLS/SSL settings in the docker image/client environment to connect with TLS 1.0.

    MinProtocol = TLSv1
    CipherString = DEFAULT@SECLEVEL=1
    

    [!NOTE]
    When connecting with Microsoft.Data.SqlClient v2.0+ from a Windows/Linux environment with TLS 1.0 or TLS 1.1, a security warning message will be thrown if the target SQL Server and client cannot negotiate a minimum of TLS version 1.2 when establishing the connection:
    Security Warning: The negotiated <TLS1.0 | TLS1.1> is an insecure protocol and is supported for backward compatibility only. The recommended protocol version is TLS 1.2 and later.

  • SQL Server enforced encryption

    If the target Server is an Azure SQL instance or an on-premises SQL Server with the «Force Encryption» property turned on, an encrypted connection is made, for which the client must establish trust with the server.

    Recommended Solution: There are two available options to fix this issue:

    1. Install the target SQL Server’s TLS/SSL certificate in the client environment. It’s validated if encryption is needed.
    2. (Less secure) Set the «TrustServerCertificate=true» property in the connection string.

    Insecure solution: Disable the «Force Encryption» setting on SQL Server.

  • TLS/SSL Certificates not signed with SHA-256 or greater.

    Recommended Solution: Generate a new TLS/SSL Certificate for the server whose hash is signed with at-least the SHA-256 hashing algorithm.

  • Tightly restricted cipher suites on Linux with .NET 5+

    .NET 5 introduced a breaking change for Linux clients, where a tightly restricted list of permitted cipher suites is used by default. You may need to expand the default cipher suite list to accept legacy clients (or to contact legacy servers) by either specify a CipherSuitePolicy value or changing the OpenSSL configuration file.

    Read more on Default TLS cipher suites for .NET on Linux
    for recommended action.

Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
 ---> System.ComponentModel.Win32Exception (0x80090325): The certificate chain was issued by an authority that is not trusted.
  • SQL Server enforced encryption

    If the target Server is an on-premises SQL Server with the «Force Encryption» property turned on and a self-signed certificate, an encrypted connection is made, for which the client must establish trust with the server.

    Recommended Solution: There are two available options to fix this issue:

    1. Install the target SQL Server’s TLS/SSL certificate in the client environment. It’s validated if encryption is needed.
    2. (Less secure) Set the «TrustServerCertificate=true» property in the connection string.

    Insecure solution: Disable the «Force Encryption» setting on SQL Server.

Connection Pool exhaustion errors

Stacktrace observed:

System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool.
This may have occurred because all pooled connections were in use and max pool size was reached.

Possible reasons and solutions

Client application is opening more connections than the connection pool can hold active at a given time.

Recommended Solution: Configure «Max Pool Size» connection property to a higher value and close unused connections in timely manner.

Contact Support

If this guide doesn’t solve your connectivity issues, you may view existing issues in the dotnet/sqlclient repository and open a new issue if needed.

  • Net runtime 1026 ошибка windows 10
  • Net helpmsg 3534 сервер solidworks как устранить ошибку
  • Net has only one pin altium ошибка
  • Net framework при обработке сертификата произошла неизвестная ошибка
  • Net framework ошибка цепочка сертификатов