I want to ping remote host and get his status I created function like this:
public async Task<Boolean> Connect_Test(string ip,int port)
{
var isReachable = await CrossConnectivity.Current.IsReachable(ip, port);
if (isReachable == true)
{
return true;
}
else
{
return false;
}
}
I call this function like this:
var connect = Connect_Test(adres_ip, 4210).Result;
if (connect==true)
{
//Alert is reachable
}
else
{
//Alert not reachable
}
My app freezes after executing this code and don't return value of of the remote host status.
I used wrong method from connectivity plugin the correct one is IsRemoteReachable. Problem is solved.
Related
I want to get an alert when a service (grafana or influxdb) in an Azure virtual machine (Ubuntu 16.04) has stopped. I'd like to use c# to connect to the VM and check the status of grafana and influxdb services. Can anyone share a code sample that implements this?
Both services provide health endpoints that can be used to check their status from a remote server. There's no need to open a remote shell connection. In fact, it would be impossible to monitor large server farms if one had to SSH to each one.
In the simplest case, and ignoring networking issues, one can simply hit the health endpoints to check the status of both services. A rough implementation could look like this :
public async Task<bool> CheckBoth()
{
var client = new HttpClient
{
Timeout = TimeSpan.FromSeconds(30)
};
const string grafanaHealthUrl = "https://myGrafanaURL/api/health";
const string influxPingUrl = "https://myInfluxURL/ping";
var (grafanaOK, grafanaError) = await CheckAsync(client, grafanaHealthUrl,
HttpStatusCode.OK, "Grafana error");
var (influxOK, influxError) = await CheckAsync(client, influxPingUrl,
HttpStatusCode.NoContent,"InfluxDB error");
if (!influxOK || !grafanaOK)
{
//Do something with the errors
return false;
}
return true;
}
public async Task<(bool ok, string result)> CheckAsync(HttpClient client,
string healthUrl,
HttpStatusCode expected,
string errorMessage)
{
try
{
var status = await client.GetAsync(healthUrl);
if (status.StatusCode != expected)
{
//Failure message, get it and log it
var statusBody = await status.Content.ReadAsStringAsync();
//Possibly log it ....
return (ok: false, result: $"{errorMessage}: {statusBody}");
}
}
catch (TaskCanceledException)
{
return (ok: false, result: $"{errorMessage}: Timeout");
}
return (ok: true, "");
}
Perhaps a better solution would be to use Azure Monitor to ping the health URLs periodically and send an alert if they are down.
Here is something you can use to connect to Azure linux using SSH in c#
using (var client = new SshClient("my-vm.cloudapp.net", 22, "username", "password​"))
{
client.Connect();
Console.WriteLine("it worked!");
client.Disconnect();
Console.ReadLine();
}
Usually SSH server only allow public key auth or other two factor auth.
Change your /etc/ssh/sshd_configuncomment #PasswordAuthentication yes
# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication yes
Later you can poll for installed services.
Also for an alternative solution, you can deploy a rest api in your linux VM to check the status of your service and the call it from C# httpclient for the status.
Hope it helps
Using PKCS11Interop on Safenet HSMs, I got this error
"Method C_OpenSession returned 2147484548"
the error, in my documentation, is CKR_SMS_ERROR: "General error from secure messaging system - probably caused by HSM failure or network failure".
This confirm the problem it happens when the connectivity is lacking.
The problem is when this happens, the service isn't able to resume the communication when the connectivity is back, until I restart manually the service managing the HSM access.
When the service starts, I call this:
private Pkcs11 _pkcs11 = null;
private Slot _slot = null;
private Session _session = null;
public async void InitPkcs11()
{
try
{
_pkcs11 = new Pkcs11(pathCryptoki, Inter_Settings.AppType);
_slot = Inter_Helpers.GetUsableSlot(_pkcs11, nSlot);
_session = _slot.OpenSession(SessionType.ReadOnly);
_session.Login(CKU.CKU_USER, Inter_Settings.NormalUserPin);
}
catch (Exception e)
{
...
}
}
When I have to use the HSM, I call something like:
using (var LocalSession = _slot.OpenSession(SessionType.ReadOnly))
{
...
}
And, when I fail the communication due to a connectivity lack, I call a function to reset the connection and try to change the slot:
private bool switching = false;
public async void SwitchSlot()
{
try
{
if (!switching)
{
switching = true;
if (nSlot == 0)
{
nSlot = 2;
}
else
{
nSlot = 0;
}
_session.Logout();
_slot.CloseAllSessions();
_pkcs11.Dispose();
InitPkcs11();
switching = false;
}
}
catch (Exception e)
{
...
}
}
But, this last snippet doens't work as expected: it tries to change the slot, but it fails always to communicate with the HSM (after a network down). If I restart the service manually (when the connectivity is back), it works like charms. So, I'm sure I'm doing something wrong in the SwitchSlot function, when I try to close the _session and open a new one.
Do you see any errors/misunderstoonding here?
I'm trying to get a Bluetooth socket connection up and running but for some reason my client will not connect.
More precisely I get an exception when I try to connect to the stream:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
All examples I found online didn't really solve my problem and I'm currently not really sure where the problem comes from.
The scanning and pairing works fine - I see that the Bluetooth device in question gets successfully paired.
I try to connect via first setting the Client and then call connect
Client Bluetooth name, address and pin are known:
public bool SetClient(String clientName, String btAddress, String pin)
{
bool retVal = false;
m_remoteBluetoothClient = new BluetoothDeviceInfo(BluetoothAddress.Parse(btAddress));
m_localBluetoothClient.SetPin(pin);
if (m_remoteBluetoothClient.Authenticated)
{
//m_localBluetoothClient.Authenticate = true;
retVal = true;
}
else
{
if (BluetoothSecurity.PairRequest(m_remoteBluetoothClient.DeviceAddress, pin))
{
retVal = true;
}
}
return retVal;
}
Then an async connect:
private void ClientConnectThread()
{
m_localBluetoothClient.BeginConnect(m_remoteBluetoothClient.DeviceAddress, BluetoothService.SerialPort, Connect, m_localBluetoothClient);
}
private void Connect(IAsyncResult result)
{
if (result.IsCompleted)
{
m_localBluetoothClient.EndConnect(result);
mBtStream = m_localBluetoothClient.GetStream();
}
}
The locals m_localBluetoothEndpoint and m_localBluetoothClient are created like this although the Endpoint is more or less new (before I used BluetoothCLient without parameter):
m_localBluetoothEndpoint = new BluetoothEndPoint(BluetoothRadio.PrimaryRadio.LocalAddress, BluetoothService.SerialPort);
m_localBluetoothClient = new BluetoothClient(m_localBluetoothEndpoint);
I also tried to work with a Listener in case the remote devices wants to connect but the callback gets never called:
public void SetupListener()
{
var listener = new BluetoothListener(BluetoothService.SerialPort);
listener.Start();
listener.BeginAcceptBluetoothClient(this.BluetoothListenerAcceptClientCallbackTwo, listener);
}
Can anyone tell me if there is anything wrong with my connection approach above and how I can figure out why I get the exception mentioned above?
The exception gets thrown here:
m_localBluetoothClient.EndConnect(result);
A thing I also don't understand is that the SupportedServices call to the remoteCLient returned 0 guids - so the device did not list any Bluetooth services.
m_remoteBluetoothClient.InstalledServices()
Thank you
I have a project about going to a website. If the website cannot because of several reasons, such as not being connected to the Internet, wrong proxy ip, etc, the browser will show a page with text "You're not connected to a network". In this situation, I want to auto refresh the browser. How will the program detect that website can't be loaded?
Take a look at my below code:
public void exam()
{
var ie = new IE();
ie.GoTo("http://search.yahoo.com");
ie.WaitForComplete(5);
if (ie.ContainsText("You're not connected to a network"))
{
ie.Close();// or ie.Refresh()
}
}
It doesn't work.
Try testing to see if you can Ping the address first ... try using this
public bool CanConnect()
{
var ping = new Ping();
var reply = ping.Send("search.yahoo.com");
return reply.Status == IPStatus.Success;
}
or if you want to pass the address as a parameter:
public bool CanConnect(string addressToTest)
{
var ping = new Ping();
var reply = ping.Send(addressToTest);
return reply.Status == IPStatus.Success;
}
What's the best method to check if SQL server exists or not?
I'm trying Microsoft.SqlServer.Management.Smo.Server.PingSqlServerVersion()
and it works fine if server exists and available.
But it kinda pretty slow, if there is no such a server.
Is there any fast enough method to check without even defining user credentials (only the server name), if a server exists?
What do you recommend to use?
You could still use Microsoft.SqlServer.Management.Smo.Server.PingSqlServerVersion() but use it asynchronously. e.g. you could call it via a BackWorker class. The DoWork event would call Microsoft.SqlServer.Management.Smo.Server.PingSqlServerVersion(). The RunWorkerCompleted would just set a boolean variable to true. THat way you could fire it off, wait however long you wanted, check the boolean value and if it was not true then you would know that the SQL server had not responded yet and you could cancel the BackgroundWorker.
You could just use TcpClient class to query the server and check if a specific port is open, could be something like this:
using System.Net;
using System.Net.Sockets;
public bool CheckServerAvailablity(string serverIPAddress, int port)
{
try
{
IPHostEntry ipHostEntry = Dns.Resolve(serverIPAddress);
IPAddress ipAddress = ipHostEntry.AddressList[0];
TcpClient TcpClient = new TcpClient();
TcpClient.Connect(ipAddress , port);
TcpClient.Close();
return true;
}
catch
{
return false;
}
}
You could try and open a tcp socket to port 1433 (default sql port) with a short timeout and see if it responds.
This requires the SQL server to have the TCP/IP protocol enabled.
To add to Mikael's, you could also ping the host first, as that will respond the quickest if the server is down.
Of course, this all assumes that you are trying to get to a remote server over TCP/IP.
After using Ben Robinson's answer I came up with this and it works good for me.
I was using the connection string to open and then close a connection in a try block but when I ran on Windows 8.1 the exception was never caught and the program crashed.
public unsafe bool OdbcConnectionTest(string sConnectionString
, out int actualTimeMs)
{
DateTime dtme = DateTime.Now;
OdbcConnectionStringBuilder con;
Microsoft.SqlServer.Management.Smo.Server svr;
Microsoft.SqlServer.Management.Common.ServerVersion sVer;
Microsoft.SqlServer.Management.Smo.Database db;
try
{
con = new System.Data.Odbc.OdbcConnectionStringBuilder(sConnectionString);
object sServer;
if (con.TryGetValue("server", out sServer))
{
svr = new Microsoft.SqlServer.Management.Smo.Server((string)sServer);
if (svr != null)
{
sVer = svr.PingSqlServerVersion((string)sServer);
if (sVer != null)
{
object sDb;
if (con.TryGetValue("database", out sDb))
{
if (!String.IsNullOrWhiteSpace((string)sDb))
{
db = svr.Databases[(string)sDb];
if (db != null && db.IsAccessible)
{
TimeSpan ts = DateTime.Now - dtme;
actualTimeMs = (int)ts.TotalMilliseconds;
return true;
}
}
}
}
}
}
}
catch
{
actualTimeMs = -1;
return false;
}
actualTimeMs = -1;
return false;
}