Remote connect to SQL server - trusted connection, windows credentials - c#

Sorry for the confusing name, I did not know of better one. There is a network with SQL 2005 server. I am provided with the windows account information to this computer so I can use remote desktop or map its drives. The SQL uses trusted connection. I am thinking whether I can connect remotely only to the SQL server? Thanks

This is based on my experience with SQL Server, but may not be entirely complete in scope.
SQL Server Manager will let you connect to the server instance with windows credentials, but to access the database tables you will need to create a login within SQL Server. Using SQL Server Manager, you can do this under the Security folder of the hierarchy of objects in the left column.
Next you will need to create a database (if one doesn't already exist that you are interested in using) and in that database's Security folder, create a user that corresponds to the login. When doing this you will also need to assign the permissions of the user (select, insert, delete, etc.).
Once that is complete, you can access the server anywhere on the network with the appropriate credentials, but you will need to make sure that there are no blocked ports, etc. from a network perspective.
In C# the statement to create a new connection looks like this:
SqlConnection conn = new SqlConnection("user id = username; " +
"password = secret; " +
"server = servername\sqlexpress; " +
"database = databasename; " +
"connection timeout = 30");
Hope that helps.

Related

C# connect WinForm App running locally via Remote Desktop (or other) to a Database

EDIT
RDP is just the current way I do this, if there is another way to connect to a database in a different environment I will do that. Ideally I want this to connect to the database as it would if the executable was in the RDP environment and show no indication of connecting to the DB via the other environment.
EDIT 2
I have also tried adding a second connection string and opening it then having my current connection string immediately after, that didn't work.
I have a C# Win Forms application which connects to a database, this works fine except I need to RDP into the correct environment and have the executable ran from there to do so.
Is it possible to do the RDP connection inside of the application then connect to the database without having to have the executable inside the RDP.
I have tried to build up a connection string using the MSTSCLib library which I found here however this isn't working at code level anyway.
Code:
private void rdpConnect_Click(object sender, EventArgs e)
{
MSTerminalServiceControl1.Server = rdpServer.Text;
MSTerminalServiceControl1.UserName = rdpUserName.Text;
IMsTscNonScriptable secured = (IMsTscNonScriptable)MSTerminalServiceControl1.GetOcx();
secured.ClearTextPassword = rdpPassword.Text;
MSTerminalServiceControl1.Connect();
}
private void rdpDisconnect_Click(object sender, EventArgs e)
{
MSTerminalServiceControl1.Disconnect();
}
Current Path:
Desired Path:
I'm sure, that can not work, because...
RDP (Remote Desktop Protocol) is a Protocol to connect you from a remote machine to a session on a Terminal Server. That's the purpose. In that session, you can start programs, open documents and do your work. Like you were sitting in front of that machine. The benefit is, this can be done by multiple users, depending only on the number of user licenses and hardware power.
There a some special cases, e.g. you can start a program automatically on start up. Then your session is limited to this program and will end, when the program ends. But this is only a restricting. You will still start a session for that.
Also, there is a small version of Terminal Server build in every windows version, not only servers. This can be used a for a remote connection in the same way.
So, sad that, RDP can not connect to a database. In no way. You need a program for that. You can build a local program with a RDP-Client inside. That can connect to a session on a remote machine and start another program, that connects to the database. But you will have no communication between the to programs by default, so there is no benefit.
I think, like others said, the best is to connect to the database directly.
Looks like you do not have references to the ActiveX Control.
In your Toolbox Choose the COM Component : Microsoft RDP Control - version x
The version here is important it should match the installed RDP version, once you have added this in your tool box drop it on your form, if there is version mismatch it would throw error. I would say start from the latest version of control and go down till you are able to successfully add it to your form. The MSTerminalServiceControl1 in your code is actually the name of this control that you should thus put on your form.
What you need is to Connect multiple sql users to one database and no to use RDP.
you should write a special connection string, for each user something like below:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=" + UserName + ";"
"Password=" + Password + ";";
conn.Open();
Put this in a class that accepts the username and password.
Full example:
class myConnection
{
public static SqlConnection GetConnection(string UserName, string Password)
{
string str = "Data Source=ServerName;Initial Catalog=DataBaseName;User id=" +
UserName + ";Password=" + Password + ";";
SQlConnection con = new SqlConnection(str);
con.Open();
return con;
}
}
Then connect each user to DB directly.
Provided you have app.config file for the executable, update the connection string parameter to point to the ip of rdp server.
Before you do this enable database port on firewall and also enable remote connections to database.
For mssql server.
Run sql server configuration manager.
Select database instance.
Enable tcp/ip under network configuration.
Under io addresses tab.
Set tcp port to 1443.
Restart instance.
Data Source=IP,1443\dbservername;
I hop this can be a starting point.
I've seen a Network Administrator configured our normal winform application to be opened remotely over the Internet using Citrix.
We made no changes to the exectuable file.
It will launch the application in the Citrix Virtual Server.
The problem is that it's a paid software.

Connect c# to a SQL Server in different domain

I have an c# app that tries to connect to a SQL Server that is in the same network but out of domain. I'm trying to use SqlConnection (I would prefer not use ODBC or ole db).
My code is the follow:
con.ConnectionString =
"Server=PCX\\SQL;"+
"Initial Catalog=BBDD_SinGuid;"+
"User id=\\\\PCX\\user;"+
"Password=passwordofuser;";
And I'm sure that the user and the password are correct and are allow to connect to the SQL Server. The error that throws is a fail in the login with the user \PCX\user.
I'm missing something?
you need to add trusted connectioon here..
Provider=SQLNCLI10;Server=myServerName\theInstanceName;Database=myDataBase;
Trusted_Connection=yes;
for more information you check below link it's has lot's of suggestion may be you will get your answer.
http://www.connectionstrings.com/sql-server-2008/

Connect to database in network drive

I am a newbie to SQL Server and .net. Please let me know if my question is not clear before down voting.
I am working on a Windows application with C#. I should give option to users to connect to a .mdf file on a network drive. On my machine, I have Windows and SQL Server authentication. Users have SQL authentication hence I should use userid and pwd. Myself and users work on that network drive, read/write/modify. We pretty much share documents, add and delete docs from network drive.
Here is the designer
I will choose the SQL Server database .mdf file which is located in network drive and then do test connection. For Test Connection this is the code
string sTemp = System.Configuration.ConfigurationManager.AppSettings["connectionStringShare"];
string connectionString = sTemp.Replace("{AppDir}", txtDB.Text.Trim());
using (SqlConnection objSqlConnection = new SqlConnection(connectionString))
{
try
{
objSqlConnection.Open();
objSqlConnection.Close();
MessageBox.Show("Connection is successfull");
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message.ToString());
}
}
This is the connection string
<add key="connectionStringShare"
value="Data Source=.\SQLEXPRESS;Initial Catalog=TableSQLExpress;AttachDBFilename={AppDir};Integrated Security=SSPI;user id=sa;password=pwd;" />
Here is the error message I got
Directory lookup for the file "S:\zrep\TableSQLExpress.mdf" failed with the operating system error 3(The system cannot find the path specified.).
Cannot attach the file 'S:\zrep\TableSQLExpress.mdf' as database 'TableSQLExpress'.
I changed connection string and tried also tired using windows authentication. No luck. Let me know if I need to provide any additional details. Since I am newbie to this field please give me detailed answer. I am glad to find this group. Thanks for everyone who looked into this.
When you use server-based SQL Server (i.e. Microsoft SQL Server Express) you are unable to share database file via network drive, it is by design. Even if you override default SQL Server behavior with a switch and enable UNC paths for databases, your data will be corrupted by multiple server instances trying to use single database MDF file. If you need to host database in serverless environment (using only a network drive), you may opt to Microsoft SQL Server Compact (SQL Server CE) edition. But be aware that in such case only one user will be able to access database file at the same time (exclusive locking -> low performance). Plus SQL Server CE does not have stored procs.

