C# Connect to MS SQL Server using Active Directory Service Account - c#

I have a stand alone application that works great with a Local user account in MS SQL. When I try to use an active directory service account instead I appear to be running into problems.
It appears Microsoft want's the exe to run as the domain user service account which is not an option for me. Looking at alternatives, one person mentioned having main exe launching a second exe that does the work or having a local windows service.. neither of these are an option either. It feels like this is getting more complex then it needs to be.
Here is an example of the piece of code I am working with:
private void MakeConnection(){
string ServerNM = #"MyServer";
string Database = #"Test01";
string Username = #"testdomain\testuser";
string Password = #"testpass";
string connection_string = "Server=" + ServerNM
+ "; Database=" + Database
+ "; User ID=" + Username
+ "; Password=" + Password
+ "; Max Pool Size= 1000;";
try {
SqlConnection oSqlConnectionTest = new SqlConnection(connection_string);
oSqlConnectionTest.Open();
}catch(Exception oException){
MessageBox.Show("Error: " + oException.ToString());
}
}
Is this a real limitation or am I missing something?

SQL Server does not accept domain accounts in the connection string for security reasons.

Related

Can't connect to named instance of sql server asp.net c#

I can't connect via ASP.NET to a named instance of a sql server, that itsn't the default instance.
My servername is NAMEOFSERVER\NAMEOFINSTANCE.
If I try to connect to the default instance of the server, it works.
I use the following connection string:
connection_string = "Data Source=" + servername + ";Initial Catalog=" + db_catalog + ";User Id=" + user + ";Password=" + password + ";persist security info=False;Trusted_Connection=No;Connection Timeout=1000"
The SQL Server Browser service is running.
Make sure your connection string have the pattern above:
var connectionString = $"Data Source=myServerName\\myInstanceName;Database=myDataBase;User Id=myUsername; Password=myPassword;",
Also, make sure you can connect via SQL Management Studio, since instances of the SQL Server can limit access to some users (make sure you connect to the same user name + password you want your app to use).
EDIT
If the user you are using to connect is not part of a Windows account, please open your instances security configuration and make sure Mixed Mode is enabled.
https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/change-server-authentication-mode
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/authentication-in-sql-server
You might want to check if your variable "servername" contains a double backslash. This is needed because backslash is a escape character.
connection_string = "Data Source=" + servername.Replace("\\", "\\\\") + ";Initial Catalog=" + db_catalog + ";User Id=" + user + ";Password=" + password + ";persist security info=False;Trusted_Connection=No;Connection Timeout=1000"

Is there any difference between connection string for SQL server express and SQL server?

In my application, i make a dynamic connection string:
server = "Server = .\\" + this.comboBoxListInstances.SelectedItem.ToString() + ";";
connectionString = server + attachDatabase + databaseName + "Integrated Security = true";
On my laptop (using SQL server 2008 express), the result is:
// server = "Server = .\\SQLEXPRESS;" (I select SQLEXRESS in comboBox)
// attachDatabase = "AttachDbFileName = |DataDirectory|\\Resources\\DT.mdf;"
// databaseName = "Database = DATA;";
// so the conectionString is : "Server = .\\SQLEXPRESS;AttachDbFileName = |DataDirectory|\\Resources\\DT.mdf;Database = DATA;Integrated Security = true"
I read registry to find all SQL server Instances and let the user choose which they want.
This conectionString work fine on my laptop and my friend who use SQL server express too. However, when i run my app on another friend's laptop with SQL server 2008 R2 installed, it throws an exception:
It say the connection string is invalid, It is :
"Server = .\\MSSQLSERVER;AttachDbFileName = |DataDirectory|\\Resources\\DT.mdf;Database = DATA;Integrated Security = true"
when I try to temporarily disable comboBoxListInstance and use this conectionString
"Server = (local);AttachDbFileName = |DataDirectory|\\Resources\\DT.mdf;Database = DATA;Integrated Security = true"
The app works! So, I think there is a difference between the conection string for SQL server express and SQL server. Is it right? There is a question similar to mine here, and they say that there is no difference. If they are right, what is the problem of my connectionString?
P/S: sorry for my bad grammar
It looks like you just proved that SqlExpress installs its default named instance as "MSSQLSERVER" where as full sql installs an unnamed default instance of blank.
(local) means " .\ " " 127.0.0.1" WHATEVER instance is at 1433.
.MSSQLEXPRESS means explicitly .\MSSQLEXPRESS which may or may not be the (local) default instance.
As An Aside usually the most relevant difference at this point is that regular SQL will install with the ports open and TCP clients ready to go.
SQL Express will only allow local "dev" type of connections until you activate the external ports and client protocols.

How to connect my app to a database

I am trying to connect my app, developed in C# with a SQL Server database.
The program is done! It's a mobile app.
My database is on C:\ProgramFiles\MyAppName\MyDatabase.sdf
My code line is:
SqlConnection conn = new SqlConnection("server =" + iP.Text +"," + port.Text + ";integrated security=false;Initial Catalog=" + DB.Text + ";User ID=" + userName.Text + ";Password=" + Pass.Text + ";Trusted_Connection=False;");
iP.Text = my IP (102.168.XXX.XXX)
port.Text = 49214 or 1433
DB.Text = "MyDatabase.sdf"
userName.Text= "sa"
pass.Text= "MyPass"
But when I try to connect it, the app says:
er.Message = "El servidor SQL Server no existe o se ha denegado el acceso.
My server name is the same that my userName?
The application was made by someone else, I did nothing. But now I have to change some things and make it better. There is no manual
Any idea? I really don't know what to do
You are using Sql Server Compact Edition (SDF file) not Sql Server.
The classes needed to connect to this kind of database are different
SqlCeConnection conn = new SqlCeConnection(......)
The classes for Sql Server cannot parse correctly your connection string and you get the mentioned error. Of course, the classes for Sql Compact Edition require a reference to the appropriate DLL
System.Data.SqlServerCe.dll
and the appropriate using statement at the beginning of your code file
using System.Data.SqlServerCe;
As last note, the connection string for a SQL CE database is simply
"Data Source = MyDatabase.sdf; Password ='<pwd>'"
doesn't seem possible to pass a specific user. See connectionstrings.com

