Connect timeout, database failover not working - c#

I have implemented database mirroring on Azure with a witness, using SQL Server 2008. The mirroring / failover works on the SQL Server side. The problem I am having is that once a failover has occurred my asp.net Website does not connect to the new principle database and is still trying to connect the the old principle.
I have tried adding a 60s Connect Timeout to my connection string as suggested in this post. However this does not have any effect. And all I end up getting is the following error after around 60s:
Request timed out.
Does anyone have any other suggestions?
Any help much appreciated!
EDIT
My connection string is:
data source=server1;Failover Partner=server2;initial catalog=DBNAME;User Id=WebsiteUser; Password=******;Connect Timeout=60;multipleactiveresultsets=True

did you add the failover partner to the connection string?
see http://blogs.msdn.com/b/spike/archive/2010/12/08/clarification-on-the-failover-partner-in-the-connectionstring-in-database-mirror-setup.aspx for example and clarification

Related

ASP.NET MVC: moving from SQL Server Express to Azure

I'm sure this has been asked before, but I'm not seeing anything in the similar questions. :(
I've got an ASP.NET MVC application I have developed locally that has been using a SQL Server Express database. In Azure, I recreated the database and taken the connection string it provided and updated the connection string in web.config of my app to use the new database.
When I publish the app to Azure, there doesn't appear to be any issues. However, when I hit a page in the app that accesses the db, it throws an error complaining it can't find the SQL Server Express database. Below is the main snippet from the error:
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: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)
So it seems like it's ignoring my connection string and still looking for a locally stored SQL Server Express database instead of using the Azure database I specify in the connection string. Any ideas why this might be? My guess is that I have missed something pretty basic (my usual guess when something that seems like it should be simple doesn't work. :) )
Connection strings per below request:
Local:
<add name="FCDbContext" connectionString="data source=(localdb)\MSSQLLocalDB;initial catalog=FormCenterResponder;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
Azure Contection String:
<add name="FCDbContext" connectionString="Server=tcp:***azuredbserver here***,1433;Initial Catalog=***azuredb here***;Persist Security Info=False;User ID=***username here***;Password=***password here***;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient" />
And configureservices per another request (it's pretty much defaults):
public void ConfigureServices(IServiceCollection service)
{
services.AddControllersWithViews();
}
Ok, mark this one up to being a asp.net/c# noob. I'll go ahead and post (the embarrassing) answer, though, in case others find themselves in my position.
A co-worker had a look at the code and found an excellent tutorial here. He was able to figure out what I had done wrong.
Basically, I had never registered the database context in Startup.ConfigureServices. I think this is why someone (who has since deleted their question) asked me to post that section of my code. Then that context can be read in by the controller files granting them the info they need to get access to the db.
App is now working as it should.

Issue connect to SQL Server 2000 from C#

I am using a Winforms C#, .Net Framework 4.0 application and I'm trying to connect to SQL Server 2000 using Data.SqlClient. Database and app are running on the same server machine.
Before, I ran app on 2 other servers successfully.
My connection string in config is:
ConnectionString="Data Source=xyz;Initial Catalog=xyz;Integrated Security=True;"
but a 3rd server causes an error:
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=3998; handshake=0; [Login] initialization=0; authentication=0; [Post-Login] complete=10000; "
Then, I changed the connection string to
ConnectionString="Data Source=xyz;Initial Catalog=xyz;Integrated Security=True;Connection Timeout=30;"
and I get a new error
A transport-level error has occurred during SSPI handshake. (provider: Named Pipes Provider, error: 0 - The pipe has been ended.)
Update: I tried using the udl file to create the connection string and put it into the config file but there is still error
So what am I missing here ?
Thanks in advance.
Update: I fixed this issue when replace sqlclient by OLEDB lib
ConnectionString="Data Source=xyz;Initial Catalog=xyz;Integrated Security=True;"
This may be correct try to close your connection after you open
I think you are not missing anything. Your connection string looks good to me.
ConnectionString="Data Source=xyz;Initial Catalog=xyz;Integrated Security=True;
May be due to any reason the connection was placed using Named Pipes instead of Shared Memory. Shared Memory is the default option for local SQL connection so SqlClient could not recognize the connection was local, and placed through Named Pipes over TCP. Result is connection was refused or not connected.
I am not sure but please check you server name, it should be qualified domain name or IP address. If you specify it by the hostname or "." or "(local)", SqlClient should recognize the local connection, and you should not see the error.
I've just been through this problem and nothing I found anywhere helped, so I thought I'd share the solution that helped me.
Turns out my client had used "username#domain.com" as their login instead of just "username". Looks like there is some functionality internal to excel that tries to authenticate the user via that domain, and thus, the connection times out without a response. Don't create logins with "#domain.com" in SQL Server.
Hope this helps someone in future.

Error Database schema could not be retrieved for this connection

Edit: if you are downvoting can you at least tell me what Im missing so I can improve my question?
I have a website which uses a SQL Server database. It works fine when building both debug and release.
But if I add a new SqlDataSource to my project and try to configure it in design view, I get this error:
Database scheme could not be retrieved for this connection. Please make sure the connection settings are correct and that the database is online.
Failed to retrieve data for this request.
Failed to connect to server---------.
Login failed for user 'xxxxxx'.
Even if I configure the connection string with the connection-guide, test the connection and save, it fails afterwards when trying to configure the datasource.
Connection string:
Data Source=SERVER\SQLEXPRESS,61180;Initial Catalog=DBNAME;User Id=USERNAME;Password=PASSWORD;
So to clarify: The connection string works fine when running the website in both debug and release, and if I connect using SQL Server Management Studio, but the only place it doesn't work is when I try to configure the datasource in design view.
After a lot of trial and error I found out that I had to put Persist Security Info=True; into the connectionstring to get it to work.
First time in my 10+ years of programming that I encountered this problem.

Azure Cloud Service unable to connect to SQL Database on write operations only

I have developed a web application in lightswitch. There is an HTML lightswitch client that connects to a server (C#) and this server gets the data from an SQL Database.
The application is working correctly in my local machine, the problem comes when I publish the solution to a Cloud Service in Azure. Then, the server connects to the database correctly and can read all the information from it, but when I try to update the database from within my application (insert or update rows) the application freezes and it promts the following error:
Unable to connect to SQL Server database.
Inner exception message:
Unable to connect to SQL Server database.
Inner exception 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)
I have checked the connection parameters and all of them are correct, this is the connection string in my web.config:
<add name="My_Data" connectionString="data source=tcp:{MyServer}.database.windows.net,1433;initial catalog={myDatabase};user id={Myuser}#{MyServer};password={MyPassword};Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.SqlClient" />
I have seen other questions with the same issue, but all of them were because the database or the server was not available. I have no problem connecting to the server because I can query my database with no problems.
The error comes when I try to write in my database, either because I click on the save button of a lightswitch screen or because I do it by code in the server:
serverContext.DataWorkspace.My_Data.SaveChanges();
If I comment the previous line, the error is not prompted.
I have also checked the user permissions in the database and this usser is a db_owner, so there should be no problem with that.
Anyone has ever faced a problem like this?
I found the solution!
After a deep research, I discovered that Azure server is adding a connection string to my application (I don't know how nor why). This connection string is inherited from somewhere and it is pointing to a local instance of SQL Express. Obviously, this instance does not exist, so after a timeout the application throws the error shown above.
I don't really know why this is happening nor why only happens when I try to write in my database. The solution I found is to add the following in the connection strings part of my web.config:
<clear />
With this, we delete the inherited connection string. And now, we have to set the connection string of the LocalSqlServer (which will be our connection string, the one that points to our remote SQL Server in Azure):
<add name="LocalSqlServer" connectionString="Data Source={SERVER}.database.windows.net;Initial Catalog={DATABASE};Integrated Security=False;User ID={USER}#{SERVER};Password={PASSWORD};Encrypt=True" />
Now, everything works fine. I hope this can help anyone who faces the same problem than me and I would really like to know why this happened, so if anyone knows it, please tell me :)

SQL Server Connection Issue - I can connect but other users can't

[edit] so not sure what happened, but we ended up resetting the server and turning off/on TCP/IP and Named Pipes and after a restart and updating the settings everything started working again. weirdest thing. anyways thanks for the help guys.
I'm building a C# WPF application for my job, and I'm getting a weird problem that I've been trying to figure out for the past week. The application connects to the server and imports several tables on start up. So I built it out and was testing it with no issues, but when i pass it to our testers, and everyone is getting the following errors:
Provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server
The users are able to connect to the server through other methods (SSMS/Excel VBA), but just through the application it won't work.
I've checked the following:
Remote connections enabled
TCP/IP connections enabled
Firewall settings are the exact same across all users (me included)
application is compiled as 32 bit (saw this in another thread)
We're using SQL Server 2008 and I've tried several connection strings/methods.
below is the code I'm using to connect:
public void Open_DB_Conn(string Connection_Str)
{
try
{
Sql_Conn = new SqlConnection(Conn_Str);
Sql_Conn.Open();
}
catch (Exception e)
{
MessageBox.Show(string.Format("Error Message:{0} Conn String: {1}",e.Message,Conn_Str));
}
}
Below is my connection string (this is just one of many iterations I've used trying to get it working):
Data Source=IP Address;Initial Catalog=DB_Name;User ID=LOGIN;Password=PWD
Anyone know why I would be the only one able to get it to work and that the users are able to login to the server using other applications without a problem? They use it for logging their excel VBA scripts and there aren't any issues there.
Try this - it may be your answer
"The error is reported by client library. While your server is listeing on remote TCP, client will still try TCP and NP connection in order. So the error client behavior is expected. From what you have described, I believe that even though you enabled the remote TCP connection on the XPSP2 machine, you didn't make the TCP listening port an exception of XPSP2 personal firewall. You should follow steps below to resolve this issue.
check the SQL Server Errorlog to make sure SQL Server is now listening on TCP/IP and confirm which port it is listening on. Usually 1433. In the Errorlog, you will see several lines that discuss what SQL Server is listening on. Below is an example:
2006-01-04 01:41:07.65 server SQL server listening on 10.254.1.150: 1433. <--Shows the IP Address and the port.
2006-01-04 01:41:07.65 server SQL server listening on 127.0.0.1: 1433. <--Shows another IP Address and the port.
2006-01-04 01:41:07.69 server SQL server listening on TCP, Shared Memory, Named Pipes.
2006-01-04 01:41:07.69 server SQL Server is ready for client connections
2, Make sure on Windows XP that the firewall is not blocking that port.
3, go to your client machine and run the client network configuration tool (cliconfg.exe) Make sure TCP/IP is enabled, click properties and make sure the port number is the same one as SQL Server is listening on. Here you can enable NP or disable client NP as well.
Once both the client and the server are using TCP/IP with the same port number and the firewall on server machines is not blocked, you should be able to connect.
Hope this helps."
(Ref: http://social.technet.microsoft.com/Forums/sqlserver/en-US/c488cf76-2515-440f-b3f8-9cfad689c5b6/named-pipes-provider-error-40-could-not-open-a-connection-to-sql-server?forum=sqldataaccess)
You have to configured your SQl server so that other IP can connect it for that you have to gone through mentioned link
Configure SQL server
What authentication are you using for the SQL Server? Windows Authentication or SQL Server authentication? My suggestion is to first turn on SQL Server authentication and use the sa\password to connect to the server. If you are successful, then ask the others (users of your application) to try with the same connection string. Let me know what you find out.
Be sure that the port specified in:
Data Source="IPAddress,port";Initial Catalog=DB_Name;User ID=LOGIN;Password=PWD
matches the port on your SQL Server. You can check that by going on SQL Server COnfiguration Manager and viewing TCP/IP properties.
EDIT :
It is also the case the port defined by blocked by an external firewall. And the rest Applications use other ports. Try to find out which port you can use (if indeed the are restrictions to your network)
Make sure your SQL Server instance is properly configured to use TCP using Sql Server Configuration Manager.
It is by default disabled in SQL Express, as show below.
I'd like to know more about your "Sql_Conn" class.
Also, try using this for your connection.
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
string cmdText = "SELECT name FROM sys.tables"
cmd.CommandText = cmdText;
cmd.ExecuteNonQuery();
}
}

Categories

Resources