TCP/IP Connection - c#

I have been trying and searched thousands of times in other sites but never found a sample or simple code to use.
I've created an application C# which uses an ODBC connection, i have also MS SQL installed and configured to enable remoting database information sharing. I want to make my database available to everyone uses this application i have made by using a connection.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace CaseMatter
{
public partial class mainLog : Form
{
string userID, userName, userAddress, userFName, userLastName, userCity, userPassword, userTele;
public mainLog()
{
InitializeComponent();
this.Size = new Size(442, 162);
}
private void Submitbtn_Click(object sender, EventArgs e)
{
string ConnectionString =
"Data Source=xx.xx.xx.xx,1433;Initial Catalog=master;Integrated Security=SSPI;";
var conn = new SqlConnection(ConnectionString);
conn.Open();
var strSQLCommand = "SELECT Name FROM example WHERE id='1'";
var command = new SqlCommand(strSQLCommand, conn);
var reader = command.ExecuteReader();
while (reader.Read())
{
passwordBox.Text = reader.GetString(0);
}
reader.Close();
conn.Close();
}
}
}
I have just edited the code and tried it, i have added a try catch to handle sql exceptions but it still freezes when i click on submit button.
Hopefully someone figures this out.
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: TCP Provider, error: 0 - No connection could be made because the target machine actively refused it.)"

I suspect there are one of four things going on here.
The SQL Server is misconfigured and isn't responding to tcp connections. The easiest way to trouble shoot this is to use SQL Management Studio to connect. If you can't connect this way then you'll have to look at the sql server service setup. Also, make sure that the SQL Browser service is running on the server.
The SQL Server is configured to use a different TCP port than the one you are trying. Remove the ",1433" from your connection string and try again. SQL Browser should respond back with the actual port that sql server is listening on.
The SQL Server has a firewall in place that is blocking remote connections. Temporarily turn off the firewall and see if you can connect. If you can, then configure the firewall correctly and turn it back on.
Your local box has some type of firewall that is blocking outgoing connections on that port. Try turning yours off to see if this helps. If so, configure it correctly and turn it back on.
If this is a brand new sql server that no one has remotely connected to then it's very likely to be entirely within the configuration of SQL server or the Windows configuration.

In your example you are not passing the USER ID and Password. Is that just because you didnt want to include your credentials? I assume not as you properly XXX out your IP address. I would start by supplying credentials of a SQL server account that can access your database.

I noticed that you're using SqlConnection which is not an ODBC connection object. With SqlConnection you're actually connecting via ADO.NET. The connection string syntax for SqlConnection (both ODBC and ADO.NET) can be found on the following site:
http://connectionstrings.com
By the way, if you're connecting to SQL 2005, the connection string would look like this:
using System.Data.SqlClient;
// trusted connection (SQL configured to use your windows ID)
string ConnectionString =
"Data Source=xxxxxxx;Initial Catalog=xxxxxx;Integrated Security=SSPI;"
// sql authentication (SQL manages its own users/pwds)
//string ConnectionString =
//"Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"
var conn = new SqlConnection(ConnectionString);
conn.Open();
var strSQLCommand = "SELECT Name from [example_autoincrement] where id='1'";
var command = new SqlCommand(strSQLCommand, conn);
var reader = command.ExecuteReader();
while (reader.Read())
{
passwordBox.Text = reader.GetString(0);
}
reader.Close();
conn.Close();

Ok, this is a strange one to check but just make sure the time and date is accurate on client and server. SSPI requires a maximum gap of 5 minutes between each

Related

Unable to connect to MySql Server in Visual C#

I am trying to create a local database using MySql in Visual C# but connection is not getting established in the code but when i add the server in the server explorer under data connections its working. I tried test connection it says connection succeeded but its not working in the code.
string connStr = "server=localhost;user=root;database=entry_database;password=superadmin";
con = new SqlConnection(connStr);
This throws an error saying
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)
You cannot use the SqlConnection class to connect to a MySQL server; that is for Microsoft SQL Server only.
Instead, install the MySqlConnector NuGet package and use the following code:
string connStr = "server=localhost;user=root;database=entry_database;password=superadmin";
using (var con = new MySqlConnection(connStr))
{
// ...
}
Your connection string is wrong.. change keys "user" to "Uid" and "password" to "Pwd".
follow eg:
string connStr = "server=localhost;Uid=root;database=entry_database;Pwd=superadmin";
con = new SqlConnection(connStr);
Correct, the format used by you to create the connection string is incorrect, giving you the error you mentioned above.
Actually, the way the connection string is written in MS-SQL is very different from MY-SQL. Every database has its own way of connecting and its individual connection tags:-
Please find the list of connection details for MS_SQL below. This would help you not only in the current mentioned scenario but also will provide a reference for future changes:-
https://www.connectionstrings.com/mysql/

