window service and sqlserver connection - sql-server

i have a project in window service, when i insert the following code in Onstart() event and debug it manually then database is inserted successfully, but when i create exe file of this project and started it in task manager then does nothing...i mean it didnt save any thing to database.
try
{
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=testing;Integrated Security=True");
SqlDataAdapter adp = new SqlDataAdapter();
cn.Open();
adp.InsertCommand = new SqlCommand("insert into testing1 values(1)", cn);
adp.InsertCommand.ExecuteNonQuery();
cn.Close();
}
catch { }

As the title of your post states "Windows service", I assume your program is running as a service. You are using integrated security, according to your connection string. Check if the account under which this runs has the rights to login to database server, and has the right to execute the insert.
You could of course also change to a fix database user account if your database is configured to allow that and there is one configured.
Edit
I also would suggest instead of an empty catch() clause, you print out/save to a log file the error message and stack trace to help diagnose the issue.

Related

Connection String generated by VS doesn't work, and any variation of it

I'm deploying a web application using IIS and ASP.NET CORE.
I setup a "appsetting.json" file that include a connection string to sql server.
So far, any variation I've tried didn't work.
The strange thing about it, is that it works perfectly on a my local machine, but when I deploy it and send an HTTPPost, log file says there's an error using connection to database on server.
Well, I tried all variations I could think of.
Current connection string generated by Visual Studio is :
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Swap;Integrated
Security=True;Connect Timeout=30;Encrypt=False;
TrustServerCertificate=False;
ApplicationIntent=ReadWrite;MultiSubnetFailover=False
I've tried changing the "Integrated Security" to False.
I've tried to replace it with User ID and password (of "sa" user).
I've tried adding a "Initial Catalog" property and set it to my database.
I'm preety sure the startup of the app is fine, because when I try to send a GET request to the main page, everything seems fine.
When I send a POST request and asks the DBcontext to Add and SaveChanges, it shows this error :
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
An error occurred using the connection to database 'Swap' on server
'(localdb)\MSSQLLocalDB'.
This is the function that I tried to send a HTTPPost request to:
byte[] j = new byte[(int)Request.ContentLength];
Request.Body.Read(j, 0, (int)Request.ContentLength);
string str = Encoding.ASCII.GetString(j);
TokenSet tokenSet = new TokenSet {Token = str };
sqlTokensetData.Add<TokenSet>(tokenSet);
sqlTokensetData.SaveChanges();
HttpClient notificationSender = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,
"https://fcm.googleapis.com/fcm/send");
request.Headers.TryAddWithoutValidation("Authorization", "key="
<somekey>);
request.Headers.TryAddWithoutValidation("Sender", "id=<id>");
Message pushNotification = new Message(new string[] { str }, "Success!"
<somestring>);
request.Content = new
StringContent(JsonConvert.SerializeObject(pushNotification)
,Encoding.UTF8,"application/json");
HttpResponseMessage output = await notificationSender.SendAsync(request);
Log file error:
https://anotepad.com/notes/9a8jxa
I hope that the "str" string will be inserted to the database.
Thank you.
Well, Basicly, Thanks to the comments above I've managed to solve it.
What you need to do if you come by the same error:
1.Download SQL Server Express -
https://www.microsoft.com/en-us/sql-server/sql-server-editions-express as said above.
and configure the SQL Server however you see fit.
2.Configure sa user, set password and enable it.
3. If SQL Authentication doesn't work, then in Microsoft SQL Server Management Studio -> Right-click the server -> Properties -> Server Authentication -> Change to SQL Server and Windows Authentication
4. Change connection string to :
Data Source=;Initial Catalog=User ID=sa;
Password=;
Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;
ApplicationIntent=ReadWrite;MultiSubnetFailover=False
It worked for me.

Program won't connect to SQL Server

Update: This is fixed thanks to some great help here. If you're having similar issues do the following:
Enable ALL exceptions before running
Figure out the exact error you're getting when trying to connect
Make sure that all users on SQL side have a user assigned to a login for that specific database
I've got a very nice program I've made that I'm ready to start pushing out for testing. The problem is that when I coded all of this I simply used the Integrated Security which uses my windows login to connect to the SQL Server. That worked fine as I'm a sysadmin on that whole server, including the database in question.
Now I'm ready to push this out to other users and I need to change the code to either use my login for all users (hard coded to the connection string) or use a new login specifically for that database.
I've used the following connection string and it won't work! I've also added the server to the data connections section of the server explorer but I guess I don't know how to tell the program to use that connection in my code.
I've obfuscated the password in the code below but it's written out in my code. No errors or anything when running - it just doesn't connect or pull data.
Thoughts? Thanks!
Dim strSQLConn As String = ("Server=Hertz1455;Database=AbsenceApplication;User ID=hac0421;Password=********")
Update - hertz1455 is the server name, there isn't a port that I need to use. Below is the rest of the code for when the program starts. I've also commented on some answers with the error I'm getting.
Dim strSQLConn As String = "Fleet_PTO.My.MySettings.AbsenceApplicationConnectionString"
Dim strQuery As String
Dim sqlSQLCon As SqlConnection
sqlSQLCon = New SqlConnection(strSQLConn)
Dim cmd As SqlCommand = New SqlCommand("SELECT person FROM tblSupervisor", sqlSQLCon)
sqlSQLCon.Open()
Dim myDA As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim myDataTable As DataTable = New DataTable
myDA.Fill(myDataTable)
sqlSQLCon.Close()
When I change the strSqlConn to the string below, everything works just fine.
Dim strSQLConn As String = ("Data Source=Hertz1455;Initial Catalog=AbsenceApplication;Integrated Security=True")
We can only guess since the question is a bit unclear without any exceptions or warning messages.
Try this:
Create a new text file anywhere. (say Desktop)
Rename the extension to udl and open the file.
You should be seeing window.
Test your connection, see if you can connect.
Lat94 might be correct with the Server=Hertz:1455 part although it's not the default MSSQL port.
Also check your server's firewall, it might be blocking the connection request. You might be getting an exception (like connection forcefully rejected) but it might not be popping up. Check exception settings, enable everything since you find a relative clue.
Note:
Dear future viewer, please follow the comments.
Perhaps you should add the driver you're using in order to get it done, like:
Dim strSQLConn As String = ("Server=SQLOLEDB;Server=Hertz1455;Database=AbsenceApplication;User ID=hac0421;Password=********")
Is "1455 at Server=Hertz1455 the port number? Shouldn't it be Server=Hertz:1455 in that case?
Check this link for more info. It is in C#, but it will not be a problem.