Retrieving Database Compatibility Level - Different Result for Same Server/DB, Different Users

I have the following code to determine a SQL Server database's compatibility level:
Microsoft.SqlServer.Management.Smo.Server server = new Server(myServerName);
if (!server.Databases.Contains(database))
{ throw new ArgumentException("Specified database ('" + myDBName+ "') not found on '" + myServerName + "'"); }
string connstr = string.Format("Data Source={0};" +
"Persist Security Info=False;" +
"User ID={1};" +
"Password={2};Enlist=False;", myServerName, username, password);
server.ConnectionContext.ConnectionString = connstr;
Microsoft.SqlServer.Management.Smo.Database db = server.Databases[myDBName];
DataSet ds = db.ExecuteWithResults(#"select compatibility_level
from sys.databases where name=db_name()");
I have two users, one of which is able to run this code and get the proper value back. Another user runs this code connecting to the same Server/Database with the exact same credentials and the DataSet returned contains no rows.
What could possibly be the difference between the two users that would cause one to get no result back for the same query? Is there a better way to get Database compatibility?
By the way, this code runs/works on SQL Server 2005 through 2012.
Edit: I should have pointed out that myServerName, myDBName, username, and password are always the same--the only difference is the two different Windows users running the code.
I suspect that the user who returns results has the VIEW_ANY_DEFINITON permission granted to his login. Grant this permission to the other user and he should get the results back.

C# system.io.filenotfoundexception

I am creating an app for my work to track behavior management over the course of a school year. To do this, I obviously needed a database. I built the program so that it would, when opened, check to see if the database exists, and if it doesn't, it creates one, and inputs the schema. This works perfectly on my dev computer, but when I switch it to a computer using windows XP it gives an error saying system.io.filenotfoundexception. I can't figure out why it won't create the database.
I am using Visual C# 2010 Express. And the database is made in sql server ce.
if (!File.Exists("chart.sdf"))//Checks if file is already in existance when app is opened
{
dbCreated = createDb();//If there is no database, creates one
}
public bool createDb()//Creates the database if needed
{
bool success = true;
//Holds sql schema for the table
string[] tableCreateArr ={"create table childNameId"
+ "(childId INT IDENTITY PRIMARY KEY, "
+ "childFName nchar(40), "
+ "childLName nchar(40));",
"create table leaderNameId"
+ "(leaderId INT IDENTITY PRIMARY KEY, "
+ "leaderFName nchar(40), "
+ "leaderLName nchar(40));",
"create table TagPulledId"
+ "(tagId INT IDENTITY PRIMARY KEY, "
+ "childId INT, "
+ "leaderId INT, "
+ "day TINYINT, "
+ "month TINYINT, "
+ "year INT);",
"CREATE TABLE tagInfo"
+ "(tagId INT, "
+ "color nchar(10), "
+ "description ntext)"};
SqlCeEngine dbCreate = new SqlCeEngine(connectString()); // creates the database obj
dbCreate.CreateDatabase(); // creates the database file
SqlCeConnection tempConnect = new SqlCeConnection(connectString());//Connects to the new database
SqlCeCommand objCmd = new SqlCeCommand();//Creates an sql command obj
tempConnect.Open(); // opens the connection
objCmd.Connection = tempConnect; //Connects the command obj
foreach (string strCmd in tableCreateArr)//Iterates throught he sql schema to create the tables
{
try
{
objCmd.CommandText = strCmd; //sets the CommandText to the next schema entry in the array
objCmd.ExecuteNonQuery(); //Executes the create query
}
catch (SqlCeException sqlError)
{
MessageBox.Show(sqlError.Message, "SQL Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
success = false;
}
}
tempConnect.Close();
return success;
}
I can't figure out why the app isn't making the database, it seems to work on some computers, while not working on others. Any help would be great! Thank you.
if (!File.Exists("chart.sdf"))
You seem to want to create the database in the same directory as your program. Yes, that will work on your dev machine but that's not going to work on a regular machine. The typical install directory (c:\program files\etc) does not permit write access to files.
You will need to use Environment.GetFolderPath() to get an ApplicationData directory that you can write to.
It is often a lot easier and less error prone to let an installer create the appdata directory and copy the initial .sdf file in there. Albeit that Setup projects are not supported by the Express edition. There does come a point where hacking code to work around the Express edition's restrictions is defeating the price of the product license. You're pretty close here.
Make sure you have deployed all the dll Sql Server Compacts need. I'm not sure you get them when you install .NET framework. The dll needed are :
sqlceca35.dll
sqlcecompact35.dll
sqlceer35EN.dll
sqlceme35.dll
sqlceoledb35.dll
sqlceqp35.dll
sqlcese35.dll
You can find more details on this MSDN page about Sql Compact Deployment for various versions of the database engine.

Categories

Resources