Unit test and SQL database Connection - sql-server

I am having a problem with a unit test I have created. First time doing this so I am not sure why I am getting this error
<DeploymentItem("ETDS.exe")> <DataSource("System.Data.SqlClient", "Data Source=Foo;Initial Catalog=FooDB;Integrated Security=True", "User_Names", DataAccessMethod.Sequential)> <TestMethod()> _
Public Sub ValidateUserNameTest()
Dim target As Login_Accessor = New Login_Accessor ' TODO: Initialize to an appropriate value
Dim expected As Boolean = True ' TODO: Initialize to an appropriate value
Dim actual As Boolean
actual = target.ValidateUserName
Assert.AreEqual(expected, actual)
End Sub
The error I am getting is
Test method ETDS_Unit_Tests.LoginTest.ValidateUserNameTest threw exception: System.Data.SqlClient.SqlException: 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server).
This is the same connection that my software is using, and the software runs fine, only the unit test is failing. What I am doing wrong?
Edit
It Seems to fail one time for each datarow in the table.
Also, I am using a Linq Query in the method that I being tested. I believe that this may be what is causing my error.

Because you are using integrated security, the problem is most likely: "Who is running the test and what rights do they have to the network and/or the SQL Server?". If it's a local machine account, it probably won't even be allowed out over the network.
I noticed that your connection string does not have Server=
If you are connecting locally, it should have Server=(local)

Do you have the Foo alias setup in your local SQL Native Client config? Without that the "Data Source = Foo;" reference in your connection string won't work.

I've no idea if this is the same as the OP encountered, but the solution I found to a very similar problem was adding Provider=SQLOLEDB; to the connection string.

Related

provider: SSL Provider, error: 0 - An existing connection was forcibly closed by the remote host

I wrote a console app that just calls a stored procedure in a SQL Server database. Then I set up a Windows Task Scheduler event to call the console app's .exe file every 5 minutes. Most of the time it works, however about 10 times a day or so we get the following sqlException as soon as the connection is opened to call the stored procedure:
System.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 - An existing connection was forcibly closed by the remote host.)
I've temporarily built in a try block with a simple 5 retries and a short pause between and it's helped some but there's still several times a day that fail out all 5 times. I'm thinking it's got to be some sort of communication issue but I'm not even sure where to look.
Most of the research I've done points toward TLS or firewall issues. I'm not an expert at either of those but I would think if either of those were the cause it would get the error every time consistently. Same thing with the reference to SSL. On the other hand for the same reason I don't see how it could be a coding issue with either the console app or the stored procedure so I'm out of ideas.
The SQL connection code is something like the following:
Public Function GetDataTable(tsql As String, Optional ConnectionString As String = Nothing, Optional TryNum As Integer = 1) As DataTable
Try
Dim dt As DataTable
Using conn As SqlConnection = New SqlConnection(If(Not ConnectionString Is Nothing, ConnectionString, SConn))
conn.Open()
Using dr As SqlDataReader = (New SqlCommand With {.CommandType = CommandType.Text, .CommandText = tsql, .Connection = conn, .CommandTimeout = SqlCommandTimeout}).ExecuteReader
dt = New DataTable()
dt.Load(dr)
dr.Close()
End Using
conn.Close()
End Using
Return dt
Catch exSQL As System.Data.SqlClient.SqlException
If exSQL.ToString.Contains("A connection was successfully established with the server, but then an error occurred during the login process.") AndAlso TryNum < MaxTries Then
Threading.Thread.Sleep(RetryWaitMS)
Return GetDataTable(tsql, ConnectionString, TryNum + 1)
Else
SendMsg(ERROR_EMAIL_GROUP, ERROR_EMAIL_GROUP, "CommonUtils - SQL Error", tsql & vbCrLf & exSQL.ToString)
Throw exSQL
End If
End Try
End Function
I had the same problem several times, and this was the cause each time:
This issue also occurs when an application running on Windows Server 2012 R2 tries to connect to SQL Server running on Windows Server 2019.
https://support.microsoft.com/en-us/help/4557473/errors-when-applications-try-to-connect-to-sql-server-in-windows
Yes, this happens randomly because it only happens when there is leading 0 in the TLS keys and one side of the connection pads the 0 while another side doesn't. If you cannot upgrade all your Windows to the latest, use this workaround:
Disable the following 2 TLS_DHE ciphers in Group policy editor:
Computer Configuration -> Administrative Templates -> Network -> SSL Configuration Settings\SSL Cipher Suite Order:
TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
Note it is not to disable the whole suite (SSL Cipher Suite Order), rather it is to enable the suite order, then take away those 2 TLS_DHE ciphers from the Options. You need a restart to make it effective.

