Our software uses a SqlConnection object to get data from SQL Server. It is running fine for many sites, but for one specific user - it cannot connect to the server. I get an exception:
A network-related or instance-specific error occurred while
establishing a connection to SQL Server.
On this PC the executable file is located on a shared drive. If we copy the executable to a local drive (the desktop) and run it from there, the connection is successful.
Here is what I use to connect to SQL Server:
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder.DataSource = SQLServerName;
builder.InitialCatalog = SQLDBName;
builder.WorkstationID = SQLServerName;
builder.PacketSize = 4096;
builder.IntegratedSecurity = true;
builder.PersistSecurityInfo = true;
builder.ApplicationName = "App";
builder.MultipleActiveResultSets = true;
using (SqlConnection myDbConn = new SqlConnection())
{
myDbConn.ConnectionString = builder.ConnectionString;
try
{
myDbConn.Open();
if (myDbConn.State != System.Data.ConnectionState.Open)
{
myDbConn.Close();
return false;
}
myDbConn.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
myDbConn.Close();
return false;
}
}
return true;
We have this problem only for a specific user on a specific PC (running Windows 7). I can't figure why moving the program from a network drive to a local drive would change its behavior. I tried adding trust assemblies full control over the shared drive with no results.
Related
Using C#, .Net framework 4.8, SQLite 1.0.115
I am using System.Data.SQLite.SQLiteConnection to open a sqllite database on the network drive. But it fails with "unable to open database file". While debugging it I found that it is always pointing to the local drive instead of the network.
example: I have provided "\\NW\test\DB\test.sqlite" as a data source in the connection string. But when I see an exception it says can't find the file in "C:\NW\test\DB\test.sqlite". My program runs on C: drive.
private SQLiteConnection _connection;
var builder = new SQLiteConnectionStringBuilder
{
DataSource = "\\\\NW\\test\\DB\\test.sqlite",
Version = 3,
ForeignKeys = true,
};
var connectionString = builder.ConnectionString;
if (_connection == null)
{
_connection = CreateConnection(connectionString );
_connection.Open();
}
return _connection.BeginTransaction(isolationLevel);
On connection open, I am getting this exception
SQLite error (14): os_win.c:47688: (3) winOpen(C:\NW\test\DB\test.sqlite) - The system cannot find the path specified.
Does anyone know why it is pointing to a local drive instead of the network?
By doing multiple trials and errors this change fixed the issue
private SQLiteConnection _connection;
var builder = new SQLiteConnectionStringBuilder
{
DataSource = #"\\\\NW\\test\\DB\\test.sqlite",
Version = 3,
ForeignKeys = true,
};
var connectionString = builder.ConnectionString;
if (_connection == null)
{
_connection = CreateConnection(connectionString );
_connection.Open();
}
return _connection.BeginTransaction(isolationLevel);
So, in the Datasource it needs "\\\\\\\\NW\\test\\DB\\test.sqlite" path. Not sure why so many back slashes but this fixed the problem.
Want to restore a database backup from linked server A to a database located on linked-server B using C#. prefer to use SMO.
I can restore from my local backup to local machine.
{
conn = new ServerConnection
{
ConnectionString = #"Data Source =
(localdb)\MSSQLLocalDb;Initial Catalog=master;Integrated Security=true",
};
try
{
//Restore Full
srv = new Server(conn);
//lsrv = srv.LinkedServers[#"DEVSQL\ALPHA"]; need to figure out how to restore to linked server instead of local.
//srv.KillAllProcesses("G4TestNew");
var res = new Restore();
res.Database = "G4TestNew";
res.Action = RestoreActionType.Database;
filePath = #"\\CABCSERVER\Database\Temp\Full.bak";
res.Devices.AddDevice(filePath, DeviceType.File);
res.ReplaceDatabase = true;
res.NoRecovery = true;
var dataFile = new RelocateFile("G4Test", #"C:\TBD\G4Test.mdf");
var logFile = new RelocateFile("G4Test_log", #"C:\TBD\G4TestNew.ldf");
res.RelocateFiles.Add(dataFile);
res.RelocateFiles.Add(logFile);
res.SqlRestore(srv);
}
EDIT(Adding more detail):.
In this case the linked servers are accessed via 'sql server authentication' and application does not have access to the credential required to connect directly and can use 'Integrated Security' to connect to localdb only.
In SMO you would not connect to one server and then administer a linked server. Instead connect directly to the target server. eg:
ConnectionString = #"Data Source =
DEVSQL\ALPHA;Initial Catalog=master;Integrated Security=true",
srv = new Server(conn);
In my C# project I have included ChilkatDotNet2.dll in order to connect to a SFTP server. For the moment, I have tried to implemt a simple connection method like the following:
Chilkat.Ftp2 F = null;
F = (Chilkat.Ftp2)new Chilkat.Ftp2();
F.Hostname = "sftp.domain.com";
F.Username = "username";
F.Password = "password";
F.Port = 22;
F.AuthTls = true;
if (!(F.Connect())) {
MainFrm.set_AlertMessage(F.ConnectFailReason);
}
and it always fails connecting and I always get the error 200 which means
Connected, but failed to receive greeting from FTP server.
according to Chilkat documentation.
What am I missing? I have tried to connect to a simple ftp server test (without SSL/TLS) and it connects correctly so I think I am missing something.
The credentials I was given are correct as I tried to connect to the SFTP server with Filezilla.
Thank you.
UPDATE
Chilkat.SFtp v_SFTP = null;
v_SFTP = (Chilkat.SFtp)new Chilkat.SFtp();
if (v_SFTP.Connect("sftp.domain.com", 22) {
if (v_SFTP.AuthenticatePw("username", "password")) {
IDVariant v_SUCCESS = null;
bool v_SUCCESS = v_SFTP.InitializeSftp();
}
}
else {
MainFrm.set_AlertMessage(v_SFTP.LastErrorText);
}
F = (Chilkat.Ftp2)new Chilkat.Ftp2();
Chilkat.Ftp2 is an FTP client. It supports the FTP protocol. SFTP is a completely different protocol which just happens to have a similar name.
If you want to connect to an SFTP server using Chilkat, look at Chilkat.SFtp.
Actually, i wanted to check is my connection string valid.
There are asp.net mvc web app and mysql db deployed on azure, so i want use second thing in first. So, i added db to visual studio server explorer - db and all tables are visible.
Now i tried to add connectionstring to my project, and, wow, there are two of them i found:
First: In Visual studio data connection properties:
server=us-cdbr-azure-central-a.cloudapp.net;user id=userid;persistsecurityinfo=True;database=crawlerdb
Second: In azure workplace's database property:
Database=CrawlerDB;Data Source=us-cdbr-azure-central-a.cloudapp.net;User Id=userid;Password=userpass
And both of them doesn't work. Never lucky.
Connection state checking code:
using (SqlConnection conn = new SqlConnection(connstr))
{
try
{
conn.Open();
var q = conn.State;
}
catch(Exception ex)
{
var q = ex.Message;
}
}
What am i doing wrong?:) Tell me plz:)
public class CrawledDataContext : DbContext
{
public CrawledDataContext()
{
Database.SetInitializer<CrawledDataContext>(null);
using (SqlConnection conn = new SqlConnection("server=us-cdbr-azure-central-a.cloudapp.net;user id=bb15193d20f901;persistsecurityinfo=True;database=crawlerdb"))
{
try
{
conn.Open();
var q = conn.State;
}
catch(Exception ex)
{
var q = ex.Message;
}
}
}
public DbSet<GroupInfo> GroupInfoes { get; set; }
}
Here is 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
SqlConnection is for SQL Server Databases. you should use MySqlConnection instead.
using (MySqlConnection conn = new MySqlConnection("server..."){}
When running the code below, I keep getting "access is denied", but i have full administrative rights on the folder.
{"Cannot open backup device '\\\\networkDrive\backups\\'. Operating system error 5(Access is denied.).\r\nBACKUP DATABASE is terminating abnormally."}
the folder target is #"\networkDrive\backups";
I've also tried #"C:\backups"\ and #"C:\backups"
private static string publicConString = "server=myServer;Trusted_Connection=Yes;persist security info=False;connection timeout=120";
public static void BackupDatabase(String databaseName, String userName, String password, String serverName, String destinationPath)
{
Backup sqlBackup = new Backup();
sqlBackup.Action = BackupActionType.Database;
sqlBackup.BackupSetDescription = "ArchiveDataBase:" +
DateTime.Now.ToShortDateString();
sqlBackup.BackupSetName = "Archive";
sqlBackup.Database = databaseName;
BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
SqlConnection sqlCon = new SqlConnection(publicConString);
ServerConnection connection = new ServerConnection(sqlCon);
Server sqlServer = new Server(connection);
Database db = sqlServer.Databases[databaseName];
sqlBackup.Initialize = true;
sqlBackup.Checksum = true;
sqlBackup.ContinueAfterError = true;
sqlBackup.Devices.Add(deviceItem);
sqlBackup.Incremental = false;
sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
//sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;
sqlBackup.FormatMedia = false;
sqlBackup.SqlBackup(sqlServer);
From your description, I think you would like to back up database to a network share folder, right?
Based on the error message, I think the SQL Server service account doesn’t have sufficient permission on the share folder. Please ensure the SQL Server service account is a domain account and it has sufficient permissions.
Please refer to this info for more information.
You cannot back up databases to a network drive if your account have not sufficient permissions to access the network drive.