Detecting SQL Server reboot - c#

My c# console app runs on an different machine than my SQL Server 2014. I use ado.net to connect to it. How can I detect if the sql server automatically reboots after installing windows updates? On my client application I use SystemEvents_SessionEnding but this does not help me.
I read about connection resiliency, but this seems also not to solve this problem.
Is there a specific ado.net event I can capture? Creating an app on the server sending UDP is not my prefered solution, aswell I dont want to use ping etc.
I'm really looking for something like an event to react on.
e.g. the notification services: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlnotificationinfo(v=vs.110).aspx
Thanks!

If you want to see if the server is down or not you can use Ping Class.
using System.Net.NetworkInformation;
var ping = new Ping();
var reply = ping.Send("SqlServerIP");
if (reply.Status == IPStatus.Success)
{
//server is available
}
else
{
//server is down
}

Related

Can't connect with mysql server using c# at work

Why i failed to connect to a free cloud mysql DB using C# connector from Nuget in my work office PC while i can connect just fine to the same server using mysql CLI tool?
The message i get when i fail to connect is "Connect Timeout expired.".
I also tried on my PC at home and i can connect just fine using exactly the same C# code.
Mysql CLI tool also work from home.
Could it be a firewall or other security measure in my work company network? Why it does not block the mysql CLI tool?
I also tried with a localhost mysql (using mysqld on port 51255) at work.
I managed to connect using mysql CLI tool but got the same error as before on c# code.
EDIT1 - Code included
EDIT2 - localhost attempt
private async Task<string> ConnectDB()
{
MySqlConnectionStringBuilder dbinfo = new MySqlConnectionStringBuilder
{
Server = "******",
Port = ****,
Database = "*****",
UserID = "*****",
Password = "*****",
};
using(MySqlConnection connection = new MySqlConnection(dbinfo.ConnectionString))
{
try
{
await connection.OpenAsync();
}
catch (MySqlException error)
{
message = error.Message;
}
if (connection.State == ConnectionState.Open)
{
message = "Success!";
}
}
return message;
}
We see the same C# code works at home, but not at the office. Therefore it's not the code; it must be something with the environment at the office. But you can connect at the office via the command line tools, so it's also not the corporate firewall, which would have a very hard time telling the the difference between the two.
What's left is something on the local PC at work. The local OS firewall and antivirus software both come to mind, and of the two the antivirus software sounds more suspect to me. One other option is DNS, where the DNS service at the office is resolving the host name for the database differently. But without more info this is just a guess. I suggest adding a lot more logging; right now we don't even know the full error message.
As an additional note, it's not common and considered very poor practice to directly expose a database to the internet. Additionally, the application should be well-connected to the database. The definition for "well-connected" has changed over the years, but "public internet" is not going to count. Typically, if you most host the database in another location you will have a web API endpoint in front of the database, where the server for this API can be in the same location as the DB and therefore well-connected.

How to determine what kind of OPC server and read its item

I was provide a link of OPC server: http://192.168.2.5:54354 and was asked for read an Item value.
I am new to OPC and I assumed that my server is OPC XML-DA but when I try the sample code, it work.
But when I replace my server URL and Item name, it not work, the server address seem to be missing some part
var client = new EasyDAClient();
DAVtqResult[] vtqResults = client.ReadMultipleItems(
new ServerDescriptor { UrlString = "http://opcxml.demo-this.com/XmlDaSampleServer/Service.asmx" },
new DAItemDescriptor[]
{
"Dynamic/Analog Types/Double",
"Dynamic/Analog Types/Double[]",
"Dynamic/Analog Types/Int",
"SomeUnknownItem"
});
This one work but did not work with my Server URL: http://192.168.2.5:54354
I am not sure what /XmlDaSampleServer/Service.asmx means but I am able to connect to my sever using https://www.kassl.de/opc/explorer.shtml
Are you sure the server is XML-DA? Very few servers use this protocol in my experience. It is usually OPC DA (OPC Classic) or OPC UA.
Is there any security on the server like username and password?
From my experience, you need to be able to establish a connection with an existing client before writing any code. There could be a network or firewall issue. It appears that the server is on your local network. Can you connect to it with the Kassl client from the same server? OPC DA relies on the COM/DCOM components for communication that tend to have many issues with remote connections and firewalls.
Try the following steps:
Ping the server and make sure it replies.
Install an OPC client like Kassl or Kepware on the same Windows machine as the server and see if it can connect.
If it can, disable firewall, antivirus, etc. and see if you can connect remotely.
Check if there are any port-forwarding that needs to be done. You may want to use Wireshark to see what is happening with the data.

SQL Server Connection Issue - I can connect but other users can't