DB connection working with old code and not with new

I am facing some issues with connectivity .
Question-
1)Is it possible that Web application access the databse but not console application?
2)When I am connecting my console app to our databse on server-"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible ",this error is coming though when I test the connection using setting tab in VS2010 for console application,it says Connection succeed,but as soon as i write Con.open,I get the error mentioned.
3)Also,If i am not able to connect to my db with new application,how come previous build web application on production are working fine.?
NOTE-There has been massive change in Server-Sql instances and all servers were upgraded.
Do I make sense?
Code I am using-
SqlConnection con;
SqlDataReader reader;
try
{
int id;
con = new SqlConnection("Data Source=DAN\\C1;Initial Catalog=tablenames;User ID=user;Password=123");
con.Open();//Error comes here
Exact same connection string works for webapplication but not for Console.Is it have something to do with sql server upgarde and changes.
Any help or guidance?
okay well from what i can see you may want to check that you have imported and used all the required namespaces involved in an SQL connection , you will need to import the following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
After ensuring all the correct namespaces have been imported then you should check your connection string maybe there is a typing error or something there , remember if you make a mistake on the connection string the connection will be refused , and im not sure if this code will work but here goes try this method of connecting :
SqlConnection con;
SqlDataReader reader;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
con = new SqlConnection(connetionString);
try
{
int id;
con.Open();
Console.WriteLine("Connection Open ! ");
cnn.Close();
}
catch (Exception ex) { Console.WriteLine("Can not open connection ! "); }
If the above code gives you problems you can try this other method of doing a SQL connection in a C# console project as seen in the link below:
http://www.c-sharpcorner.com/UploadFile/5089e0/how-to-create-single-connection-string-in-console-applicatio/
First check in the Server Explorer whether you are connected to the Server or database.If u connected to the server, server name will be visible under data connection, right click on it go to properties there u can find connection string value. copy paste that value in your sql connection code. Try this it may solve your connection string problem.
Thanks everyone.But it was some security issue.Once I deploy my code on server,its working.Remote connectivity was somehow restricted in the sql server.

Connection String via IP Address For SQL Server

I want to create connection string so that I can connect to SQL database remotely in my C# code using OleDb as a provider and the server IP address.
Note 1 : I'm using OleDb because I want to handle different database types. SQL is just an example.
Note 2 : The database resides on another machine (machine on another network)
I did all the setup to connect from another machine (firewall,Enable TCP/IP..etc), and now I can connect remotely using Microsoft SQL Server Management 2014 by specifying (server name : My Computer Name-PC\Instance name) and using SQL Authentication then entering the username and password and press connect and then it goes well, I connect successfully.
BUT I TRIED A LOT OF COMBINATIONS TO BUILD THE CONNECTION STRING IN MY C# CODE AND NONE OF THEM WORKS EXCEPT THIS :
OleDbConnection conn = new OleDbConnection(#"provider = sqloledb; data source = MyCompName-PC\sqlexpress; Initial Catalog = DataBase1 ; user id = MyUsername ; password = MyPassword ;");
Otherwise if I try to use my server public IP address instead of MyCompName in Data Source it keeps giving me error : server not found or access denied.
I search in connectionstrings.com but problem is still there.
From your post it looks like you are trying to connect to a SQL Server database then why are you using OleDbConnection? instead of using SQL Server connection provider.
OleDbConnection connection provider is used for connecting to MS Access database.
You should be using a SqlConnection class like
SqlConnection conn = new SqlConnection("data source = MyCompName-PC\sqlexpress; Initial Catalog = DataBase1 ; user id = MyUsername ; password = MyPassword ;")
See SQLConnection Reference for more information as commented by #AlexK.

Impersonation succeeds but database connection fails

I have C# (.NET 4.5) code like this (simplified for demonstration) used to connect to a SQL Server 2012 database:
public static void Test(WindowsIdentity ident)
{
using (WindowsImpersonationContext ctx = ident.Impersonate())
{
using (SqlConnection con = new SqlConnection("Data Source=MyServer;Initial Catalog=MyDatabase;Persist Security Info=False;Integrated Security=SSPI;Network Library=dbmssocn"))
{
con.Open();
}
ctx.Undo();
}
}
The Open() method throws the following exception every time:
System.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
connection could be made because the target machine actively refused
it.)
The impersonation is succeeding because if I add tracing like this:
public static void Test(WindowsIdentity ident)
{
using (TextWriterTraceListener listener = new TextWriterTraceListener(#"C:\temp\trace.log"))
{
using (WindowsImpersonationContext ctx = ident.Impersonate())
{
listener.WriteLine("Impersonated");
using (SqlConnection con = new SqlConnection("Data Source=MyServer,MyPort;Initial Catalog=MyDatabase;Persist Security Info=False;Integrated Security=SSPI;Network Library=dbmssocn"))
{
listener.WriteLine("About to open connection; WindowsIdentity.GetCurrent().Name = " + WindowsIdentity.GetCurrent().Name);
con.Open();
}
ctx.Undo();
listener.WriteLine("Impersonation undone");
}
}
}
I get this:
Impersonated
About to open connection; WindowsIdentity.GetCurrent().Name = MyDomain\MyUser
If I put the exact same connection string in a .udl file, run it under the same "MyDomain\MyUser" account on the same machine, and click Test Connection, it succeeds. Since that's the case, I just don't see how the problem could be a firewall or anything of that nature. Does anyone know what could be going wrong? I do not have access to log onto the database server itself, so I cannot check its event log (etc.) at this point.
Your problem come from the connection string. The "Network Library = dbmssocn" in connection string will make client attempting to connect to SQL server on the UDP port 1434 rather than the TCP port 1433. You remove the "Network Library = dbmssocn" from the your application's connection string the application will connect to SQL server successfully.
The anonymous login failed error means that kerberos authentication failed for some reason.
Kerberos delegation (delegation is when your impersonated credentials are passed to a different machine) is relatively simple in theory. In practice it is fraught with gotcha's and can be one of the most frustrating things to troubleshoot.
In your case, it is entirely possible that from the standpoint of your program, the impersonation is succeeding, but the token it is passing to sql server isn't usable.
If you are lucky and have access to a really good network/system admin, then they can help you troubleshoot it.
Otherwise googling "sql server kerberos delegation" will point you in the right direction.
This is the kind of problem that requires substantial back and forth to resolve and is more suited to a forum than a Q&A site.

What is the difference between Java and C# when it comes to connect to Sql Server Database?

I am writing an application requires to connect to sql server. I prefer to write the App in Java. but When I try to connect to the server I got the connection refused error. I am using JTDS JDBC driver. I think it is due to the port 1433 or 1434 are not open. The server is in my work place and I can not change the ports. But funny enough, I use c# writing the same thing, it connects successfully. is it because SqlConnection class in C# library works better with ms sql server? or am I doing something wrong here? FYI, the server we are using in work is MS SERVER 2003.
Sorry I did not provide any code earlier. One tricky part is that the server we have is called "SERVER" on the local network.
C#:
SqlConnection objConnection = new SqlConnection("Data Source= SERVER\\SQLEXPRESS;Initial Catalog=SSS;Persist Security Info=True;User ID=user;Password=pass");
SqlCommand objcommand = new SqlCommand();
string strSQL;
objcommand.Connection = objConnection;
strSQL = "select * from company where companyid = #companyID ";
try
{
objConnection.Open();
SqlDataReader Query = objcommand.ExecuteReader();
while (Query.Read())
{
MessageBox.Show(Convert.ToString(Query["clientRef"]));
}
objConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error Retreiving info: " + ex.ToString(), "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
objConnection.Close();
}
As I am not really familiar with C#. I have got the code above from one of the colleges. and it returns the info correctly.
Java:
try{
Connection connection;
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:jtds:sqlserver://network.local/SERVER\\SQLEXPRESS:1433/SSS","user","pass");
System.out.println("Connection succeed!");
}
catch (Exception e) {
e.printStackTrace();
}
The java code above got Network error IOException: Connection refused error.
FYI: I can ping server.network.local successfully. But when I telnet server.network.local 1433/1434, I got telnet: Unable to connect to remote host: Connection refused.
Check how your .NET app is connecting. It may be as simple as it using named pipes, which JTDS supports as well.
It might be that the defaults are different, are you setting the port when you initialise your driver
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
Something like this jdbc:jtds:sqlserver://nameofyourdatabaseserver.or.ipaddress:port/yourdatabasename
Try using the full dns name for your server or the IP address
At the following link you will find a useful tutorial which describes in detail how to connect to MS SQLServer database, both from Java and C#. It also describes how to query the database, pass and retrieve data and much more. Hope you find it useful: http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html

Categories