Why I cannot connect to remote SQL server via C# application? - c#

I am new to C# and I am using windows forms.
I have 2 computers connected together via Ethernet cross cable (no domain used) and they communicate successfully. PC1 has windows 7 and it hosts SQL server (192.168.10.1), PC2 has C# application which connects to SQL server, the C# application as following:
namespace Remote_DB_Connection
{
public partial class Form1 : Form
{
SqlConnection MyConnection = new SqlConnection(#"Data Source=192.168.10.1\COFFEESHOP-PC,1433;Initial Catalog=mydb1;Trusted_Connection=True");
SqlCommand MyCommand = new SqlCommand();
DataTable DataTable = new DataTable();
SqlDataAdapter Sql_Data_Adapter = new SqlDataAdapter();
public Form1()
{
InitializeComponent();
MyConnection.Open();
MyCommand.CommandText = "SELECT * FROM Table1";
MyCommand.Connection = MyConnection;
Sql_Data_Adapter.SelectCommand = MyCommand;
Sql_Data_Adapter.Fill(DataTable);
button1.Text = Convert.ToString(DataTable.Rows[0]["Type"]);
button2.Text = Convert.ToString(DataTable.Rows[1]["Type"]);
button3.Text = Convert.ToString(DataTable.Rows[2]["Type"]);
MyCommand.Parameters.Clear();
Sql_Data_Adapter.Dispose();
MyConnection.Close();
}
}
}
now, when I run the application it throws this error : "The login is from an untrusted domain and cannot be used with Windows authentication" . in the sql server I login using windows authentication.
I had a look here and here they said I should create a username and password in sql server to remotely connect to sql server.
My question is: do I really have to create username and password in sql server to fix this error and connect to sql? I mean is there other ways to fix the issue?
Please help me, thank you

My question is: do I really have to create username and password in
sql server to fix this error and connect to sql?
Yes, because your machines are not part of a Windows Domain and Windows trusted authentication (Trusted_Connection=True) is not possible between them. If the machines are not part of a Windows Domain, SQL Server has no way of knowing who the client is unless it provides a username and a password in the connection string.

Related

C# VS 2019 SQLException: code works on Console App but not on WebForms app

I am working with VS 2019 in an ASP.NET Webforms project, and I am getting the following error when I try to execute a stored procedure on a remote SQL Server database:
System.Data.SqlClient.SqlException: 'Cannot open database "AMSTSUFSS" requested by the login. The login failed.
Login failed for user 'AMERICAS\espinjon'.'
I can login just fine with Windows Authentication in SSMS. Also, the same code works just fine in a console application, so there must be something going on with the form, the onlick event, the post....I don't know, and this is driving me crazy now! Please help.
This is the code and it fails on the line da.Fill(table);:
private static System.Data.DataTable GetListOflocIds(SqlConnection Conn, DateTime pStartDate, DateTime pEndDate)
{
System.Data.DataTable table = new System.Data.DataTable();
using (var cmd = new SqlCommand("UBOX.SP_GetPartnerList", Conn))
using (var da = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#StartDate", SqlDbType.Date).Value = pStartDate;
cmd.Parameters.Add("#EndDate", SqlDbType.Date).Value = pEndDate;
da.SelectCommand.CommandTimeout = 180;
da.Fill(table);
}
return table;
}
The problem might be related to the connection string.
Web apps sometimes run under different users in IIS and if the connection string doesn't explicitly state that it should use windows authentication, the web server might decide to use the credentials of that user instead.
Do you have Integrated Security=true; in your connection string? If not, adding it might help.
Also have a look at this answer here:
https://stackoverflow.com/a/1642508/1936841

Error while connecting UWP with remote SQL Server

I want to connect UWP to SQL Server Database. I used below code to do that.
private LogIn GetDetails(string UserName)
{
SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder();
connectionString.DataSource = "IP,Port";
connectionString.InitialCatalog = "Database Name";
connectionString.UserID = "sa";
connectionString.Password = "Password";
var logIn = new LogIn();
try
{
using (SqlConnection conn = new SqlConnection(connectionString.ConnectionString))
{
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = $"SELECT * FROM Login where UserName = '{UserName}'";
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
logIn.UserName = reader.GetString(0);
logIn.Password = reader.GetString(1);
logIn.Type = reader.GetString(2);
}
}
}
}
}
return logIn;
}
catch (Exception)
{
return null;
}
}
This code throws below exception
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
So I tried to open the SQL Server database in Server Explorer of Visual Studio. It connection opened properly but If I open the Tables folder It shows
So I tried to open the SQL Server database in SQL Server Management Studio. In that, It works properly. Connection opened properly and also I can view the tables inside Tables folder.
Don't have any idea about the place of error. Maybe in Code or Server Explorer of Visual Studio or SQL Server configuration of the server computer.
Solution tried
Creating a new SQL Server Login account and log in through new the
new account
Enabled Mixed Mode using below command
ALTER LOGIN [sa] WITH PASSWORD='newpassword', CHECK_POLICY=OFF
GO
ALTER LOGIN [sa] ENABLE
GO
You need to ensure that the required networking capabilities are declared in your appx manifest. Depending on your networking setup/configuration these are the ones to check for:
<Capability Name="internetClient" />
<Capability Name="internetClientServer" />
<Capability Name="privateNetworkClientServer" />
<uap:Capability Name="enterpriseAuthentication" />
You need to enable Mixed Mode and 'sa' user for logon.
ALTER LOGIN [sa] WITH PASSWORD='newpassword', CHECK_POLICY=OFF
GO
ALTER LOGIN [sa] ENABLE
GO
Taken from here.
Set below capabilities in Package.appxmanifest
Internet (Client & Server)
Private Network (Client & Server)