SSIS Connection Manager Does Not Exist

I have created a database through a task script in SSIS. When I later try to connect to that database through the Connection Manager I am told that the Connection Manager does not exist. The database is there in the server.
How can I establish the connection to the database to load the data after I've created a new DB in the script?
Error: The connection "Data Source=..;Initial Catalog=8888888;Provider=SQLNCLI11.1;Integrated Security=SSPI;Auto Translate=False;" is not found. This error is thrown by Connections collection when the specific connection element is not found.
From the Microsoft Forums The connection "" is not found from..
Similar question: SSIS Connection not found in package
You will need a ConnectionManager. It's an object in your project (assuming you are working in a project...) which you can add. This ConnectionManager can then be modified in order to not use a static connectionstring but to use a variable instead. This string variable as you already mentioned has then to be populated with the correct string. This can be done within your script task

How do I connect to an SQL server database in R

I'm trying to connect to the SQL Sever database using R but not sure on the details for the query string. I normally use SQL server management studio on SQL Server 2008 and connnect using single sign on. I found the below example
myconn <- odbcDriverConnect(connection="Driver={SQL Server
Native Client 11.0};server=hostname;database=TPCH;
trusted_connection=yes;")
I get the below warning message
Warning messages:
1: In odbcDriverConnect(connection = "Driver={SQL Server \nNative Client 11.0};server=hostname;database=TPCH;\ntrusted_connection=yes;") :
[RODBC] ERROR: state IM002, code 0, message [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
2: In odbcDriverConnect(connection = "Driver={SQL Server \nNative Client 11.0};server=hostname;database=TPCH;\ntrusted_connection=yes;") :
ODBC connection failed
How do I go about finding the specifics i need?
I have done this in the past with an odbc named connection that I've already had in place. In case you don't know, you can create one in windows by typing into the search prompt 'odbc' and selecting "set up data sources". For example - if you named an odbc connection 'con1' you can connect the following way:
con<-odbcConnect('con1') #opening odbc connection
df<-sqlQuery(con, "select *
from ssiD.dbo.HOURLY_SALES
") #querying table
close(con)
This works for me.
library(RODBC)
dbconnection <- odbcDriverConnect("Driver=ODBC Driver 11 for SQL Server;Server=server_name; Database=table_name;Uid=; Pwd=; trusted_connection=yes")
initdata <- sqlQuery(dbconnection,paste("select * from MyTable;"))
odbcClose(channel)
Also, see these links.
RODBC odbcDriverConnect() Connection Error
https://www.simple-talk.com/sql/reporting-services/making-data-analytics-simpler-sql-server-and-r/
The problem is simpler than this. The big clue is the \n in the error message. Something has re-flowed your connection string such that there is now a new-line character in the driver name. That won't match any registered driver name. Pain and suffering then ensues. Make sure your whole connection string is on a single line!
I often use:
driver={SQL Server Native Client 11.0}; ...
and it works really well. Much better than having to rely on pre-defined connection names.
Try another ODBC driver.
In windows press the "windows" button and then type "odbc".
Click the "Data sources (ODBC)" link.
Go to the "Drivers" tab to see the available drivers for SQL Server.
Also - remove the " " spaces after the semicolons in your connection string.
Note - the database property should point to a database name rather than a table name.
This worked for me:
odbcDriverConnect("Driver=SQL Server Native Client 11.0;Server=<IP of server>;Database=<Database Name>;Uid=<SQL username>;Pwd=<SQL password>")
First, you need to install the package 'RSQLServer', and all its dependencies.
Then execute the following command in RStudio, with relevant parameters:
conn <- DBI::dbConnect(RSQLServer::SQLServer(),
server = '<server>',
port = '<port>',
properties = list(
user = '<user>',
password = '<password>'
))
Finally, db_list_tables(conn) gives you the list of tables in the corresponding database.

Connection Failed SQL Server

I have the following code snippet:
SqlConnection sr = new SqlConnection(this.strConnection);
sr.Open();
Where connection string is:
Data Source = localhost;Initial Catalog=UIB_IS;Persist Security info=True;User ID=USR;Password=PSW;
(I have removed the user name and password from above for purpose of this question - I have double checked the password has not expired and is still the same.)
Every time I try to open the connection I get a failed exception.
I have also tried using the Microsoft.SqlServer.Management.Smo.Server() object with a string connection as well as a ServerConnection object. With the server connection object using a string and SQLConnection object.
None seem to be working.
Within the connection string I have tried the syntax ServerName\SQLSERVERNAME, 127.0.0.1 as well as localhost as you can see above.
Previously this code has been working over the last 6 months using the 'ServerName\SQSERVERNAME' syntax in the connection string on a Microsoft.SqlServer.Management.Smo.Server() object.
This last week.....no longer works.
No System updates have been applied. The DB and SQL User exist with the appropriate permissions set as were before. SQL Server still has allow remote connections set to allow.
The server firewall is also off (Development machine)
I cannot understand why it would suddenly stop working?
Anyone have any ideas?
Thanks in advance.
Be sure that your Sql Server allow remote connections. You can check its status under Sql Server Surface Area Configuration --> Surface Area Configuration for Services and Connection.

Intermittent SQL Exception - network-related or instance-specific error

We have a very strange intermittent issue which has started coming up over the last month or so whereby some connections to mssql server fail with the error:
System.Data.SqlClient.SqlException: 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
The error does not bring down the site, nor does it require a db restart - if you simply rerun the same query will work the second time. This means a lot of users will hit an error every now and then and have to refresh the error page for things to work.
Now, my initial knee-jerk reaction was this could be due to:
Resource related issue - so I started running SQL profiler and perfmon, but did not find any issues with the serve struggling to keep up with the number of connections / sec. I've been looking at MSSQL:SQL Errors, MSSQL:Wait Statistics, MSSQL:Exec Statistics, MSSQL:Locks. Does anyone have any guidance on other stats I should be poking and prodding here?
Unclosed DB connections - I ruled this one out after going through all the data-tier code. We have all the fail safes in place to stop this from happening.
Connection / Network related issue: our SQL server sits on a separate server (MS SQL Server Standard 2008) to our application server (running ASP.Net on IIS7) - both servers run on xlarge Amazon EC2 instances with all security policies configured (as per Amazons direction). Anyone got guidance on how to test the connectivity between the two servers or if this could be the issue?
Is it a possible issue with the IIS connection string? I have not tested this but should we be fully qualifying the server with the computer name we are connecting to (just thought of it)? We use a connection string in the format: server=xxxxx;Database=xxxx;uid=xxxx;password=xxx;
Your thoughts and insight is very much appreciated!
Thanks in advance
Solved. After testing almost every possible performance metric and examining every piece of code, I discovered that the error was caused by a bit of deprecated database code. The main issue was being caused by code using:
SqlConnection.ClearPools;
For future reference, any other developers looking to debug their code and manage connection pools, an excellent resource can be found here: http://www.codeproject.com/KB/dotnet/ADONET_ConnectionPooling.aspx
Try changing the connection string to the FQDN+port
server=xxxxx.domain.tld,1234;
Note: you don't need any instance name if you use port
On our global corporate intranet... we had a similar issue that happened to remote clients: more often if they were further away, never in the same building as the server.
After some poking around, chatting to the DBAs and MS, it was said to be caused by timing/Kerberos/too many firewalls etc. Adding FQDN+port removed all our issues.
It may be solved by switching to TCP/IP instead of Named Pipes, if you can.
Perhaps you can test this by changing the server name to the server IP address.
I use server=tcp:servername in my connection string to force TCP.
KB313295
It seems like connection are not being closed correctly, and after some time you can't open any more new connections. As the total allowed connections to database is a constant digit.
If you are using C#/VB.net
Are you using "Using" statements to open the connections ?
using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string"))
{
con.Open();
}

Resources