I'm trying to change from c# the TCP/IP ports and dynamic ports of my instance in SQL Server 2005.
I have already tried a solution, as in the code above, but it works only if some Server 2008 functionality are installed (like: SharedManagementObject.msi).
I need a solution that work for Sql Server 2005 without the additional installation of other Sql Server editions.
Here is the code that i have already tried (
try
{
Console.WriteLine(" Started...\n");
const string instanceName = "INSTANCENAME";
var managedComputer = new ManagedComputer();
var serviceController = new ServiceController(string.Concat("MSSQL$", instanceName));
Console.WriteLine(" - Istance: " + instanceName + "\n - DisplayName: " + serviceController.DisplayName + "\n");
var serverInstance = managedComputer.ServerInstances[instanceName];
var serverProtocol = serverInstance.ServerProtocols["Tcp"];
var ipAddresses = serverProtocol.IPAddresses;
if (ipAddresses != null)
{
for (var i = 0; i < ipAddresses.Count; i++)
{
var ipAddress = ipAddresses[i];
if (serviceController.Status == ServiceControllerStatus.Running)
{
serviceController.Stop();
serviceController.WaitForStatus(ServiceControllerStatus.Stopped);
}
if (!string.Equals(ipAddress.Name, "IPAll"))
{
ipAddress.IPAddressProperties["Enabled"].Value = true;
}
ipAddress.IPAddressProperties["TcpDynamicPorts"].Value = "";
ipAddress.IPAddressProperties["TcpPort"].Value = "1433";
serverProtocol.Alter();
}
}
if (serviceController.Status == ServiceControllerStatus.Running)
{
return;
}
serviceController.Start();
serviceController.WaitForStatus(ServiceControllerStatus.Running);
Console.WriteLine(" Finished...\n");
}
catch (Exception exception)
{
Console.WriteLine("\n" + exception + "\n");
}
finally
{
Console.Write(" Press any key to continue... ");
Console.ReadKey();
}
Google is your friend...
If enabled, the default instance of the Microsoft SQL Server Database Engine listens on TCP port 1433. Named instances of the SQL Server Database Engine and SQL Server Mobile are configured for dynamic ports, which means they select an available port when the SQL Server service is started. When connecting to a named instance through a firewall, configure the Database Engine to listen on a specific port, so that the appropriate port can be opened in the firewall.
To assign a TCP/IP port number to the SQL Server Database Engine
In SQL Server Configuration Manager, in the console pane, expand SQL Server 2005 Network Configuration, expand Protocols for <instance name>, and then double-click TCP/IP.
In the TCP/IP Properties dialog box, on the IP Addresses tab, several IP addresses appear, in the format IP1, IP2, up to IPAll. One of these are for the IP address of the loopback adapter, 127.0.0.1. Additional IP addresses appear for each IP Address on the computer. Right-click each address, and then click Properties to identify the IP address that you wish to configure.
If the TCP Dynamic Ports dialog box contains 0, indicating the Database Engine is listening on dynamic ports, delete the 0.
In the IPn Properties area box, in the TCP Port box, type the port number you wish this IP address to listen on, and then click OK.
In the console pane, click SQL Server 2005 Services.
In the details pane, right-click SQL Server (<instance name>) and then click restart, to stop and restart SQL Server.
After you have configured SQL Server to listen on a specific port there are three ways to connect to a specific port with a client application:
Run the SQL Server Browser service on the server to connect to the Database Engine instance by name.
Create an alias on the client, specifying the port number.
Program the client to connect using a custom connection string.
Now to do that in C#, I don't know. Maybe try a BAT file and call it from C#?
Related
I have a problem connecting to a SQL Server using C#. I have to connect to a SQL Server instance, that is behind a firewall. I am using the following code (I don't have the exact code snippet right now, but this should be very close to it):
using (SqlConnection myConnection = new SqlConnection("Server=myServerName\myInstanceName;" +
"Database=myDataBase;" +
"User Id=myUsername;" +
"Password=myPassword;")
{
myConnection.Open();
using (SqlCommand myCommand = new SqlCommand("select * from table",
myConnection))
{
myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
// do sth.
}
}
}
When I run this code, it seems to need TCP-Connections on a range of very high ports (that is what my Firewall administrator told me).
The first time I ran it, it tried to establish TCP-Connections on ports 65175-65177. When we tried it again a while later, it then tried to connect via TCP on three ports somewhere around 45000.
This is a problem, because we don't know which ports to open, because they seem to be random (which seems very weird to me).
All I could find with google is, that normally you only need port 1433 TCP and 1434 UDP. We opened those, but then encountered the problem above.
Can somebody explain to me, why this code tries to connect on these high, random ports? Or how to tell my code not to do that?
A bit of additional information:
If I use SQL Server Management Studio to connect to the SQL Server, I have the same problem. It seems to need these high ports.
If I change my code to use ODBC (from the System.Data.Odbc-Namespace) I have the same problem.
If I use my code on a machine which has free access to the SQL Server (no firewall in between) it works fine.
As Martin Smith pointed out in a comment, the solution was to change the configuration of SQL Server, because it was configured for dynamic ports.
Copied from https://technet.microsoft.com/en-us/library/ms177440(v=sql.105).aspx:
To assign a TCP/IP port number to the SQL Server Database Engine
1.In SQL Server Configuration Manager, in the console panel, expand SQL Server Network Configuration, expand Protocols for instance name, and then double-click TCP/IP.
2.In the TCP/IP Properties dialog box, on the IP Addresses tab, several IP addresses appear in the format IP1, IP2, up to IPAll. One of these is for the IP address of the loopback adapter, 127.0.0.1. Additional IP addresses appear for each IP Address on the computer. Right-click each address, and then click Properties to identify the IP address that you want to configure.
3.If the TCP Dynamic Ports dialog box contains 0, indicating the Database Engine is listening on dynamic ports, delete the 0.
4.In the IPn Properties area box, in the TCP Port box, type the port number you want this IP address to listen on, and then click OK.
5.In the console pane, click SQL Server Services.
6.In the details pane, right-click SQL Server (instance name) and then click Restart, to stop and restart SQL Server.
I downloaded SQL Server 2016 Express and Visual Studio 2015.
I get this message when I try to open SQL Server is my Visual Studio program.
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)
My code is
// _ConnectionString = "Server = ARKY/SQLExpress; Database = Tracker; User Id = Track;Password =Track;Trusted_Connection=True;";
_ConnectionString = "Server = ARKY/SQLExpress; Database = Tracker;Trusted_Connection=True;Connect Timeout=10";
SqlConnection myConnection = new SqlConnection(_ConnectionString);
try
{
myConnection.Open();
return "";
}
catch (Exception e)
{
return e.Message + " " + _ConnectionString;
}
I tried my different connection strings. This is one example.
ARKY is the name of my computer and SQLEXPRESS is my named instance.
See the screen shot of my SQL Server database. I will appreciate any suggestions.
Try this:
_ConnectionString = #"Data Source=ARKY\SQLExpress;InitialCatalog=Tracker;Trusted_Connection=True;Connection Timeout=10";
You need a backslash rather than a front slash in your server name, and several parameters are misnamed.
In general, you can open "Server Explorer" in VS, add a data connection to your server there, then click on the data connection and look for the connection string in the properties window. You can cut and paste from there.
Try to use this one
_ConnectionString = "Data Source=ARKY/SQLExpress;Initial Catalog=Tracker;Trusted_Connection=True;Connect Timeout=10";
_ConnectionString = "Server = ARKY\\SQLExpress; Database = Tracker;Trusted_Connection=True;Connect Timeout=10";
Check your connection string as well
From FIX : ERROR : Could not open a connection to SQL Server:
Check if your SQL server services is up and running properly:
Go to All Programs > Microsoft SQL Server 2016 > Configuration Tools > SQL Server Configuration Manager > SQL Server Services
Check to make sure SQL Server service status is Running.
In addition, ensure that your remote server is in the same network. Run sqlcmd -L to ascertain if your server is included in your network list.
Enable TCP/IP in SQL Server Configuration
When two or more SQL Servers are connected across network they do all communication using TCP/IP. The default port of SQL Server installation is 1433. This port can be changed through SQL Server Configuration Manager. TCP/IP should be enabled for SQL Server to be connected.
Go to All Programs >> Microsoft SQL Server 2016 >> Configuration Tools >> SQL Server Configuration Manager >> Select TCP/IP
Right Click on TCP/IP >> Click on Enable
You must restart SQL Server Services for all the changes to take effect. Right click and go to menu properties to select location where default port of SQL Server can be changed.
My MySQL connect code below is 'Catching' this error: "Unable to connect to any of the specified MySQL hosts."
My DB is on my linux website and I have remote access enabled using % so anyone can access the DB.
My code is .NET C# and I have a winform.
string server = "http://www.mywebite.net";
string database = "mywebsite_app";
string uid = "admin";
string password = "Password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
MySqlConnection dbConn;
try
{
dbConn = new MySqlConnection(connectionString);
dbConn.Open();
if (dbConn.State.ToString() != "Open")
{
this.Text = "could not open database connection";
}
else
{
this.Text = "database connection opened";
}
}
catch (Exception ex) // catch on general exceptions, not specific
{
this.Text = ex.Message;
}
Thanks for any help...
If you mysql database is on remote hosting, then you usually out of luck try to connect to that database remotely.
The hosting provider usually blocked remote mysql access.
Try using ssh-tunneling.
download putty
http://www.chiark.greenend.org.uk/~sgtatham/putty/
open the command line, and execute putty from the installation directory
putty username#remote_mysqlhost -L 3306:localhost:3306
or you could use the gui, fill the address with your mysql remote, but dont open connection yet.
go to ssh tunnel, add new forwarded port 3306, and the destination as localhost:3306.
as of why the destination is localhost, it is because the destination is what the ssh session see. because you already connected to your remote server in your ssh session, thus, the mysql host is local.
this could also be a set up for dmz.
you can create a dmz gateway using putty to tunnel trough any computer within the dmz network. but the computer behind the gateway, wont publicly expose to the internet.
dont forget to klik the add button to make sure the configuration is added to tunnel list.
open the connection and use your password (ssh user and password, usually the same as webhosting control panel user and password
Now, instead connecting to your remote mysql, you can connect to mysql trough localhost. it would be tunneled by putty to your remote mysql.
try to connect using mysql administration tool first. to test wheter or not the connection is success.
the way ssh tunnel work is almost the same as vpn, from user view.
but without the hassle of setting up vpn server on remote host.
My problem is quite simple: I'm writing a WinForms app in .net 4.0 C# in Visual Studio 2010 it works nicely on my computer.
It connects to a remote SQL Server database using System.Data.SqlClient's SqlConnection.
When the program loads the first form it runs the following code:
SqlConnection ACconnection = new SqlConnection(String.Format(
"Server=xxx.xx.xxx.xxx\\TEST;Database=REP01;User Id={0};Password={1};", User, Password));
private bool TestConnection()
{
try
{
ACconnection.Open();
lbl_connectionStatus.Text = "Server: Connected";
lbl_connectionStatus.ForeColor = Color.FromArgb(0, 150, 30);
ACconnection.Close();
return true;
}
catch (Exception ex)
{
Functions.GetError(ex);
return false;
}
}
I get the error:
SQL Network Interfaces, error: 26
My problem is that even though it is working fine on my computer it won't work nearly anywhere else. All the computers I've tried it are running on Windows 7 or 8, including mine.
I've googled the error, but all the answers focus on the server side, and since it's working fine from my computer I know it's not a server side problem.
Assuming you have firewall issues addressed (either turn off the firewall on your SQL Server box, or make sure there's a hole at port 1433, or whatever port your SQL Server instance is configured to use), make sure you enable remote connections:
From SQL Server Management Studio on the box with the SQL Server instance running, connect to your instance, right-click the server instance in the left pane, and select "Properties". Click the "Connections" tab, and ensure the "Allow remote connections to this server" is checked.
And finally launch your "SQL Server Configuration Manager" tool, and ensure you have Shared Memory, TCP/IP, and Named Pipes all enabled for client protocols for your client configuration. You'll need to do this for both 32 bit and 64 bit.
You should be good to go then.
I figured it out!
The problem was that even though I gave only an instance name in the connection string and no port. So eventually my code was off.
The solution: give the instance name and the port also.
SqlConnection ACconnection = new SqlConnection(String.Format(
"Server=xxx.xx.xxx.xxx\\TEST,49232;Database=REP01;User Id={0};Password={1};", User, Password));
Trying to debug a customer's connection problem when they try specifying the SQL Server port.
Reproducing the issue locally I checked and my server runs under the default 1433 port. Specifying that port using:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "servername,1433";
builder.InitialCatalog = databaseName;
builder.IntegratedSecurity = false;
builder.UserID = userName;
builder.Password = UserPsw;
This fails with "Login failed for user". If I remove the port number, it connects fine. Why does this happen?
By the way the same happens with Windows Integrated Security.
And one more piece of information: I do run also a SQL Server 2005 express SQL server on the same box.
If you are using SQL Server Express and a named instance then the port will not be 1433 but rather a dynamically assigned port.
See this article, scroll down to the section 'Ports used by SQL Server' and look for 'SQL Server named instances in the default configuration'.
http://msdn.microsoft.com/en-us/library/cc646023.aspx
I don't know if you can assign specific ports to SQL Server Express instances. If so, that is what you would need to do, and specify that port in your connection string. If it is not possible to assign a specific port to a to SQL Server Express named instance then you would have to stick with specifying the instance name, without a port.