I have a simple windows service and within this service I'm trying to connect to a sql server in a timer block (I tried to do that only once in onStart method -> same result).
For the moment I'm trying just to execute a select, using the following code:
using (SqlConnection sc = new SqlConnection())
{
var sqlConnection = new SqlConnection(_sqlConnectionString);
string commanda = "SELECT Moneda, SimbolMoneda FROM NomMoneda WHERE Moneda != '' AND SimbolMoneda != ''";
SqlCommand command = new SqlCommand(commanda, sqlConnection);
command.CommandType = System.Data.CommandType.Text;
IDataReader reader;
sc.ConnectionString = _sqlConnectionString;
sc.Open();
reader = command.ExecuteReader(CommandBehavior.CloseConnection);
}
I attached the service to debug, and I noticed that it didn't pass by this line of code sc.Open().
The service is not on the same machine as the sql server, but I have tried to install it under different users, LocalSystem, NetworkService, user within the same domain with the sql server, but with no result.
Any help would be appreciated.
It looks like you may have a logical error in this code. You are using sc for the SqlConnection, but when you create the command object you use sqlConnection, which is never actually opened.
This line is the problem:
SqlCommand command = new SqlCommand(commanda, sqlConnection);
Try the following instead:
SqlCommand command = new SqlCommand(commanda, sc);
EDIT at 10:22 following user comment
Just to confirm that you have made the change as indicated, I've re-jigged your code. Could you try the following:
using (SqlConnection sc = new SqlConnection())
{
sc.ConnectionString = _sqlConnectionString;
sc.Open();
string commanda = "SELECT Moneda, SimbolMoneda FROM NomMoneda WHERE Moneda != '' AND SimbolMoneda != ''";
SqlCommand command = new SqlCommand(commanda, sc);
command.CommandType = System.Data.CommandType.Text;
IDataReader reader;
reader = command.ExecuteReader();
}
I would expect that whatever the issue is it would be easier to figure out if you had a logging mechanism in place to catch and log unhandled exceptions. Due to the fact that Windows Services do not have a user interface you should implement logging from the beginning. Otherwise you will get to a point where the service terminates unexpectedly and what little information you gather from the system logs won't be enough to help you.
In short, add file logging and you'll probably figure out the issue immediately.
The problem was simple, but hard to detect. My connection string wasn't prefixed with the # char:
ex: _connectionString = #"Data Source =.......";
Related
i am creating connection string for oracle in c#
below is my code
OracleConnection cn = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.0.5 )(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=ORCL)));User Id=nTireoffice ;Password=nTireoffice;");
DataTable dt = new DataTable();
string strSql = " select to_number (nvl(max(nvl(Region_ID ,0)),0)+1 ) as No from BO_REGION_MASTER ;";
cn.Open();
OracleDataAdapter objSda = new OracleDataAdapter(strSql, cn);
objSda.Fill(dt);
string s = dt.Rows[0][0].ToString();
its throwing exception ORA-06413: Connection not open.
i am using windows 8 enterprises 64 bit os
thank u...
Have a look here. (This is a very useful site for clues about most ORA errors.)
It sounds like it could be the folder your executable is in, or the actual name of your executable.
PS It would be useful if you could tell us the actual line the error occurs on.
I've created the connection like this.
ora_cmd = new OracleCommand();
ora_con = new OracleConnection("Data Source={YOUR_HOST}:{YOUR_PORT}/{YOUR_DB};Persist Security Info=True;User ID={YOUR_ID};Password={YOUR_PASSWORD};Pooling=True;Max Pool Size=200;");
ora_cmd.Connection = ora_con;
ora_connect.Open();
Then use the ora_cmd to executes statements
The code below has been used successfully in other parts of the application without fault.
However, for some reason, an InvalidOperationException is thrown when it comes time to read data from the Access database.
The code below contains only the essentials (not the items that are trying to be read, as that would made readability difficult).
Why am I getting this error, despite the fact I am calling the "Open" method on my connection?
Code follows:
string connString = "Provider= Microsoft.ACE.OLEDB.12.0;" + "Data Source= C:\\temp\\IntelliMed.accdb";
string queryString = "SELECT patientID, firstName, lastName, patientGender, dateOfBirth, residentialAddress, postalAddress, nationalHealthNumber, telephoneNumber, cellphoneNumber, cscNumber FROM PatientRecord WHERE patientID = #patientID";
try
{
using (OleDbConnection con = new OleDbConnection(connString))
{
con.Open();
OleDbCommand command = new OleDbCommand();
command.CommandText = queryString;
command.Parameters.AddWithValue("#patientID", patientID);
command.Connection = ctnPatientRecord;
OleDbDataReader prescriptionDetailsReader = command.ExecuteReader();
while (prescriptionDetailsReader.Read())
{
//Read stuff.
}
//Close the reader.
}
//Close the connection.
} //Method "closing" bracket.
Any help is gratefully received. Thanks in advance.
I think you should associate the command with the connection
command.Connection = con;
or better yet create the command through the connection using the CreateCommand method instead of the constructor.
I run the code below
var connectionString="Data Source=MyFooServer.myDomaion.com;Initial Catalog=FooDb;Integrated Security=True; MultipleActiveResultSets=true";
using (var con = new SqlConnection(connectionString))
{
var q = "SELECT COUNT(*) FROM Pizza";
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = q;
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
reader = cmd.ExecuteReader();
con.Close();
}
from 2 different places:
1) LinqPad
2) A Console application in Visual Studio 2010
LinqPad works fine. No exceptions.
But the same code throws an SQL exception: "The target principal name is incorrect. Cannot generate SSPI context."
QUESTION: Why I can connect to my database without any problem from LinqPad but not from the console application even tough I run the same code?
Rebooting my machine helped... No idea what was the root cause of this behavior tough.
Try to use SQL username and password instead of Windows Inegrated Security.
var connctionString="Data Source=MyFooServer.myDomain.com;Initial Catalog=FooDb;Uid=Username; pwd=password"
I'm quite used to using c# with SQL server. I have no idea why a simple statement would fail to insert data. My code is as follows:
query = "INSERT INTO MCDPhoneNumber ([MCDID],[PhoneNumber])" +
"VALUES("+maxid+", '"+tel+"')";
SqlConnection conn = new SqlConnection("Data Source=source; ...");
SqlCommand newCommand = new SqlCommand(query, conn);
int success= myCommand.ExecuteNonQuery();
if (success!= 1)
{
MessageBox.Show("It didn't insert anything:" + query);
}
First of all let me tell that I know that I should use parameters for data and I initially did, but when it failed I tried a simple query and it still fails. For addition I can tell that I have a similar insert just before that one in another table and it works. What's funnier is that when I copy paste query to SQL Server Management Studio it works. It also doesn't report any error in process.
====================== Edit ===============================
If you wish to use old command object (i.e. myCommand) then use following code instead of creating a new command(newCommand)
myCommand.CommandText = query;
myCommand.CommandType = System.Data.CommandType.Text;
And then execute it
you are binding query with newCommand and executing myCommand.
====================== Edit ===============================
SqlCommand newCommand = new SqlCommand(query, conn);
here you have defined newCommand for SQLCOMMAND object
int success= myCommand.ExecuteNonQuery();
and you are accessing it as myCommand
And moreover i think you are not opening connection
First of all, you define your command as newCommand but you executing your myCommand.
You should always use parameterized queries for your sql queries. This kind of string concatenations are open for SQL Injection attacks.
query = "INSERT INTO MCDPhoneNumber (MCDID, PhoneNumber) VALUES(#maxid, #tel)";
using(SqlConnection conn = new SqlConnection("Data Source=source; Initial Catalog=base; Integrated Security = true"))
{
SqlCommand newCommand = new SqlCommand(query, conn);
conn.Open();
newCommand.Parameters.AddWithValue("#maxid", maxid);
newCommand.Parameters.AddWithValue("#tel", tel);
int success= newCommand.ExecuteNonQuery();
if (success != 1)
{
MessageBox.Show("It didn't insert shit:" + query);
}
}
And please be more polite about your error messages :)
When I tried to add a connection it is showing the following error as shown in the attachment. “Unable to open the physical file. Access is Denied” .
When I searched about it, it suggest for adding the SQL Server’s account to the folder. Then, using the following query I found that the account is “LocalSystem”. When I tried to add “LocalSystem” to ACL of the folder, such an account is not available. How do we resolve it and add the connection to DBML?
Note: When I used DataReader with the database name in a C# program, it worked well.
Query Used:
declare #sqlser varchar(20)
EXEC master..xp_regread #rootkey='HKEY_LOCAL_MACHINE',
#key='SYSTEM\CurrentControlSet\Services\MSSQLSERVER',
#value_name='objectname', #value=#sqlser OUTPUT
SELECT convert(varchar(30),#sqlser)
Working C# Program:
SqlDataReader rdr = null;
SqlConnection con = null;
SqlCommand cmd = null;
try
{
// Open connection to the database
string ConnectionString = "server=D088DTRV;integrated security=true; database=BankAccount";
con = new SqlConnection(ConnectionString);
con.Open();
string CommandText = "SELECT * FROM Account";
cmd = new SqlCommand(CommandText);
cmd.Connection = con;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string test = rdr["AccountType"].ToString();
}
}
The problem was related to Data Connections.
In the advanced window, when I checked, it was trying for ./SQLExpress. I modified it with ".".
I restarted the machine. I also stopped the SQLExpress in the services.msc
Data Source=.;AttachDbFilename=C:\DevTEST\Databases\LibraryReservationSystem.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True