[edit] so not sure what happened, but we ended up resetting the server and turning off/on TCP/IP and Named Pipes and after a restart and updating the settings everything started working again. weirdest thing. anyways thanks for the help guys.
I'm building a C# WPF application for my job, and I'm getting a weird problem that I've been trying to figure out for the past week. The application connects to the server and imports several tables on start up. So I built it out and was testing it with no issues, but when i pass it to our testers, and everyone is getting the following errors:
Provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server
The users are able to connect to the server through other methods (SSMS/Excel VBA), but just through the application it won't work.
I've checked the following:
Remote connections enabled
TCP/IP connections enabled
Firewall settings are the exact same across all users (me included)
application is compiled as 32 bit (saw this in another thread)
We're using SQL Server 2008 and I've tried several connection strings/methods.
below is the code I'm using to connect:
public void Open_DB_Conn(string Connection_Str)
{
try
{
Sql_Conn = new SqlConnection(Conn_Str);
Sql_Conn.Open();
}
catch (Exception e)
{
MessageBox.Show(string.Format("Error Message:{0} Conn String: {1}",e.Message,Conn_Str));
}
}
Below is my connection string (this is just one of many iterations I've used trying to get it working):
Data Source=IP Address;Initial Catalog=DB_Name;User ID=LOGIN;Password=PWD
Anyone know why I would be the only one able to get it to work and that the users are able to login to the server using other applications without a problem? They use it for logging their excel VBA scripts and there aren't any issues there.
Try this - it may be your answer
"The error is reported by client library. While your server is listeing on remote TCP, client will still try TCP and NP connection in order. So the error client behavior is expected. From what you have described, I believe that even though you enabled the remote TCP connection on the XPSP2 machine, you didn't make the TCP listening port an exception of XPSP2 personal firewall. You should follow steps below to resolve this issue.
check the SQL Server Errorlog to make sure SQL Server is now listening on TCP/IP and confirm which port it is listening on. Usually 1433. In the Errorlog, you will see several lines that discuss what SQL Server is listening on. Below is an example:
2006-01-04 01:41:07.65 server SQL server listening on 10.254.1.150: 1433. <--Shows the IP Address and the port.
2006-01-04 01:41:07.65 server SQL server listening on 127.0.0.1: 1433. <--Shows another IP Address and the port.
2006-01-04 01:41:07.69 server SQL server listening on TCP, Shared Memory, Named Pipes.
2006-01-04 01:41:07.69 server SQL Server is ready for client connections
2, Make sure on Windows XP that the firewall is not blocking that port.
3, go to your client machine and run the client network configuration tool (cliconfg.exe) Make sure TCP/IP is enabled, click properties and make sure the port number is the same one as SQL Server is listening on. Here you can enable NP or disable client NP as well.
Once both the client and the server are using TCP/IP with the same port number and the firewall on server machines is not blocked, you should be able to connect.
Hope this helps."
(Ref: http://social.technet.microsoft.com/Forums/sqlserver/en-US/c488cf76-2515-440f-b3f8-9cfad689c5b6/named-pipes-provider-error-40-could-not-open-a-connection-to-sql-server?forum=sqldataaccess)
You have to configured your SQl server so that other IP can connect it for that you have to gone through mentioned link
Configure SQL server
What authentication are you using for the SQL Server? Windows Authentication or SQL Server authentication? My suggestion is to first turn on SQL Server authentication and use the sa\password to connect to the server. If you are successful, then ask the others (users of your application) to try with the same connection string. Let me know what you find out.
Be sure that the port specified in:
Data Source="IPAddress,port";Initial Catalog=DB_Name;User ID=LOGIN;Password=PWD
matches the port on your SQL Server. You can check that by going on SQL Server COnfiguration Manager and viewing TCP/IP properties.
EDIT :
It is also the case the port defined by blocked by an external firewall. And the rest Applications use other ports. Try to find out which port you can use (if indeed the are restrictions to your network)
Make sure your SQL Server instance is properly configured to use TCP using Sql Server Configuration Manager.
It is by default disabled in SQL Express, as show below.
I'd like to know more about your "Sql_Conn" class.
Also, try using this for your connection.
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
string cmdText = "SELECT name FROM sys.tables"
cmd.CommandText = cmdText;
cmd.ExecuteNonQuery();
}
}

C# Custom Remote Desktop Client using RDP 8.0