Error connecting to SQL server through string, not recognising user name or password

the problem I am having is connecting to an account on my sql server (2005) from an ASP.NET application.
Ive tried using the default sa login and users ive created already also the setting of the sql management studio are set to mixed properties, I have the string connection in the webconfig as well but also doesnt work.
c# code
//string conStr = ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString;
string conStr = #"server=JAMES-PC\SQLEXPRESS; database=projectDB; uid=james; password=password;";
string query = "SELECT [TaskID], [Task], [Start Date] AS Start_Date, [End Date] AS End_Date, [Priority], [Time Allowance] AS Time_Allowance, [Details], [Catagory] FROM [schedulerData0]";
SqlDataAdapter dataAdapt = new SqlDataAdapter(query, conStr);
DataTable table = new DataTable();
dataAdapt.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
The error message I receive is:
Login failed for user 'james'. The user is not associated with a trusted SQL Server connection.
Any help appreciated
James
Your SQL SERVER configured for Windows Only connections and you current windows user not associated as trusted. Try to configure your SQL SEREVR to accept Mixed Mode connections.
Try this,I'm not sure but hope it will work-
<connectionStrings>
<add name ="conStr" connectionString ="Initial Catalog = projectDB;
Data Source =JAMES-PC\SQLEXPRESS; User Id=james;Password=password;"/>
</connectionStrings>
try mapping projectDB to user:james. open SQL Server Management Studio, select Security - Logins, double click user:james, select page:User Mapping, check projectDB.
Please try the following format If It is Sql Server user mode,
ConStr = "Server=JAMES-PC\SQLEXPRESS;Database=projectDB;User Id=james;
Password=password;"
if you are trying to connect using windows,
then you must provide Trusted Connection = true

Connecting to a database server

There is a database server at IP address 192.168.1.11. There are several databases on that server. It has authentication, like user : System and pass : 123123 .
Now I want to connect to this server only, not any particular database, and then get a list of databases available on that server.
I know the normal procedure of connecting to a database with SqlConnection. But I'm wondering how I could just get connected to the server and get the list of the databases on that server.
I am using Visual Studio 2010 and SQL Server 2008-
run this query on a Method
SELECT [name]
FROM master.dbo.sysdatabases
WHERE dbid > 4
or by
String connString ="Data Source=localhost;User ID=username;Password=passwrd;";
using (SqlConnection sqlConn = new SqlConnection(connString))
{
sqlConn.Open();
DataTable tblDatabases = sqlConn.GetSchema("Databases");
sqlConn.Close();
DataTable td = tblDatabases.Select("dbid>6").CopyToDataTable();
}

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