connection to a sql server database by ip - c#

I am doing an application that connects to a database located in the same network. the DBMS is SQL Server 2005 and i'd like to test the ping to the ip adress and then test the connection to the database by ado.net:
Ping p = new Ping();
try
{
PingReply pingReply6 = p.Send(ip.Text);
MessageBox.Show("IP: " + pingReply6.Address + " \n Etat : " + pingReply6.Status);
string connexionString;
connexionString = #"Data Source=Owner;Initial Catalog=base;Integrated Security=true;";
IDbConnection connexion = new SqlConnection(connexionString);
try { connexion.Open(); MessageBox.Show(" the connection is established "); }
catch(Exception ex) { MessageBox.Show(ex.ToString()); }
}
catch { MessageBox.Show("Invalid IP"); }
As you see, i'd like to connect to a database by it adress ip, i test the ping and it works but when i test the connection to my database in my server it isn't working
what is the error in the connection string?
how can i change the connection string to connect not to my own database but to other database with the indicated adress ip (windows authentification)?

Use SqlConnectionStringBuilder. Assign the DataSource property to the server name you want to connect to. Extract the ConnectionString from the builder when you want to open a connection. This guarantees a correctly formatted connection string.
In general is a bad practice to use the IP. Use the computer name.
Testing for ping is not relevant for connectivity. SQL connection can use protocols that are not related to TCP/IP (eg. shared memory). Ping can fail depending on various corpnet ICMP settings. Ping can succeed but connectivity can fail based on firewall and IPSec rules. TCP/IP connectivity does not guarantee T-SQL connectivity.

something like this might help
connexionString = #"Data Source=" + pingReply6.Address + "\Owner;Initial Catalog=base;Integrated Security=true;";
In your above . in the connection string means localhost
As #RemusRusanu says IP address is considered poor form however the above will function. hostname would be better

Related

error connection to database c#

I'm trying to connect to a database from VS2017
var str = str1.ConnectionString =
"Data Source=141.*****.199;" +
"Initial Catalog=****;" +
"User id=***;" +
"Password=****;";
using (SqlConnection conn = new SqlConnection(str))
{
try
{
conn.Open();
var text = "SELECT * FROM Users u WHERE u.Id=76769";
...
}
catch (Exception e)
{
return req.CreateResponse(HttpStatusCode.OK, e.ToString());
}
and get error
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.
It's azure function. If I set this connection from LogicApp, then there are no errors.
Why the connection does not work from the azure-function?
can someone help. Functions refer to the database not with only ip , which are listed on the portal. They have several variants. And on the portal these addresses do not look, only through https: //resources.azure.com. And yes, you just need to specify in the firewall all valid values
I am connecting to an SQL DB from Azure Function, and I noticed a little difference in connection string that I am using.
Pls try and see if it works for you:
"Server=tcp:141.*****.199,1433;Initial Catalog=****;User ID=*****;Password=*****;"
1433 - is the default MS SQL port number.

Oracle connection with port, service name, and database from C# (ORA-12514

I'm new to Oracle. Trying to connect C# windows app to an Oracle database but can't seem to establish a proper connection. Keep getting exception: "ORA-12514: TNS:listener does not currently know of service requested in connect descriptor". I have to specify the port, service name, and database name in the connection string because the service id has access to multiple databases. I know that the values in the string are valid (valid server, valid serviceid, valid username, password, etc) because I have a third-party tool that is able to connect using the same parameters from a wizard. I've tried a lot of different ways to format the connection string but I always get the same 12514 error. In the code example, you'll see three formats (cxn, cxn2, and cxn3), I've tried each of them but get the same error.
string cxn = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MyServerName)(PORT=MyPortNumber))" +
"(CONNECT_DATA=(SERVICE_NAME=MyServiceId)));User Id=MyUserName; Password=MyPassword;";
string cxn2 = "DATA SOURCE=MyServerName:MyPortNumber/MyUserName;" +
"PERSIST SECURITY INFO=True;USER ID=MyUserName; password=MyPassword; Pooling = False;";
string cxn3 = "DATA SOURCE=MyServerName:MyPortNumber/MyServiceId;" +
"PERSIST SECURITY INFO=True;USER ID=MyUserName; password=MyPassword; Pooling = False;";
using (OracleConnection conn = new OracleConnection(cxn3))
{
string sqlSelect = "SELECT * FROM PERSONS";
using (OracleDataAdapter da = new OracleDataAdapter(sqlSelect, conn))
{
var table = new DataTable();
da.Fill(table);
if (table.Rows.Count > 1)
Console.WriteLine("Successfully read oracle.");
}
}
Again, I've used MyServiceId in the third-party tool's wizard and I connect just fine and select my database. I'm using Oracle.ManagedDataAccess.Client. I consulted a number of articles online including Oracle's guidance in section "Getting Started with ODP.NET, Managed Driver". How can I get the driver to recognize the valid service id and then also accept the database name? Any guidance is appreciated. Thanks.
Well I wish I had a more definitive explanation but as it turns out the code from my original question works NOW using the connection string defined in variable "cxn". I ran it many times before with no success, so my only guess is that the DBA changed something or rebooted the server since initial configuration.

Querying a website database from a C# console application