strange azure sql database connection issue

I got some rather strange sql database connection issue.
We have a VM that is hosted on azure and installed sql server on it.
Randomly it throws
could not open a connection to SQL Server(53)
However, the exception was not thrown fromconn.Open(), but from the place I read the Sql Data reader. The problem will last like 5-10 minutes and then disappear for every long time (e.g. days).
using (SqlConnection conn = new SqlConnection(this.ConnStr))
{
conn.Open();
InsrumentName insrument = new InsrumentName();
using (SqlCommand cmd = new SqlCommand("WF_CHART_GETNAME", conn))
{
SqlParameter para = new SqlParameter("#code", SqlDbType.VarChar, 500);
para.Value = code;
cmd.Parameters.Add(para);
cmd.CommandType = CommandType.StoredProcedure;
var reader = cmd.ExecuteReader();
while (reader.Read()) --------------- Could not open a connection to SQL Server 53 thrown here
{
Do something
}
return insrument;
}
}
I had a look of the VM and sql server log, but couldn't find anything remotely close. Anyone gets some idea?
When a pooled connection is reused, the connection error won't be raised until a query is executed on the connection. Open just returns an unused connection from the pool.
Error 53 (gleaned from the command NET HELPMSG 53) is "The network path was not found." That suggests a name resolution error which seems to be intermittent in your case.
Next time this happens, try to PING the server from the client using the same name as specified in the connection string.

Connect To SQL From CRM Dynamics 2011 Plugin

Hi All I posted a question earlier regarding, how to set an active contract to draft, but doing my research I found out it can either been done going straight into SQL doing the update or do it by copying the contract and then make an update. I had to go for option one. I'm trying to access my database and update the table, but get a SQL generic error from the plugin. My code to access the database from the plugin (I usually use Entity Framework to connect):
string strConn = "Data Source=serverName;Initial Catalog=DatabaseName;IntegratedSecurity=SSPI";
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = strConn;
connection.Open();
command.Connection = connection;
command.CommandText = "Update ContractBase set StateCode = 0,StatusCode = 1 "
+ "where ContractId = ACC70D43-DEBA-E111-8610-00155D041E80";
command.ExecuteNonQuery();
connection.Close();
Is there anything else I need to consider when I connect to the database from the plugin? Thanks in advance.
Would the SetStateRequest message not be the appropriate way of setting the state and status? or am I missing something?
I am not sure if this is too late but you can create a SSIS package that stores CRM data in to SQL table. Create a simple plugin that on create or update fires of this SSIS package.
You will have to run this plugin with none isolation mode as the sandbox isolation will not allow file access (package).

Why does sqlConnection.Close() not close the login?

We have unit tests to test that our database install and uninstall features successfully work.
The unit tests use the SqlClient.SqlConnection class to check the database contents before, during and after.
Our problem is that after using SqlClient.SqlConnection, the drop login part of the uninstall fails because it claims that a user is currently logged in. Even though we have called SqlConnection.Close(), the login seems to be still open.
Our code looks a little like this:
InstallTables(); // function uses smo to create tables in a database.
string connString = CreateLogin("userName", "password"); // create login with smo
// Test the returned connection string connects to the database
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
//test code to read the DB version out of a table
//Dispose calls con.Close() - I have also tried calling it explicitly
}
DropTables(); // uses smo to drop tables from the database
DropLogin("userName", "password"); // uses smo to drop the login
The DropLogin fails with the following exception:
System.Data.SqlClient.SqlException: Could not drop login 'engageSecurity_unittest_129418264074692569' as the user is currently logged in.
If I remove all the SqlConnection code until after the DropLogin, then everything runs fine.
Does anyone know why the user is not logged out when I call SqlConnection.Close() ?
Is this something to do with connection pooling?
Unless you're explicitly disabling Connection Pooling in your connection string, my guess is that even though you're disposing the connection it is still alive in the Connection Pool (in case you decide to re-use it):
SQL Server Connection Pooling (ADO.NET)
Try disabling Connection Pooling (by adding Pooling=false; in your connection string) and see what happens.
Alternatives to Pooling=false are SqlConnection.ClearPool and SqlConnection.ClearAllPools Method.

Resources