Create a visual studio Windows Service application that performs SQL operations - c#

Alright, I am new to Windows Service applications. I am trying to create a Windows Service application using C# on Visual Studio 2012 that runs SQL statements. I was under the impression that we needed to enter a connection string in the web.config file for my SQL statements to communicate with the server. But there is no web.config file in a service application. How do I go about doing this? Any links to a tutorial or a tutorial in itself would be appreciated! I want to know the project structure and what I need to do for my application to work right.
Also, I have some SQL queries that need to run on multiple servers. The same queries run on 3 different servers. Does creating 3 connection strings and connecting to the 3 servers and running them the way to do it?

First of all, all applications have either a web.config or an app.config. If you are writing an MVC application or a Web Forms applications, then there is a web.config file. If you are writing a Windows service or a Windows Console or Desktop application, you'll have an app.config file instead.
Connecting to SQL Server is a pretty simple task. You just create a connection using SqlConnection. Next, you create a SqlCommand. Finally, you can execute your SQL query.
Here is an example:
public void DeleteRow()
{
using (var connection = new SqlConnection("your connection string here..."))
{
using (var command = new SqlCommand())
{
command.Connection = connection;
// Next command is your query.
command.CommandText = "DELETE FROM Customers WHERE CustomerId = 1";
command.CommandType = CommandType.Text;
connection.Open();
command.ExecuteNonQuery();
}
}
}
Use that first example if you are executing queries that return no data. If you need to return data, then use an example like this:
public void GetCustomer()
{
using (var connection = new SqlConnection("your connection string here..."))
{
using (var command = new SqlCommand())
{
SqlDataReader reader;
command.Connection = connection;
// Next command is your query.
command.CommandText = "SELECT * FROM Customers WHERE CustomerId = 1";
command.CommandType = CommandType.Text;
connection.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
}
}
}

Related

Cannot connect to SQL Server with Windows authentication from C#

I want to connect to SQL Server 2016 using Windows authentication.
I am using C# with this connection string
Server=192.168.1.12,14331;Database=master;Integrated Security=true;Timeout=30
or
Server=serversql\newinstance;Database=master;Integrated Security=true;Timeout=30
The error is a timeout connection.
When using connection with SQL Server authentication like this:
Server=192.168.1.12,14331;Database=master;User Id=***;Password=****;Timeout=30
everything is ok.
Source code C#
var constr = "<connection string>";
using (var connection = new SqlConnection(constr))
{
var command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = "SELECT 1";
command.CommandTimeout = 0;
connection.Open();
command.ExecuteNonQuery();
}
But when I am using SQL Server Management Studio to check connection to the SQL Server instance with Windows authentication, it is ok. Using alias or Ip address does not help the error.
I don't understand why I get this error ...
Help me please! Thanks you everyone!
UPDATE:
If I use connection 1 with IP and port, there is an error:
Login failed. The login is from an untrusted domain and cannot be used
with Windows
UPDATE:
Instance SQL installed on other PC the same network LAN with My PC.
I'm checked Log Viewer on PC install instance SQL but no record log.
I'm not sure it works for you, but you can try it:
SqlConnection cnn;
public connect(){
string strConnect = #"Data Source=192.168.1.12,14331;Network Library=DBMSSOCN;Initial Catalog=master;User ID=****;Password=*****";
cnn = new SqlConnection(strConnect);
try
{
cnn.Open();
}
catch(Exception)
{
// connect failed
}
}
public void ExeQuery(string query){
// query="select * from tblA"
SqlCommand sqlCmd = new SqlCommand(query,cnn);
sqlCmd.ExecuteNonQuery();
sql.Dispose();
}

How to connect SQLite with my C# application