I'm trying to write a simple app in C# that will query a database available to the public located at https://newswire.theunderminejournal.com/
They give an example located at https://newswire.theunderminejournal.com/sample2.php
As far as I know, the server I'm trying to connect to is "newswire.theunderminejournal.com" and the database is "newsstand".
This gives me a string of:
string connection_str ="Server=newsstand.theunderminejournal.com;Database=newsstand";
My code looks like this:
xData = "Unable to connect to database.";
string server = "'newswire.theunderminejournal.com'";
//string server = "45.75.164.122";
string database = "'newsstand'";
string connection_str = string.Format("Server={0};Database={1};", server, database);
Console.WriteLine(connection_str);
SqlConnection connection = new SqlConnection(connection_str);
try
{
connection.Open();
xData = "Connection established!";
}
catch(Exception e)
{
xData = e.Message;
}
connection.Close();
connection.Dispose();
This results only in an error message:
"A network-related or instance-specific error occured while not
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)"
I've pinged the server, getting an IP address at 45.79.164.122 and no issues at all pinging it.
Is there something obvious I'm missing here? I'm brand new to C# so if there is another/better way of doing this, I'd appreciate it!
Thanks.
You cannot create a SqlConnection to a mySQL database, which is why the error message refers to "… establishing a connection to SQL Server.".
You need to use a MySqlConnection instead, which you get when you install Connector/Net - which you can download from Oracle here

get unused IP address

I need to get an available IP from the DHCP. I tried to get any ip address and start to ping the next until I reach one that doesn't respond.
public static IPAddress FindNextFree(this IPAddress address)
{
IPAddress workingAddress = address;
Ping pingSender = new Ping();
while (true)
{
byte[] localBytes = workingAddress.GetAddressBytes();
localBytes[3]++;
if (localBytes[3] > 254)
localBytes[3] = 1;
workingAddress = new IPAddress(localBytes);
if (workingAddress.Equals(address))
throw new TimeoutException("Could not find free IP address");
PingReply reply = pingSender.Send(workingAddress, 1000);
if (reply.Status != IPStatus.Success)
{
return workingAddress;
}
}
}
However, sometimes the DHCP reserves special address for some computers, so I need to get an available ip address from the dhcp.
How can I implement that in C#?
That is not the right way you are using it ,
you should request the DHCP server a new ip and then accept it ,
read about communicating with DHCP Server here
http://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol
A client application cannot make a request to the DHCP server for all available addresses.
A DHCP server can only process the following messages from a client:
DHCPDISCOVER
DHCPREQUEST
DHCPDECLINE
DHCPRELEASE
DHCPINFORM
Please see RFC 2131 - Dynamic Host Configuration Protocolfor additional information.
If you are running Windows DHCP server and you have access to the box, you can use Windows PowerShell Scripting to query the DHCP database.
Excerpt from Weekend Scripter: Parsing the DHCP Database? No Way!
Summary: Microsoft Scripting Guy, Ed Wilson, talks about a Windows PowerShell function from the DHCPServer module that permits parsing the DHCP database.
I found this app that solve the problem
http://www.centrel-solutions.com/support/tools.aspx?feature=dhcpapi

Connecting to SQL Azure with ADO.NET

Hi I try to connect to a SQL AZURE DB with ADO.NET.
Here is my code:
private static string userName = "<**#********>";
private static string password = "<********>";
private static string dataSource = "<******.database.windows.net>";
private static string databaseName = "<******>";
public void Save()
{
SqlDataReader queryResultCloud;
string queryString = "select * from tblScan";
SqlConnectionStringBuilder connString2Builder;
connString2Builder = new SqlConnectionStringBuilder();
connString2Builder.DataSource = dataSource;
connString2Builder.InitialCatalog = databaseName;
connString2Builder.Encrypt = true;
connString2Builder.TrustServerCertificate = false;
connString2Builder.UserID = userName;
connString2Builder.Password = password;
using (SqlConnection connection = new SqlConnection(connString2Builder.ConnectionString))
{
SqlCommand command = new SqlCommand(queryString);
command.Connection = connection;
connection.Open();
queryResultCloud = command.ExecuteReader();
connection.Close();
}
and I get next error:
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)
Your code seems to be correct. One thing to try is to set TrustServerCertificate to true, and see if it works. Note it is recommended to set this property to false when Encrypt is set to true. But there’re reports that combination cause connection issues. I would like to suggest you to check http://www.wadewegner.com/2010/08/using-the-trustservercertificate-property-with-sql-azure-and-entity-framework/ for more information. In addition, check again if you have configured SQL Azure firewall to allow connection to your local machine. If you’re behind a proxy, it is needed to add your proxy’s IP address to the firewall exception.
Best Regards,
Ming Xu.
You're likely behind a proxy that doesn't allow outbound connections to port 1433, which is the only port you can use with SQL Azure:
The Windows Azure SQL Database service is only available with TCP port
1433. To access a SQL Database database from your computer, ensure that your firewall allows outgoing TCP communication on TCP port 1433.
I'm in this situation as well, and the most promising / challenging solution appears to be this port bridging application technique, but the solution itself is dated and needs an older version of VS than I have installed, so I'm looking at some other alternatives.

Categories