I have searched MSDN forum for this, but it seems everyone(i think) suggests to revert to RDP 7.x (uninstall MS Update KB2592687).
I have an custom Remote Desktop client written in C#/WPF,the Remote Desktop ActiveX control is hosted inside a WindowsFormsHost control.
The app works well prior to update RDP 8.0 (MS Update KB2592687). If i uninstall the MS update(revert to RDP 7.1), the app works.
My RDP Client is used to connect to Virtualbox VRDP (Virtualbox 4.2.x), no authentication needed(Null). With RDP 8.0 installed, the Windows Remote Desktop Client(mstsc.exe) connects just fine, with much better responsiveness(RDP 8.0 enhancements); but my custom RD Client is unable to connect.
Upon further investigation, my custom RDP Client is not throwing any exceptions or firing the OnConnecting and OnLogonError or most of the other events.
What's odd is, it is ONLY firing these two events (in order)
OnAuthenticationWarningDisplayed
OnAuthenticationWarningDismissed
I also tested with RawCap(http://www.netresec.com/?page=RawCap) to see if my custom RDP Client is sending packets to Virtualbox VRDP prior to those events. Surprisingly, it's not even sending packets. (MS RD Client - mstsc.exe works fine.)
So it boils down to these events/method calls on my custom RDP Client, and unfortunately I'm stuck.
(Code is shortened for brevity)
AxMSTSCLib.AxMsRdpClient8 rdp = new AxMSTSCLib.AxMsRdpClient8();
rdp.OnAuthenticationWarningDisplayed+=new EventHandler(rdp_OnAuthenticationWarningDisplayed);
rdp.OnAuthenticationWarningDismissed+=new EventHandler(rdp_OnAuthenticationWarningDismissed);
rdp.Server = server;
rdp.AdvancedSettings8.RDPPort = 5050;
//No username/password since Virtualbox RDP authentication is set to *null*
//MS RD Client connects just fine to Virtualbox RDP without username/password
try
{
rdp.Connect();
}
catch (Exception ex)
{
}
putting a breakpoint on OnAuthenticationWarningDisplayed and OnAuthenticationWarningDismissed confirms both events are fired after Connect() method.
I suspect the ActiveX control, after the Connect() method is called, is trying to show a dialogbox(??); but i can't seem to figure out.
Has anyone else done some custom client using RDP 8.0? What are the prerequisites to have it working(code).
Many thanks! Would greatly appreciate it.
Solved this problem!
Just try to use AxMSTSCLib.AxMsRdpClient8NotSafeForScripting instead of AxMSTSCLib.AxMsRdpClient8
Here's working code (Delphi):
rdp:TMsRdpClient8NotSafeForScripting; // ***Instead of TMsRdpClient8 (!!!)***
...
if rdp.Connected<>0 then rdp.Disconnect;
rdp.Server:='192.168.1.1';
rdp.UserName:='User';
rdp.AdvancedSettings8.ClearTextPassword:='Password';
rdp.AdvancedSettings8.AuthenticationLevel:=2;
rdp.AdvancedSettings8.EnableCredSspSupport:=true;
rdp.AdvancedSettings8.NegotiateSecurityLayer:=false;
rdp.AdvancedSettings8.RelativeMouseMode:=true;
rdp.AdvancedSettings.BitmapPeristence:=1;
rdp.AdvancedSettings.Compress:=1;
rdp.AdvancedSettings8.SmartSizing:=true;
rdp.DesktopHeight:= Screen.Height;
rdp.DesktopWidth:= Screen.Width;
rdp.FullScreen:=true;
rdp.ColorDepth:= 15;
rdp.AdvancedSettings8.RedirectDrives:=false;
rdp.AdvancedSettings8.RedirectPrinters:=false;
rdp.AdvancedSettings8.RedirectClipboard:=true;
rdp.AdvancedSettings8.RedirectSmartCards:=false;
rdp.Connect;
P.S. And do not use the following property:
rdp.AdvancedSettings8.AuthenticationServiceClass

What is the best approach for an asynchronous callback/event from gSOAP server?

I am designing a webservice interface for use between a Windows CE device and a PC. The Windows CE device is server and the PC is client.
I have decided to use the gSOAP library to implement the server and I am using .NET/C# for the client. I have followed the approach described here and everything is working well.
My question is about how to best implement an asynchronous callback/event from the server to the client. I can think of two methods:
Continuously polling the server for active events
A blocking method that keeps the connection open until an event occurs
I have currently chosen option 2 and it seems to be working well. I use an asynchronous method in the client and therefore get a callback when the method completes, i.e. when an event occurs on the Windows CE device. I then immediately call the same method again so it is ready for the next event.
Example server method (no error handling):
int ns__WaitForEvent(struct soap* soap, int *eventId)
{
WaitForSingleObject(hMyServerEvent, INFINITE);
*eventId = GetCurrentEventId();
return SOAP_OK;
}
Example client (no error handling):
private void SubscribeToServerEvents()
{
var server = new MyMethods.ServicePortTypeClient(
new BasicHttpBinding(),
new EndpointAddress(myIpAddress));
AsyncCallback cb = this.Callback;
server.BeginWaitForEvent(cb, server);
}
private void Callback(IAsyncResult ar)
{
var server = (MyMethods.ServicePortType)ar.AsyncState;
var result = server.EndWaitForEvent(ar);
// Do stuff with result
}
The server must be multi-threaded for this approach to work, and the number of clients should be limited so the server does not have a large number of threads hanging with blocking methods. In my case none of these issues are a problem - it is simple to setup a multi-threaded server using gSOAP and there will only ever be one client (which I control) attached to each server.
Are there any significant disadvantages to this approach? Can you suggest a better solution?
I suggest to turn the WinCE device into a webclient instead of a webserver and the PC into a server, that will be notified on something happens on the client. It is more natural this approach, you can still use gSoap for a soap client. On the PC you should have a web-server like Apache or IIS installed, or you could make a Windows server that will host an embedded light webserver.

Categories

Resources