Error attaching a database (.mdf file) to SQL Server

I'm having trouble attaching a database DBName.mdf to a network SQL Server. The admin can manually attach the database but if I try, I get the following error message.
Database 'DBName' cannot be upgraded because it is read-only, has read-only files or the user does not have permissions to modify some of the files. Make the database or files writeable, and rerun recovery. (Microsoft SQL Server, Error: 3415)
Here is my code:
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString = #"Server=" + SQLServerName + ";database=master;User ID=" + UserName + ";Pwd=" + Password; ;
try
{
conn.Open();
System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand("CREATE DATABASE DBName ON ( FILENAME = '" + #"C:\DBName.mdf" + "' ), ( FILENAME = '" + #"C:\DBName_log.ldf" + "' ) FOR ATTACH", conn);
com.ExecuteScalar();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
Here is the details of SQL Server
- Product - Microsoft SQL Server Express Edition (64-bit)
- Version - 11.0.2218.0
I can create a new database just fine but cannot attach an existing database. What am I missing here?
Any help will be appreciated.
I figured out what the problem was.
This link was helpful in figuring out the problem.
http://www.sqlservercentral.com/Forums/FindPost1367859.aspx
The user under which the SQL Service was running didn't have full access permissions to that folder. I gave the user full permission and everything worked fine.
I had the same error trying to attach via SQL server management studio.
Running SQL server Management studio as Administrator solved this problem for me.
Info gleaned from here http://www.nickyvv.com/2013/02/database-databasename-cannot-be.html.
I also faced the similar problems and I resolved it using both approaches listed above by Butters and pblack. To sum up they are:
Go to the system services and find SQL Server Database service.
Right click on the service and select properties
Go to the Log On tab
If the "Log On As" user from your service is a user account, make sure that user account has Full Control on that folder.
If the "Log On As" user from your service is "Network Service" or "Local System" those account should already have access, but go ahead and add them and give them Full Control.
Lastly, RUN SQL Server management studio using Administrative privileges
I also faced similar situation while using T-SQL Script but i choose another way through SSMS. Here are some easy steps that are very helpful to you to attach SQL MDF file through SQL Server Management Studio.
Go through Start Button->All Programs->SQL Server XXXX->SQL Server Management Studio
Login in it
Select Object Explorer enlisted databases
Then Right click on it and Select Attach database
Database Attachment Windows appears on the Screen then click on ADD button
Then you need to select MDF file which you want to attach and click OK
Confirm it and Click OK
Database is successfully attached. You can checkout in the Databases list.

can not open database on localnetworks

I write a win app,and i create my database on the server by codes.now every client on local network can't login to my database and this error occured
:"cannot open database "test" requested by the login.the login failed for user "farzane".
the connectionstring for to make my database is:
ConnectionString=#"Data Source=SERVER\SQLEXPRESS;Initial Catalog=master;Integrated security=SSPI;Persist Security Info=False";
and it's my connection string for open my database:
ConnectionString=#"Data Source=SERVER\SQLEXPRESS;Initial Catalog=test;Integrated security=SSPI;Persist Security Info=False";
how can give permission for logining to my database to any client with codes???
thanks in advance for any help.
I would check two things here:
Ensure that your SQL Express install allows remote connections. (Simple to check using SQL Server Studio Manager).
You are using trusted authentication in your connection string. You have to explicitly give users on your domain access on the database. You will have to this in SQL Server.
are you using a domain for the network ?
if yes then make sure that the user name has access to the SQL server
if you're using a workgroup then it won't work... just create a user on the sql server and use the sql server auth at the server and connection string
Points i concluded:
First of all the users who are going to create the database , must be authorized to use master database. So ask your admin to allow permission to farzanne.
If you(farzanne) are admin, set farzanne to create databases permission to true. Or the other users that might create dbs. Also, if you allow all users then it will be difficult to handle, your application, so be alert.
What is the need of the dynamically createing database from application. Is this a part of setup or deployment or you are creating an isolated space that is different user different database.

Categories

Resources