i have a problem with making a local database into my c# project and creating it..
I tried first with making a Microsoft Sql Server but the problem is that i need to make app which should run on every pc. The app should input data from user , and collect it to the database, and on every start of program, the database should be filled with the leftover of earlier input.. What you suggest me to do?
First to connect your c# application with sqlite you should start with getting connection string
private static string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static string oldconnectionstring = Path.Combine(executableLocation, "YourDB.db");
private static string connectionString = "Data Source =" + oldconnectionstring.ToString();
After getting connection, to add your input to database follow below steps
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
//Open connection to DB
conn.Open();
//Query to be fired
string sql = "Your Query to insert rows";
//Executing the query
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
//Executing the query
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
//Close connection to DB
conn.Close();
}

Is there a way to get the connection string from a SQL DB then use that through the application?

I am just doing some research at the moment into this and would like to know if it's possible.
I have an application where someone logs in with a username/ I would like to have a table with all the company id's stored and depending on which one they log in using it will use a connection string from the DB for that company.
I am fully aware of how to do it with the web.config but want to minimise the information kept here because potentially we are talking of around 1,000 connection strings.
Sure create a table or modify an existing table.
CREATE TABLE Connection
(
Id INT IDENTITY NOT NULL PRIMARY KEY
,ConnectionString VARCHAR(100) NOT NULL
);
INSERT INTO Connection (ConnectionString)
VALUES ('Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;');
I would advise against storing passwords in the connection string when the contents of the table are unencrypted. Setup a domain account with Sql Server privileges to run your IIS app pool or Windows Service under.
const string Query = "SELECT ConnectionString FROM Connection WHERE Id = #Id";
public string GetConnectionString(int id)
{
using(var connection = GetConnection())
using(var command = new SqlCommand(Query, connection))
{
command.Parameters.AddWithValue("#Id", id);
connection.Open();
using(var reader = command.ExecuteReader())
{
if(reader.Read())
{
return Convert.ToString(reader["ConnectionString"]);
}
}
}
}
var connectionString = GetConnectionString(1);
using(var connection = new SqlConnection(connectionString))
{
//logic
}
Yes, this is possible.
Store the connection strings in your (main?) DB, retrieve them and use them when instantiating new DdConnections.
Most of the classes that inherit from DbConnection (SqlConnection, for example) have a constructor overload that takes a connection string.

Sql connetion doesn't open in windows service

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 =.......";

ADO.Net DataReader error: Already an Open DataReader

I am using C# + .Net 3.5 + VSTS 2008 + ADO.Net + SQL Server 2008. And I am sharing one single SQL Connection object (TestDBConnection variable in my below sample) within my application.
The exception I met with is, "There is already an open DataReader associated with this Command which must be closed first.." Any ideas what is wrong?
The patterns within my application which I am using are all like this, i.e. sharing the single db connection object TestDBConnection, and using the single TestDBConnection variable to create command on it and execute store procedure.
using (SqlCommand testCommand = new SqlCommand())
{
testCommand.Connection = TestDBConnection;
testCommand.CommandType = CommandType.StoredProcedure;
testCommand.CommandText = "prc_AddOrderStatus";
testCommand.Parameters.Add("#orderID", SqlDbType.NVarChar).Value = orderID;
testCommand.ExecuteNonQuery();
}
thanks in advance,
George
Don't share the connection, use connection pooling instead. If you are doing two things at the same time on the connection, you might want to look into MARS.
For a test add this to your connection string: ;MultipleActiveResultSets=True; and see if this "fixes" the error. A lot of people believe you should avoid using MARS, so this is something to consider.
using (sqlConnection theconnection = new sqlconnection(initialise it))
{
using (SqlCommand testCommand = new SqlCommand())
{
testCommand.Connection = theConnection
testCommand.CommandType = CommandType.StoredProcedure;
testCommand.CommandText = "prc_AddOrderStatus";
testCommand.Parameters.Add("#orderID", SqlDbType.NVarChar).Value = orderID;
testCommand.ExecuteNonQuery();
}
}
is the pattern that i use in multi threaded cases with no problems at all.
Incidently this is connection pooling.
George, is it possible that the exception is telling you the truth? Are there any other commands that you've started but not yet finished?

Categories